diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..452c78a055e72a6d04f1013d1a98fda33fdc449e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/__init__.py @@ -0,0 +1,71 @@ +from . import caching +from ._version import __version__ # noqa: F401 +from .callbacks import Callback +from .compression import available_compressions +from .core import get_fs_token_paths, open, open_files, open_local, url_to_fs +from .exceptions import FSTimeoutError +from .mapping import FSMap, get_mapper +from .registry import ( + available_protocols, + filesystem, + get_filesystem_class, + register_implementation, + registry, +) +from .spec import AbstractFileSystem + +__all__ = [ + "AbstractFileSystem", + "FSTimeoutError", + "FSMap", + "filesystem", + "register_implementation", + "get_filesystem_class", + "get_fs_token_paths", + "get_mapper", + "open", + "open_files", + "open_local", + "registry", + "caching", + "Callback", + "available_protocols", + "available_compressions", + "url_to_fs", +] + + +def process_entries(): + try: + from importlib.metadata import entry_points + except ImportError: + return + if entry_points is not None: + try: + eps = entry_points() + except TypeError: + pass # importlib-metadata < 0.8 + else: + if hasattr(eps, "select"): # Python 3.10+ / importlib_metadata >= 3.9.0 + specs = eps.select(group="fsspec.specs") + else: + specs = eps.get("fsspec.specs", []) + registered_names = {} + for spec in specs: + err_msg = f"Unable to load filesystem from {spec}" + name = spec.name + if name in registered_names: + continue + registered_names[name] = True + register_implementation( + name, + spec.value.replace(":", "."), + errtxt=err_msg, + # We take our implementations as the ones to overload with if + # for some reason we encounter some, may be the same, already + # registered + clobber=True, + ) + + +process_entries() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/_version.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..668eaa38c6505a9898469a23ff6c19dd63947148 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/_version.py @@ -0,0 +1,34 @@ +# file generated by setuptools-scm +# don't change, don't track in version control + +__all__ = [ + "__version__", + "__version_tuple__", + "version", + "version_tuple", + "__commit_id__", + "commit_id", +] + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import Tuple + from typing import Union + + VERSION_TUPLE = Tuple[Union[int, str], ...] + COMMIT_ID = Union[str, None] +else: + VERSION_TUPLE = object + COMMIT_ID = object + +version: str +__version__: str +__version_tuple__: VERSION_TUPLE +version_tuple: VERSION_TUPLE +commit_id: COMMIT_ID +__commit_id__: COMMIT_ID + +__version__ = version = '2025.9.0' +__version_tuple__ = version_tuple = (2025, 9, 0) + +__commit_id__ = commit_id = None diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/archive.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/archive.py new file mode 100644 index 0000000000000000000000000000000000000000..13a4da8df7c9405297cdd7d37476be2f725b2f57 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/archive.py @@ -0,0 +1,75 @@ +import operator + +from fsspec import AbstractFileSystem +from fsspec.utils import tokenize + + +class AbstractArchiveFileSystem(AbstractFileSystem): + """ + A generic superclass for implementing Archive-based filesystems. + + Currently, it is shared amongst + :class:`~fsspec.implementations.zip.ZipFileSystem`, + :class:`~fsspec.implementations.libarchive.LibArchiveFileSystem` and + :class:`~fsspec.implementations.tar.TarFileSystem`. + """ + + def __str__(self): + return f"" + + __repr__ = __str__ + + def ukey(self, path): + return tokenize(path, self.fo, self.protocol) + + def _all_dirnames(self, paths): + """Returns *all* directory names for each path in paths, including intermediate + ones. + + Parameters + ---------- + paths: Iterable of path strings + """ + if len(paths) == 0: + return set() + + dirnames = {self._parent(path) for path in paths} - {self.root_marker} + return dirnames | self._all_dirnames(dirnames) + + def info(self, path, **kwargs): + self._get_dirs() + path = self._strip_protocol(path) + if path in {"", "/"} and self.dir_cache: + return {"name": "", "type": "directory", "size": 0} + if path in self.dir_cache: + return self.dir_cache[path] + elif path + "/" in self.dir_cache: + return self.dir_cache[path + "/"] + else: + raise FileNotFoundError(path) + + def ls(self, path, detail=True, **kwargs): + self._get_dirs() + paths = {} + for p, f in self.dir_cache.items(): + p = p.rstrip("/") + if "/" in p: + root = p.rsplit("/", 1)[0] + else: + root = "" + if root == path.rstrip("/"): + paths[p] = f + elif all( + (a == b) + for a, b in zip(path.split("/"), [""] + p.strip("/").split("/")) + ): + # root directory entry + ppath = p.rstrip("/").split("/", 1)[0] + if ppath not in paths: + out = {"name": ppath, "size": 0, "type": "directory"} + paths[ppath] = out + if detail: + out = sorted(paths.values(), key=operator.itemgetter("name")) + return out + else: + return sorted(paths) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/asyn.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/asyn.py new file mode 100644 index 0000000000000000000000000000000000000000..83772839450ec74a8fb37f9be323341f948e3748 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/asyn.py @@ -0,0 +1,1097 @@ +import asyncio +import asyncio.events +import functools +import inspect +import io +import numbers +import os +import re +import threading +from collections.abc import Iterable +from glob import has_magic +from typing import TYPE_CHECKING + +from .callbacks import DEFAULT_CALLBACK +from .exceptions import FSTimeoutError +from .implementations.local import LocalFileSystem, make_path_posix, trailing_sep +from .spec import AbstractBufferedFile, AbstractFileSystem +from .utils import glob_translate, is_exception, other_paths + +private = re.compile("_[^_]") +iothread = [None] # dedicated fsspec IO thread +loop = [None] # global event loop for any non-async instance +_lock = None # global lock placeholder +get_running_loop = asyncio.get_running_loop + + +def get_lock(): + """Allocate or return a threading lock. + + The lock is allocated on first use to allow setting one lock per forked process. + """ + global _lock + if not _lock: + _lock = threading.Lock() + return _lock + + +def reset_lock(): + """Reset the global lock. + + This should be called only on the init of a forked process to reset the lock to + None, enabling the new forked process to get a new lock. + """ + global _lock + + iothread[0] = None + loop[0] = None + _lock = None + + +async def _runner(event, coro, result, timeout=None): + timeout = timeout if timeout else None # convert 0 or 0.0 to None + if timeout is not None: + coro = asyncio.wait_for(coro, timeout=timeout) + try: + result[0] = await coro + except Exception as ex: + result[0] = ex + finally: + event.set() + + +def sync(loop, func, *args, timeout=None, **kwargs): + """ + Make loop run coroutine until it returns. Runs in other thread + + Examples + -------- + >>> fsspec.asyn.sync(fsspec.asyn.get_loop(), func, *args, + timeout=timeout, **kwargs) + """ + timeout = timeout if timeout else None # convert 0 or 0.0 to None + # NB: if the loop is not running *yet*, it is OK to submit work + # and we will wait for it + if loop is None or loop.is_closed(): + raise RuntimeError("Loop is not running") + try: + loop0 = asyncio.events.get_running_loop() + if loop0 is loop: + raise NotImplementedError("Calling sync() from within a running loop") + except NotImplementedError: + raise + except RuntimeError: + pass + coro = func(*args, **kwargs) + result = [None] + event = threading.Event() + asyncio.run_coroutine_threadsafe(_runner(event, coro, result, timeout), loop) + while True: + # this loops allows thread to get interrupted + if event.wait(1): + break + if timeout is not None: + timeout -= 1 + if timeout < 0: + raise FSTimeoutError + + return_result = result[0] + if isinstance(return_result, asyncio.TimeoutError): + # suppress asyncio.TimeoutError, raise FSTimeoutError + raise FSTimeoutError from return_result + elif isinstance(return_result, BaseException): + raise return_result + else: + return return_result + + +def sync_wrapper(func, obj=None): + """Given a function, make so can be called in blocking contexts + + Leave obj=None if defining within a class. Pass the instance if attaching + as an attribute of the instance. + """ + + @functools.wraps(func) + def wrapper(*args, **kwargs): + self = obj or args[0] + return sync(self.loop, func, *args, **kwargs) + + return wrapper + + +def get_loop(): + """Create or return the default fsspec IO loop + + The loop will be running on a separate thread. + """ + if loop[0] is None: + with get_lock(): + # repeat the check just in case the loop got filled between the + # previous two calls from another thread + if loop[0] is None: + loop[0] = asyncio.new_event_loop() + th = threading.Thread(target=loop[0].run_forever, name="fsspecIO") + th.daemon = True + th.start() + iothread[0] = th + return loop[0] + + +def reset_after_fork(): + global lock + loop[0] = None + iothread[0] = None + lock = None + + +if hasattr(os, "register_at_fork"): + # should be posix; this will do nothing for spawn or forkserver subprocesses + os.register_at_fork(after_in_child=reset_after_fork) + + +if TYPE_CHECKING: + import resource + + ResourceError = resource.error +else: + try: + import resource + except ImportError: + resource = None + ResourceError = OSError + else: + ResourceError = getattr(resource, "error", OSError) + +_DEFAULT_BATCH_SIZE = 128 +_NOFILES_DEFAULT_BATCH_SIZE = 1280 + + +def _get_batch_size(nofiles=False): + from fsspec.config import conf + + if nofiles: + if "nofiles_gather_batch_size" in conf: + return conf["nofiles_gather_batch_size"] + else: + if "gather_batch_size" in conf: + return conf["gather_batch_size"] + if nofiles: + return _NOFILES_DEFAULT_BATCH_SIZE + if resource is None: + return _DEFAULT_BATCH_SIZE + + try: + soft_limit, _ = resource.getrlimit(resource.RLIMIT_NOFILE) + except (ImportError, ValueError, ResourceError): + return _DEFAULT_BATCH_SIZE + + if soft_limit == resource.RLIM_INFINITY: + return -1 + else: + return soft_limit // 8 + + +def running_async() -> bool: + """Being executed by an event loop?""" + try: + asyncio.get_running_loop() + return True + except RuntimeError: + return False + + +async def _run_coros_in_chunks( + coros, + batch_size=None, + callback=DEFAULT_CALLBACK, + timeout=None, + return_exceptions=False, + nofiles=False, +): + """Run the given coroutines in chunks. + + Parameters + ---------- + coros: list of coroutines to run + batch_size: int or None + Number of coroutines to submit/wait on simultaneously. + If -1, then it will not be any throttling. If + None, it will be inferred from _get_batch_size() + callback: fsspec.callbacks.Callback instance + Gets a relative_update when each coroutine completes + timeout: number or None + If given, each coroutine times out after this time. Note that, since + there are multiple batches, the total run time of this function will in + general be longer + return_exceptions: bool + Same meaning as in asyncio.gather + nofiles: bool + If inferring the batch_size, does this operation involve local files? + If yes, you normally expect smaller batches. + """ + + if batch_size is None: + batch_size = _get_batch_size(nofiles=nofiles) + + if batch_size == -1: + batch_size = len(coros) + + assert batch_size > 0 + + async def _run_coro(coro, i): + try: + return await asyncio.wait_for(coro, timeout=timeout), i + except Exception as e: + if not return_exceptions: + raise + return e, i + finally: + callback.relative_update(1) + + i = 0 + n = len(coros) + results = [None] * n + pending = set() + + while pending or i < n: + while len(pending) < batch_size and i < n: + pending.add(asyncio.ensure_future(_run_coro(coros[i], i))) + i += 1 + + if not pending: + break + + done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED) + while done: + result, k = await done.pop() + results[k] = result + + return results + + +# these methods should be implemented as async by any async-able backend +async_methods = [ + "_ls", + "_cat_file", + "_get_file", + "_put_file", + "_rm_file", + "_cp_file", + "_pipe_file", + "_expand_path", + "_info", + "_isfile", + "_isdir", + "_exists", + "_walk", + "_glob", + "_find", + "_du", + "_size", + "_mkdir", + "_makedirs", +] + + +class AsyncFileSystem(AbstractFileSystem): + """Async file operations, default implementations + + Passes bulk operations to asyncio.gather for concurrent operation. + + Implementations that have concurrent batch operations and/or async methods + should inherit from this class instead of AbstractFileSystem. Docstrings are + copied from the un-underscored method in AbstractFileSystem, if not given. + """ + + # note that methods do not have docstring here; they will be copied + # for _* methods and inferred for overridden methods. + + async_impl = True + mirror_sync_methods = True + disable_throttling = False + + def __init__(self, *args, asynchronous=False, loop=None, batch_size=None, **kwargs): + self.asynchronous = asynchronous + self._pid = os.getpid() + if not asynchronous: + self._loop = loop or get_loop() + else: + self._loop = None + self.batch_size = batch_size + super().__init__(*args, **kwargs) + + @property + def loop(self): + if self._pid != os.getpid(): + raise RuntimeError("This class is not fork-safe") + return self._loop + + async def _rm_file(self, path, **kwargs): + raise NotImplementedError + + async def _rm(self, path, recursive=False, batch_size=None, **kwargs): + # TODO: implement on_error + batch_size = batch_size or self.batch_size + path = await self._expand_path(path, recursive=recursive) + return await _run_coros_in_chunks( + [self._rm_file(p, **kwargs) for p in reversed(path)], + batch_size=batch_size, + nofiles=True, + ) + + async def _cp_file(self, path1, path2, **kwargs): + raise NotImplementedError + + async def _mv_file(self, path1, path2): + await self._cp_file(path1, path2) + await self._rm_file(path1) + + async def _copy( + self, + path1, + path2, + recursive=False, + on_error=None, + maxdepth=None, + batch_size=None, + **kwargs, + ): + if on_error is None and recursive: + on_error = "ignore" + elif on_error is None: + on_error = "raise" + + if isinstance(path1, list) and isinstance(path2, list): + # No need to expand paths when both source and destination + # are provided as lists + paths1 = path1 + paths2 = path2 + else: + source_is_str = isinstance(path1, str) + paths1 = await self._expand_path( + path1, maxdepth=maxdepth, recursive=recursive + ) + if source_is_str and (not recursive or maxdepth is not None): + # Non-recursive glob does not copy directories + paths1 = [ + p for p in paths1 if not (trailing_sep(p) or await self._isdir(p)) + ] + if not paths1: + return + + source_is_file = len(paths1) == 1 + dest_is_dir = isinstance(path2, str) and ( + trailing_sep(path2) or await self._isdir(path2) + ) + + exists = source_is_str and ( + (has_magic(path1) and source_is_file) + or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1)) + ) + paths2 = other_paths( + paths1, + path2, + exists=exists, + flatten=not source_is_str, + ) + + batch_size = batch_size or self.batch_size + coros = [self._cp_file(p1, p2, **kwargs) for p1, p2 in zip(paths1, paths2)] + result = await _run_coros_in_chunks( + coros, batch_size=batch_size, return_exceptions=True, nofiles=True + ) + + for ex in filter(is_exception, result): + if on_error == "ignore" and isinstance(ex, FileNotFoundError): + continue + raise ex + + async def _pipe_file(self, path, value, mode="overwrite", **kwargs): + raise NotImplementedError + + async def _pipe(self, path, value=None, batch_size=None, **kwargs): + if isinstance(path, str): + path = {path: value} + batch_size = batch_size or self.batch_size + return await _run_coros_in_chunks( + [self._pipe_file(k, v, **kwargs) for k, v in path.items()], + batch_size=batch_size, + nofiles=True, + ) + + async def _process_limits(self, url, start, end): + """Helper for "Range"-based _cat_file""" + size = None + suff = False + if start is not None and start < 0: + # if start is negative and end None, end is the "suffix length" + if end is None: + end = -start + start = "" + suff = True + else: + size = size or (await self._info(url))["size"] + start = size + start + elif start is None: + start = 0 + if not suff: + if end is not None and end < 0: + if start is not None: + size = size or (await self._info(url))["size"] + end = size + end + elif end is None: + end = "" + if isinstance(end, numbers.Integral): + end -= 1 # bytes range is inclusive + return f"bytes={start}-{end}" + + async def _cat_file(self, path, start=None, end=None, **kwargs): + raise NotImplementedError + + async def _cat( + self, path, recursive=False, on_error="raise", batch_size=None, **kwargs + ): + paths = await self._expand_path(path, recursive=recursive) + coros = [self._cat_file(path, **kwargs) for path in paths] + batch_size = batch_size or self.batch_size + out = await _run_coros_in_chunks( + coros, batch_size=batch_size, nofiles=True, return_exceptions=True + ) + if on_error == "raise": + ex = next(filter(is_exception, out), False) + if ex: + raise ex + if ( + len(paths) > 1 + or isinstance(path, list) + or paths[0] != self._strip_protocol(path) + ): + return { + k: v + for k, v in zip(paths, out) + if on_error != "omit" or not is_exception(v) + } + else: + return out[0] + + async def _cat_ranges( + self, + paths, + starts, + ends, + max_gap=None, + batch_size=None, + on_error="return", + **kwargs, + ): + """Get the contents of byte ranges from one or more files + + Parameters + ---------- + paths: list + A list of of filepaths on this filesystems + starts, ends: int or list + Bytes limits of the read. If using a single int, the same value will be + used to read all the specified files. + """ + # TODO: on_error + if max_gap is not None: + # use utils.merge_offset_ranges + raise NotImplementedError + if not isinstance(paths, list): + raise TypeError + if not isinstance(starts, Iterable): + starts = [starts] * len(paths) + if not isinstance(ends, Iterable): + ends = [ends] * len(paths) + if len(starts) != len(paths) or len(ends) != len(paths): + raise ValueError + coros = [ + self._cat_file(p, start=s, end=e, **kwargs) + for p, s, e in zip(paths, starts, ends) + ] + batch_size = batch_size or self.batch_size + return await _run_coros_in_chunks( + coros, batch_size=batch_size, nofiles=True, return_exceptions=True + ) + + async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs): + raise NotImplementedError + + async def _put( + self, + lpath, + rpath, + recursive=False, + callback=DEFAULT_CALLBACK, + batch_size=None, + maxdepth=None, + **kwargs, + ): + """Copy file(s) from local. + + Copies a specific file or tree of files (if recursive=True). If rpath + ends with a "/", it will be assumed to be a directory, and target files + will go within. + + The put_file method will be called concurrently on a batch of files. The + batch_size option can configure the amount of futures that can be executed + at the same time. If it is -1, then all the files will be uploaded concurrently. + The default can be set for this instance by passing "batch_size" in the + constructor, or for all instances by setting the "gather_batch_size" key + in ``fsspec.config.conf``, falling back to 1/8th of the system limit . + """ + if isinstance(lpath, list) and isinstance(rpath, list): + # No need to expand paths when both source and destination + # are provided as lists + rpaths = rpath + lpaths = lpath + else: + source_is_str = isinstance(lpath, str) + if source_is_str: + lpath = make_path_posix(lpath) + fs = LocalFileSystem() + lpaths = fs.expand_path(lpath, recursive=recursive, maxdepth=maxdepth) + if source_is_str and (not recursive or maxdepth is not None): + # Non-recursive glob does not copy directories + lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))] + if not lpaths: + return + + source_is_file = len(lpaths) == 1 + dest_is_dir = isinstance(rpath, str) and ( + trailing_sep(rpath) or await self._isdir(rpath) + ) + + rpath = self._strip_protocol(rpath) + exists = source_is_str and ( + (has_magic(lpath) and source_is_file) + or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath)) + ) + rpaths = other_paths( + lpaths, + rpath, + exists=exists, + flatten=not source_is_str, + ) + + is_dir = {l: os.path.isdir(l) for l in lpaths} + rdirs = [r for l, r in zip(lpaths, rpaths) if is_dir[l]] + file_pairs = [(l, r) for l, r in zip(lpaths, rpaths) if not is_dir[l]] + + await asyncio.gather(*[self._makedirs(d, exist_ok=True) for d in rdirs]) + batch_size = batch_size or self.batch_size + + coros = [] + callback.set_size(len(file_pairs)) + for lfile, rfile in file_pairs: + put_file = callback.branch_coro(self._put_file) + coros.append(put_file(lfile, rfile, **kwargs)) + + return await _run_coros_in_chunks( + coros, batch_size=batch_size, callback=callback + ) + + async def _get_file(self, rpath, lpath, **kwargs): + raise NotImplementedError + + async def _get( + self, + rpath, + lpath, + recursive=False, + callback=DEFAULT_CALLBACK, + maxdepth=None, + **kwargs, + ): + """Copy file(s) to local. + + Copies a specific file or tree of files (if recursive=True). If lpath + ends with a "/", it will be assumed to be a directory, and target files + will go within. Can submit a list of paths, which may be glob-patterns + and will be expanded. + + The get_file method will be called concurrently on a batch of files. The + batch_size option can configure the amount of futures that can be executed + at the same time. If it is -1, then all the files will be uploaded concurrently. + The default can be set for this instance by passing "batch_size" in the + constructor, or for all instances by setting the "gather_batch_size" key + in ``fsspec.config.conf``, falling back to 1/8th of the system limit . + """ + if isinstance(lpath, list) and isinstance(rpath, list): + # No need to expand paths when both source and destination + # are provided as lists + rpaths = rpath + lpaths = lpath + else: + source_is_str = isinstance(rpath, str) + # First check for rpath trailing slash as _strip_protocol removes it. + source_not_trailing_sep = source_is_str and not trailing_sep(rpath) + rpath = self._strip_protocol(rpath) + rpaths = await self._expand_path( + rpath, recursive=recursive, maxdepth=maxdepth + ) + if source_is_str and (not recursive or maxdepth is not None): + # Non-recursive glob does not copy directories + rpaths = [ + p for p in rpaths if not (trailing_sep(p) or await self._isdir(p)) + ] + if not rpaths: + return + + lpath = make_path_posix(lpath) + source_is_file = len(rpaths) == 1 + dest_is_dir = isinstance(lpath, str) and ( + trailing_sep(lpath) or LocalFileSystem().isdir(lpath) + ) + + exists = source_is_str and ( + (has_magic(rpath) and source_is_file) + or (not has_magic(rpath) and dest_is_dir and source_not_trailing_sep) + ) + lpaths = other_paths( + rpaths, + lpath, + exists=exists, + flatten=not source_is_str, + ) + + [os.makedirs(os.path.dirname(lp), exist_ok=True) for lp in lpaths] + batch_size = kwargs.pop("batch_size", self.batch_size) + + coros = [] + callback.set_size(len(lpaths)) + for lpath, rpath in zip(lpaths, rpaths): + get_file = callback.branch_coro(self._get_file) + coros.append(get_file(rpath, lpath, **kwargs)) + return await _run_coros_in_chunks( + coros, batch_size=batch_size, callback=callback + ) + + async def _isfile(self, path): + try: + return (await self._info(path))["type"] == "file" + except: # noqa: E722 + return False + + async def _isdir(self, path): + try: + return (await self._info(path))["type"] == "directory" + except OSError: + return False + + async def _size(self, path): + return (await self._info(path)).get("size", None) + + async def _sizes(self, paths, batch_size=None): + batch_size = batch_size or self.batch_size + return await _run_coros_in_chunks( + [self._size(p) for p in paths], batch_size=batch_size + ) + + async def _exists(self, path, **kwargs): + try: + await self._info(path, **kwargs) + return True + except FileNotFoundError: + return False + + async def _info(self, path, **kwargs): + raise NotImplementedError + + async def _ls(self, path, detail=True, **kwargs): + raise NotImplementedError + + async def _walk(self, path, maxdepth=None, on_error="omit", **kwargs): + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + path = self._strip_protocol(path) + full_dirs = {} + dirs = {} + files = {} + + detail = kwargs.pop("detail", False) + try: + listing = await self._ls(path, detail=True, **kwargs) + except (FileNotFoundError, OSError) as e: + if on_error == "raise": + raise + elif callable(on_error): + on_error(e) + if detail: + yield path, {}, {} + else: + yield path, [], [] + return + + for info in listing: + # each info name must be at least [path]/part , but here + # we check also for names like [path]/part/ + pathname = info["name"].rstrip("/") + name = pathname.rsplit("/", 1)[-1] + if info["type"] == "directory" and pathname != path: + # do not include "self" path + full_dirs[name] = pathname + dirs[name] = info + elif pathname == path: + # file-like with same name as give path + files[""] = info + else: + files[name] = info + + if detail: + yield path, dirs, files + else: + yield path, list(dirs), list(files) + + if maxdepth is not None: + maxdepth -= 1 + if maxdepth < 1: + return + + for d in dirs: + async for _ in self._walk( + full_dirs[d], maxdepth=maxdepth, detail=detail, **kwargs + ): + yield _ + + async def _glob(self, path, maxdepth=None, **kwargs): + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + import re + + seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,) + ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash + path = self._strip_protocol(path) + append_slash_to_dirname = ends_with_sep or path.endswith( + tuple(sep + "**" for sep in seps) + ) + idx_star = path.find("*") if path.find("*") >= 0 else len(path) + idx_qmark = path.find("?") if path.find("?") >= 0 else len(path) + idx_brace = path.find("[") if path.find("[") >= 0 else len(path) + + min_idx = min(idx_star, idx_qmark, idx_brace) + + detail = kwargs.pop("detail", False) + + if not has_magic(path): + if await self._exists(path, **kwargs): + if not detail: + return [path] + else: + return {path: await self._info(path, **kwargs)} + else: + if not detail: + return [] # glob of non-existent returns empty + else: + return {} + elif "/" in path[:min_idx]: + min_idx = path[:min_idx].rindex("/") + root = path[: min_idx + 1] + depth = path[min_idx + 1 :].count("/") + 1 + else: + root = "" + depth = path[min_idx + 1 :].count("/") + 1 + + if "**" in path: + if maxdepth is not None: + idx_double_stars = path.find("**") + depth_double_stars = path[idx_double_stars:].count("/") + 1 + depth = depth - depth_double_stars + maxdepth + else: + depth = None + + allpaths = await self._find( + root, maxdepth=depth, withdirs=True, detail=True, **kwargs + ) + + pattern = glob_translate(path + ("/" if ends_with_sep else "")) + pattern = re.compile(pattern) + + out = { + p: info + for p, info in sorted(allpaths.items()) + if pattern.match( + p + "/" + if append_slash_to_dirname and info["type"] == "directory" + else p + ) + } + + if detail: + return out + else: + return list(out) + + async def _du(self, path, total=True, maxdepth=None, **kwargs): + sizes = {} + # async for? + for f in await self._find(path, maxdepth=maxdepth, **kwargs): + info = await self._info(f) + sizes[info["name"]] = info["size"] + if total: + return sum(sizes.values()) + else: + return sizes + + async def _find(self, path, maxdepth=None, withdirs=False, **kwargs): + path = self._strip_protocol(path) + out = {} + detail = kwargs.pop("detail", False) + + # Add the root directory if withdirs is requested + # This is needed for posix glob compliance + if withdirs and path != "" and await self._isdir(path): + out[path] = await self._info(path) + + # async for? + async for _, dirs, files in self._walk(path, maxdepth, detail=True, **kwargs): + if withdirs: + files.update(dirs) + out.update({info["name"]: info for name, info in files.items()}) + if not out and (await self._isfile(path)): + # walk works on directories, but find should also return [path] + # when path happens to be a file + out[path] = {} + names = sorted(out) + if not detail: + return names + else: + return {name: out[name] for name in names} + + async def _expand_path(self, path, recursive=False, maxdepth=None): + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + if isinstance(path, str): + out = await self._expand_path([path], recursive, maxdepth) + else: + out = set() + path = [self._strip_protocol(p) for p in path] + for p in path: # can gather here + if has_magic(p): + bit = set(await self._glob(p, maxdepth=maxdepth)) + out |= bit + if recursive: + # glob call above expanded one depth so if maxdepth is defined + # then decrement it in expand_path call below. If it is zero + # after decrementing then avoid expand_path call. + if maxdepth is not None and maxdepth <= 1: + continue + out |= set( + await self._expand_path( + list(bit), + recursive=recursive, + maxdepth=maxdepth - 1 if maxdepth is not None else None, + ) + ) + continue + elif recursive: + rec = set(await self._find(p, maxdepth=maxdepth, withdirs=True)) + out |= rec + if p not in out and (recursive is False or (await self._exists(p))): + # should only check once, for the root + out.add(p) + if not out: + raise FileNotFoundError(path) + return sorted(out) + + async def _mkdir(self, path, create_parents=True, **kwargs): + pass # not necessary to implement, may not have directories + + async def _makedirs(self, path, exist_ok=False): + pass # not necessary to implement, may not have directories + + async def open_async(self, path, mode="rb", **kwargs): + if "b" not in mode or kwargs.get("compression"): + raise ValueError + raise NotImplementedError + + +def mirror_sync_methods(obj): + """Populate sync and async methods for obj + + For each method will create a sync version if the name refers to an async method + (coroutine) and there is no override in the child class; will create an async + method for the corresponding sync method if there is no implementation. + + Uses the methods specified in + - async_methods: the set that an implementation is expected to provide + - default_async_methods: that can be derived from their sync version in + AbstractFileSystem + - AsyncFileSystem: async-specific default coroutines + """ + from fsspec import AbstractFileSystem + + for method in async_methods + dir(AsyncFileSystem): + if not method.startswith("_"): + continue + smethod = method[1:] + if private.match(method): + isco = inspect.iscoroutinefunction(getattr(obj, method, None)) + unsync = getattr(getattr(obj, smethod, False), "__func__", None) + is_default = unsync is getattr(AbstractFileSystem, smethod, "") + if isco and is_default: + mth = sync_wrapper(getattr(obj, method), obj=obj) + setattr(obj, smethod, mth) + if not mth.__doc__: + mth.__doc__ = getattr( + getattr(AbstractFileSystem, smethod, None), "__doc__", "" + ) + + +class FSSpecCoroutineCancel(Exception): + pass + + +def _dump_running_tasks( + printout=True, cancel=True, exc=FSSpecCoroutineCancel, with_task=False +): + import traceback + + tasks = [t for t in asyncio.tasks.all_tasks(loop[0]) if not t.done()] + if printout: + [task.print_stack() for task in tasks] + out = [ + { + "locals": task._coro.cr_frame.f_locals, + "file": task._coro.cr_frame.f_code.co_filename, + "firstline": task._coro.cr_frame.f_code.co_firstlineno, + "linelo": task._coro.cr_frame.f_lineno, + "stack": traceback.format_stack(task._coro.cr_frame), + "task": task if with_task else None, + } + for task in tasks + ] + if cancel: + for t in tasks: + cbs = t._callbacks + t.cancel() + asyncio.futures.Future.set_exception(t, exc) + asyncio.futures.Future.cancel(t) + [cb[0](t) for cb in cbs] # cancels any dependent concurrent.futures + try: + t._coro.throw(exc) # exits coro, unless explicitly handled + except exc: + pass + return out + + +class AbstractAsyncStreamedFile(AbstractBufferedFile): + # no read buffering, and always auto-commit + # TODO: readahead might still be useful here, but needs async version + + async def read(self, length=-1): + """ + Return data from cache, or fetch pieces as necessary + + Parameters + ---------- + length: int (-1) + Number of bytes to read; if <0, all remaining bytes. + """ + length = -1 if length is None else int(length) + if self.mode != "rb": + raise ValueError("File not in read mode") + if length < 0: + length = self.size - self.loc + if self.closed: + raise ValueError("I/O operation on closed file.") + if length == 0: + # don't even bother calling fetch + return b"" + out = await self._fetch_range(self.loc, self.loc + length) + self.loc += len(out) + return out + + async def write(self, data): + """ + Write data to buffer. + + Buffer only sent on flush() or if buffer is greater than + or equal to blocksize. + + Parameters + ---------- + data: bytes + Set of bytes to be written. + """ + if self.mode not in {"wb", "ab"}: + raise ValueError("File not in write mode") + if self.closed: + raise ValueError("I/O operation on closed file.") + if self.forced: + raise ValueError("This file has been force-flushed, can only close") + out = self.buffer.write(data) + self.loc += out + if self.buffer.tell() >= self.blocksize: + await self.flush() + return out + + async def close(self): + """Close file + + Finalizes writes, discards cache + """ + if getattr(self, "_unclosable", False): + return + if self.closed: + return + if self.mode == "rb": + self.cache = None + else: + if not self.forced: + await self.flush(force=True) + + if self.fs is not None: + self.fs.invalidate_cache(self.path) + self.fs.invalidate_cache(self.fs._parent(self.path)) + + self.closed = True + + async def flush(self, force=False): + if self.closed: + raise ValueError("Flush on closed file") + if force and self.forced: + raise ValueError("Force flush cannot be called more than once") + if force: + self.forced = True + + if self.mode not in {"wb", "ab"}: + # no-op to flush on read-mode + return + + if not force and self.buffer.tell() < self.blocksize: + # Defer write on small block + return + + if self.offset is None: + # Initialize a multipart upload + self.offset = 0 + try: + await self._initiate_upload() + except: + self.closed = True + raise + + if await self._upload_chunk(final=force) is not False: + self.offset += self.buffer.seek(0, 2) + self.buffer = io.BytesIO() + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + await self.close() + + async def _fetch_range(self, start, end): + raise NotImplementedError + + async def _initiate_upload(self): + pass + + async def _upload_chunk(self, final=False): + raise NotImplementedError diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/caching.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/caching.py new file mode 100644 index 0000000000000000000000000000000000000000..de6a4e3407a62a1c2123bf2b4a81afb96c54150a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/caching.py @@ -0,0 +1,1004 @@ +from __future__ import annotations + +import collections +import functools +import logging +import math +import os +import threading +import warnings +from collections import OrderedDict +from concurrent.futures import Future, ThreadPoolExecutor +from itertools import groupby +from operator import itemgetter +from typing import ( + TYPE_CHECKING, + Any, + Callable, + ClassVar, + Generic, + NamedTuple, + TypeVar, +) + +if TYPE_CHECKING: + import mmap + + from typing_extensions import ParamSpec + + P = ParamSpec("P") +else: + P = TypeVar("P") + +T = TypeVar("T") + + +logger = logging.getLogger("fsspec") + +Fetcher = Callable[[int, int], bytes] # Maps (start, end) to bytes +MultiFetcher = Callable[[list[int, int]], bytes] # Maps [(start, end)] to bytes + + +class BaseCache: + """Pass-though cache: doesn't keep anything, calls every time + + Acts as base class for other cachers + + Parameters + ---------- + blocksize: int + How far to read ahead in numbers of bytes + fetcher: func + Function of the form f(start, end) which gets bytes from remote as + specified + size: int + How big this file is + """ + + name: ClassVar[str] = "none" + + def __init__(self, blocksize: int, fetcher: Fetcher, size: int) -> None: + self.blocksize = blocksize + self.nblocks = 0 + self.fetcher = fetcher + self.size = size + self.hit_count = 0 + self.miss_count = 0 + # the bytes that we actually requested + self.total_requested_bytes = 0 + + def _fetch(self, start: int | None, stop: int | None) -> bytes: + if start is None: + start = 0 + if stop is None: + stop = self.size + if start >= self.size or start >= stop: + return b"" + return self.fetcher(start, stop) + + def _reset_stats(self) -> None: + """Reset hit and miss counts for a more ganular report e.g. by file.""" + self.hit_count = 0 + self.miss_count = 0 + self.total_requested_bytes = 0 + + def _log_stats(self) -> str: + """Return a formatted string of the cache statistics.""" + if self.hit_count == 0 and self.miss_count == 0: + # a cache that does nothing, this is for logs only + return "" + return f" , {self.name}: {self.hit_count} hits, {self.miss_count} misses, {self.total_requested_bytes} total requested bytes" + + def __repr__(self) -> str: + # TODO: use rich for better formatting + return f""" + <{self.__class__.__name__}: + block size : {self.blocksize} + block count : {self.nblocks} + file size : {self.size} + cache hits : {self.hit_count} + cache misses: {self.miss_count} + total requested bytes: {self.total_requested_bytes}> + """ + + +class MMapCache(BaseCache): + """memory-mapped sparse file cache + + Opens temporary file, which is filled blocks-wise when data is requested. + Ensure there is enough disc space in the temporary location. + + This cache method might only work on posix + + Parameters + ---------- + blocksize: int + How far to read ahead in numbers of bytes + fetcher: Fetcher + Function of the form f(start, end) which gets bytes from remote as + specified + size: int + How big this file is + location: str + Where to create the temporary file. If None, a temporary file is + created using tempfile.TemporaryFile(). + blocks: set[int] + Set of block numbers that have already been fetched. If None, an empty + set is created. + multi_fetcher: MultiFetcher + Function of the form f([(start, end)]) which gets bytes from remote + as specified. This function is used to fetch multiple blocks at once. + If not specified, the fetcher function is used instead. + """ + + name = "mmap" + + def __init__( + self, + blocksize: int, + fetcher: Fetcher, + size: int, + location: str | None = None, + blocks: set[int] | None = None, + multi_fetcher: MultiFetcher | None = None, + ) -> None: + super().__init__(blocksize, fetcher, size) + self.blocks = set() if blocks is None else blocks + self.location = location + self.multi_fetcher = multi_fetcher + self.cache = self._makefile() + + def _makefile(self) -> mmap.mmap | bytearray: + import mmap + import tempfile + + if self.size == 0: + return bytearray() + + # posix version + if self.location is None or not os.path.exists(self.location): + if self.location is None: + fd = tempfile.TemporaryFile() + self.blocks = set() + else: + fd = open(self.location, "wb+") + fd.seek(self.size - 1) + fd.write(b"1") + fd.flush() + else: + fd = open(self.location, "r+b") + + return mmap.mmap(fd.fileno(), self.size) + + def _fetch(self, start: int | None, end: int | None) -> bytes: + logger.debug(f"MMap cache fetching {start}-{end}") + if start is None: + start = 0 + if end is None: + end = self.size + if start >= self.size or start >= end: + return b"" + start_block = start // self.blocksize + end_block = end // self.blocksize + block_range = range(start_block, end_block + 1) + # Determine which blocks need to be fetched. This sequence is sorted by construction. + need = (i for i in block_range if i not in self.blocks) + # Count the number of blocks already cached + self.hit_count += sum(1 for i in block_range if i in self.blocks) + + ranges = [] + + # Consolidate needed blocks. + # Algorithm adapted from Python 2.x itertools documentation. + # We are grouping an enumerated sequence of blocks. By comparing when the difference + # between an ascending range (provided by enumerate) and the needed block numbers + # we can detect when the block number skips values. The key computes this difference. + # Whenever the difference changes, we know that we have previously cached block(s), + # and a new group is started. In other words, this algorithm neatly groups + # runs of consecutive block numbers so they can be fetched together. + for _, _blocks in groupby(enumerate(need), key=lambda x: x[0] - x[1]): + # Extract the blocks from the enumerated sequence + _blocks = tuple(map(itemgetter(1), _blocks)) + # Compute start of first block + sstart = _blocks[0] * self.blocksize + # Compute the end of the last block. Last block may not be full size. + send = min(_blocks[-1] * self.blocksize + self.blocksize, self.size) + + # Fetch bytes (could be multiple consecutive blocks) + self.total_requested_bytes += send - sstart + logger.debug( + f"MMap get blocks {_blocks[0]}-{_blocks[-1]} ({sstart}-{send})" + ) + ranges.append((sstart, send)) + + # Update set of cached blocks + self.blocks.update(_blocks) + # Update cache statistics with number of blocks we had to cache + self.miss_count += len(_blocks) + + if not ranges: + return self.cache[start:end] + + if self.multi_fetcher: + logger.debug(f"MMap get blocks {ranges}") + for idx, r in enumerate(self.multi_fetcher(ranges)): + (sstart, send) = ranges[idx] + logger.debug(f"MMap copy block ({sstart}-{send}") + self.cache[sstart:send] = r + else: + for sstart, send in ranges: + logger.debug(f"MMap get block ({sstart}-{send}") + self.cache[sstart:send] = self.fetcher(sstart, send) + + return self.cache[start:end] + + def __getstate__(self) -> dict[str, Any]: + state = self.__dict__.copy() + # Remove the unpicklable entries. + del state["cache"] + return state + + def __setstate__(self, state: dict[str, Any]) -> None: + # Restore instance attributes + self.__dict__.update(state) + self.cache = self._makefile() + + +class ReadAheadCache(BaseCache): + """Cache which reads only when we get beyond a block of data + + This is a much simpler version of BytesCache, and does not attempt to + fill holes in the cache or keep fragments alive. It is best suited to + many small reads in a sequential order (e.g., reading lines from a file). + """ + + name = "readahead" + + def __init__(self, blocksize: int, fetcher: Fetcher, size: int) -> None: + super().__init__(blocksize, fetcher, size) + self.cache = b"" + self.start = 0 + self.end = 0 + + def _fetch(self, start: int | None, end: int | None) -> bytes: + if start is None: + start = 0 + if end is None or end > self.size: + end = self.size + if start >= self.size or start >= end: + return b"" + l = end - start + if start >= self.start and end <= self.end: + # cache hit + self.hit_count += 1 + return self.cache[start - self.start : end - self.start] + elif self.start <= start < self.end: + # partial hit + self.miss_count += 1 + part = self.cache[start - self.start :] + l -= len(part) + start = self.end + else: + # miss + self.miss_count += 1 + part = b"" + end = min(self.size, end + self.blocksize) + self.total_requested_bytes += end - start + self.cache = self.fetcher(start, end) # new block replaces old + self.start = start + self.end = self.start + len(self.cache) + return part + self.cache[:l] + + +class FirstChunkCache(BaseCache): + """Caches the first block of a file only + + This may be useful for file types where the metadata is stored in the header, + but is randomly accessed. + """ + + name = "first" + + def __init__(self, blocksize: int, fetcher: Fetcher, size: int) -> None: + if blocksize > size: + # this will buffer the whole thing + blocksize = size + super().__init__(blocksize, fetcher, size) + self.cache: bytes | None = None + + def _fetch(self, start: int | None, end: int | None) -> bytes: + start = start or 0 + if start > self.size: + logger.debug("FirstChunkCache: requested start > file size") + return b"" + + end = min(end, self.size) + + if start < self.blocksize: + if self.cache is None: + self.miss_count += 1 + if end > self.blocksize: + self.total_requested_bytes += end + data = self.fetcher(0, end) + self.cache = data[: self.blocksize] + return data[start:] + self.cache = self.fetcher(0, self.blocksize) + self.total_requested_bytes += self.blocksize + part = self.cache[start:end] + if end > self.blocksize: + self.total_requested_bytes += end - self.blocksize + part += self.fetcher(self.blocksize, end) + self.hit_count += 1 + return part + else: + self.miss_count += 1 + self.total_requested_bytes += end - start + return self.fetcher(start, end) + + +class BlockCache(BaseCache): + """ + Cache holding memory as a set of blocks. + + Requests are only ever made ``blocksize`` at a time, and are + stored in an LRU cache. The least recently accessed block is + discarded when more than ``maxblocks`` are stored. + + Parameters + ---------- + blocksize : int + The number of bytes to store in each block. + Requests are only ever made for ``blocksize``, so this + should balance the overhead of making a request against + the granularity of the blocks. + fetcher : Callable + size : int + The total size of the file being cached. + maxblocks : int + The maximum number of blocks to cache for. The maximum memory + use for this cache is then ``blocksize * maxblocks``. + """ + + name = "blockcache" + + def __init__( + self, blocksize: int, fetcher: Fetcher, size: int, maxblocks: int = 32 + ) -> None: + super().__init__(blocksize, fetcher, size) + self.nblocks = math.ceil(size / blocksize) + self.maxblocks = maxblocks + self._fetch_block_cached = functools.lru_cache(maxblocks)(self._fetch_block) + + def cache_info(self): + """ + The statistics on the block cache. + + Returns + ------- + NamedTuple + Returned directly from the LRU Cache used internally. + """ + return self._fetch_block_cached.cache_info() + + def __getstate__(self) -> dict[str, Any]: + state = self.__dict__ + del state["_fetch_block_cached"] + return state + + def __setstate__(self, state: dict[str, Any]) -> None: + self.__dict__.update(state) + self._fetch_block_cached = functools.lru_cache(state["maxblocks"])( + self._fetch_block + ) + + def _fetch(self, start: int | None, end: int | None) -> bytes: + if start is None: + start = 0 + if end is None: + end = self.size + if start >= self.size or start >= end: + return b"" + + # byte position -> block numbers + start_block_number = start // self.blocksize + end_block_number = end // self.blocksize + + # these are cached, so safe to do multiple calls for the same start and end. + for block_number in range(start_block_number, end_block_number + 1): + self._fetch_block_cached(block_number) + + return self._read_cache( + start, + end, + start_block_number=start_block_number, + end_block_number=end_block_number, + ) + + def _fetch_block(self, block_number: int) -> bytes: + """ + Fetch the block of data for `block_number`. + """ + if block_number > self.nblocks: + raise ValueError( + f"'block_number={block_number}' is greater than " + f"the number of blocks ({self.nblocks})" + ) + + start = block_number * self.blocksize + end = start + self.blocksize + self.total_requested_bytes += end - start + self.miss_count += 1 + logger.info("BlockCache fetching block %d", block_number) + block_contents = super()._fetch(start, end) + return block_contents + + def _read_cache( + self, start: int, end: int, start_block_number: int, end_block_number: int + ) -> bytes: + """ + Read from our block cache. + + Parameters + ---------- + start, end : int + The start and end byte positions. + start_block_number, end_block_number : int + The start and end block numbers. + """ + start_pos = start % self.blocksize + end_pos = end % self.blocksize + + self.hit_count += 1 + if start_block_number == end_block_number: + block: bytes = self._fetch_block_cached(start_block_number) + return block[start_pos:end_pos] + + else: + # read from the initial + out = [self._fetch_block_cached(start_block_number)[start_pos:]] + + # intermediate blocks + # Note: it'd be nice to combine these into one big request. However + # that doesn't play nicely with our LRU cache. + out.extend( + map( + self._fetch_block_cached, + range(start_block_number + 1, end_block_number), + ) + ) + + # final block + out.append(self._fetch_block_cached(end_block_number)[:end_pos]) + + return b"".join(out) + + +class BytesCache(BaseCache): + """Cache which holds data in a in-memory bytes object + + Implements read-ahead by the block size, for semi-random reads progressing + through the file. + + Parameters + ---------- + trim: bool + As we read more data, whether to discard the start of the buffer when + we are more than a blocksize ahead of it. + """ + + name: ClassVar[str] = "bytes" + + def __init__( + self, blocksize: int, fetcher: Fetcher, size: int, trim: bool = True + ) -> None: + super().__init__(blocksize, fetcher, size) + self.cache = b"" + self.start: int | None = None + self.end: int | None = None + self.trim = trim + + def _fetch(self, start: int | None, end: int | None) -> bytes: + # TODO: only set start/end after fetch, in case it fails? + # is this where retry logic might go? + if start is None: + start = 0 + if end is None: + end = self.size + if start >= self.size or start >= end: + return b"" + if ( + self.start is not None + and start >= self.start + and self.end is not None + and end < self.end + ): + # cache hit: we have all the required data + offset = start - self.start + self.hit_count += 1 + return self.cache[offset : offset + end - start] + + if self.blocksize: + bend = min(self.size, end + self.blocksize) + else: + bend = end + + if bend == start or start > self.size: + return b"" + + if (self.start is None or start < self.start) and ( + self.end is None or end > self.end + ): + # First read, or extending both before and after + self.total_requested_bytes += bend - start + self.miss_count += 1 + self.cache = self.fetcher(start, bend) + self.start = start + else: + assert self.start is not None + assert self.end is not None + self.miss_count += 1 + + if start < self.start: + if self.end is None or self.end - end > self.blocksize: + self.total_requested_bytes += bend - start + self.cache = self.fetcher(start, bend) + self.start = start + else: + self.total_requested_bytes += self.start - start + new = self.fetcher(start, self.start) + self.start = start + self.cache = new + self.cache + elif self.end is not None and bend > self.end: + if self.end > self.size: + pass + elif end - self.end > self.blocksize: + self.total_requested_bytes += bend - start + self.cache = self.fetcher(start, bend) + self.start = start + else: + self.total_requested_bytes += bend - self.end + new = self.fetcher(self.end, bend) + self.cache = self.cache + new + + self.end = self.start + len(self.cache) + offset = start - self.start + out = self.cache[offset : offset + end - start] + if self.trim: + num = (self.end - self.start) // (self.blocksize + 1) + if num > 1: + self.start += self.blocksize * num + self.cache = self.cache[self.blocksize * num :] + return out + + def __len__(self) -> int: + return len(self.cache) + + +class AllBytes(BaseCache): + """Cache entire contents of the file""" + + name: ClassVar[str] = "all" + + def __init__( + self, + blocksize: int | None = None, + fetcher: Fetcher | None = None, + size: int | None = None, + data: bytes | None = None, + ) -> None: + super().__init__(blocksize, fetcher, size) # type: ignore[arg-type] + if data is None: + self.miss_count += 1 + self.total_requested_bytes += self.size + data = self.fetcher(0, self.size) + self.data = data + + def _fetch(self, start: int | None, stop: int | None) -> bytes: + self.hit_count += 1 + return self.data[start:stop] + + +class KnownPartsOfAFile(BaseCache): + """ + Cache holding known file parts. + + Parameters + ---------- + blocksize: int + How far to read ahead in numbers of bytes + fetcher: func + Function of the form f(start, end) which gets bytes from remote as + specified + size: int + How big this file is + data: dict + A dictionary mapping explicit `(start, stop)` file-offset tuples + with known bytes. + strict: bool, default True + Whether to fetch reads that go beyond a known byte-range boundary. + If `False`, any read that ends outside a known part will be zero + padded. Note that zero padding will not be used for reads that + begin outside a known byte-range. + """ + + name: ClassVar[str] = "parts" + + def __init__( + self, + blocksize: int, + fetcher: Fetcher, + size: int, + data: dict[tuple[int, int], bytes] | None = None, + strict: bool = True, + **_: Any, + ): + super().__init__(blocksize, fetcher, size) + self.strict = strict + + # simple consolidation of contiguous blocks + if data: + old_offsets = sorted(data.keys()) + offsets = [old_offsets[0]] + blocks = [data.pop(old_offsets[0])] + for start, stop in old_offsets[1:]: + start0, stop0 = offsets[-1] + if start == stop0: + offsets[-1] = (start0, stop) + blocks[-1] += data.pop((start, stop)) + else: + offsets.append((start, stop)) + blocks.append(data.pop((start, stop))) + + self.data = dict(zip(offsets, blocks)) + else: + self.data = {} + + def _fetch(self, start: int | None, stop: int | None) -> bytes: + if start is None: + start = 0 + if stop is None: + stop = self.size + + out = b"" + for (loc0, loc1), data in self.data.items(): + # If self.strict=False, use zero-padded data + # for reads beyond the end of a "known" buffer + if loc0 <= start < loc1: + off = start - loc0 + out = data[off : off + stop - start] + if not self.strict or loc0 <= stop <= loc1: + # The request is within a known range, or + # it begins within a known range, and we + # are allowed to pad reads beyond the + # buffer with zero + out += b"\x00" * (stop - start - len(out)) + self.hit_count += 1 + return out + else: + # The request ends outside a known range, + # and we are being "strict" about reads + # beyond the buffer + start = loc1 + break + + # We only get here if there is a request outside the + # known parts of the file. In an ideal world, this + # should never happen + if self.fetcher is None: + # We cannot fetch the data, so raise an error + raise ValueError(f"Read is outside the known file parts: {(start, stop)}. ") + # We can fetch the data, but should warn the user + # that this may be slow + warnings.warn( + f"Read is outside the known file parts: {(start, stop)}. " + f"IO/caching performance may be poor!" + ) + logger.debug(f"KnownPartsOfAFile cache fetching {start}-{stop}") + self.total_requested_bytes += stop - start + self.miss_count += 1 + return out + super()._fetch(start, stop) + + +class UpdatableLRU(Generic[P, T]): + """ + Custom implementation of LRU cache that allows updating keys + + Used by BackgroudBlockCache + """ + + class CacheInfo(NamedTuple): + hits: int + misses: int + maxsize: int + currsize: int + + def __init__(self, func: Callable[P, T], max_size: int = 128) -> None: + self._cache: OrderedDict[Any, T] = collections.OrderedDict() + self._func = func + self._max_size = max_size + self._hits = 0 + self._misses = 0 + self._lock = threading.Lock() + + def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: + if kwargs: + raise TypeError(f"Got unexpected keyword argument {kwargs.keys()}") + with self._lock: + if args in self._cache: + self._cache.move_to_end(args) + self._hits += 1 + return self._cache[args] + + result = self._func(*args, **kwargs) + + with self._lock: + self._cache[args] = result + self._misses += 1 + if len(self._cache) > self._max_size: + self._cache.popitem(last=False) + + return result + + def is_key_cached(self, *args: Any) -> bool: + with self._lock: + return args in self._cache + + def add_key(self, result: T, *args: Any) -> None: + with self._lock: + self._cache[args] = result + if len(self._cache) > self._max_size: + self._cache.popitem(last=False) + + def cache_info(self) -> UpdatableLRU.CacheInfo: + with self._lock: + return self.CacheInfo( + maxsize=self._max_size, + currsize=len(self._cache), + hits=self._hits, + misses=self._misses, + ) + + +class BackgroundBlockCache(BaseCache): + """ + Cache holding memory as a set of blocks with pre-loading of + the next block in the background. + + Requests are only ever made ``blocksize`` at a time, and are + stored in an LRU cache. The least recently accessed block is + discarded when more than ``maxblocks`` are stored. If the + next block is not in cache, it is loaded in a separate thread + in non-blocking way. + + Parameters + ---------- + blocksize : int + The number of bytes to store in each block. + Requests are only ever made for ``blocksize``, so this + should balance the overhead of making a request against + the granularity of the blocks. + fetcher : Callable + size : int + The total size of the file being cached. + maxblocks : int + The maximum number of blocks to cache for. The maximum memory + use for this cache is then ``blocksize * maxblocks``. + """ + + name: ClassVar[str] = "background" + + def __init__( + self, blocksize: int, fetcher: Fetcher, size: int, maxblocks: int = 32 + ) -> None: + super().__init__(blocksize, fetcher, size) + self.nblocks = math.ceil(size / blocksize) + self.maxblocks = maxblocks + self._fetch_block_cached = UpdatableLRU(self._fetch_block, maxblocks) + + self._thread_executor = ThreadPoolExecutor(max_workers=1) + self._fetch_future_block_number: int | None = None + self._fetch_future: Future[bytes] | None = None + self._fetch_future_lock = threading.Lock() + + def cache_info(self) -> UpdatableLRU.CacheInfo: + """ + The statistics on the block cache. + + Returns + ------- + NamedTuple + Returned directly from the LRU Cache used internally. + """ + return self._fetch_block_cached.cache_info() + + def __getstate__(self) -> dict[str, Any]: + state = self.__dict__ + del state["_fetch_block_cached"] + del state["_thread_executor"] + del state["_fetch_future_block_number"] + del state["_fetch_future"] + del state["_fetch_future_lock"] + return state + + def __setstate__(self, state) -> None: + self.__dict__.update(state) + self._fetch_block_cached = UpdatableLRU(self._fetch_block, state["maxblocks"]) + self._thread_executor = ThreadPoolExecutor(max_workers=1) + self._fetch_future_block_number = None + self._fetch_future = None + self._fetch_future_lock = threading.Lock() + + def _fetch(self, start: int | None, end: int | None) -> bytes: + if start is None: + start = 0 + if end is None: + end = self.size + if start >= self.size or start >= end: + return b"" + + # byte position -> block numbers + start_block_number = start // self.blocksize + end_block_number = end // self.blocksize + + fetch_future_block_number = None + fetch_future = None + with self._fetch_future_lock: + # Background thread is running. Check we we can or must join it. + if self._fetch_future is not None: + assert self._fetch_future_block_number is not None + if self._fetch_future.done(): + logger.info("BlockCache joined background fetch without waiting.") + self._fetch_block_cached.add_key( + self._fetch_future.result(), self._fetch_future_block_number + ) + # Cleanup the fetch variables. Done with fetching the block. + self._fetch_future_block_number = None + self._fetch_future = None + else: + # Must join if we need the block for the current fetch + must_join = bool( + start_block_number + <= self._fetch_future_block_number + <= end_block_number + ) + if must_join: + # Copy to the local variables to release lock + # before waiting for result + fetch_future_block_number = self._fetch_future_block_number + fetch_future = self._fetch_future + + # Cleanup the fetch variables. Have a local copy. + self._fetch_future_block_number = None + self._fetch_future = None + + # Need to wait for the future for the current read + if fetch_future is not None: + logger.info("BlockCache waiting for background fetch.") + # Wait until result and put it in cache + self._fetch_block_cached.add_key( + fetch_future.result(), fetch_future_block_number + ) + + # these are cached, so safe to do multiple calls for the same start and end. + for block_number in range(start_block_number, end_block_number + 1): + self._fetch_block_cached(block_number) + + # fetch next block in the background if nothing is running in the background, + # the block is within file and it is not already cached + end_block_plus_1 = end_block_number + 1 + with self._fetch_future_lock: + if ( + self._fetch_future is None + and end_block_plus_1 <= self.nblocks + and not self._fetch_block_cached.is_key_cached(end_block_plus_1) + ): + self._fetch_future_block_number = end_block_plus_1 + self._fetch_future = self._thread_executor.submit( + self._fetch_block, end_block_plus_1, "async" + ) + + return self._read_cache( + start, + end, + start_block_number=start_block_number, + end_block_number=end_block_number, + ) + + def _fetch_block(self, block_number: int, log_info: str = "sync") -> bytes: + """ + Fetch the block of data for `block_number`. + """ + if block_number > self.nblocks: + raise ValueError( + f"'block_number={block_number}' is greater than " + f"the number of blocks ({self.nblocks})" + ) + + start = block_number * self.blocksize + end = start + self.blocksize + logger.info("BlockCache fetching block (%s) %d", log_info, block_number) + self.total_requested_bytes += end - start + self.miss_count += 1 + block_contents = super()._fetch(start, end) + return block_contents + + def _read_cache( + self, start: int, end: int, start_block_number: int, end_block_number: int + ) -> bytes: + """ + Read from our block cache. + + Parameters + ---------- + start, end : int + The start and end byte positions. + start_block_number, end_block_number : int + The start and end block numbers. + """ + start_pos = start % self.blocksize + end_pos = end % self.blocksize + + # kind of pointless to count this as a hit, but it is + self.hit_count += 1 + + if start_block_number == end_block_number: + block = self._fetch_block_cached(start_block_number) + return block[start_pos:end_pos] + + else: + # read from the initial + out = [self._fetch_block_cached(start_block_number)[start_pos:]] + + # intermediate blocks + # Note: it'd be nice to combine these into one big request. However + # that doesn't play nicely with our LRU cache. + out.extend( + map( + self._fetch_block_cached, + range(start_block_number + 1, end_block_number), + ) + ) + + # final block + out.append(self._fetch_block_cached(end_block_number)[:end_pos]) + + return b"".join(out) + + +caches: dict[str | None, type[BaseCache]] = { + # one custom case + None: BaseCache, +} + + +def register_cache(cls: type[BaseCache], clobber: bool = False) -> None: + """'Register' cache implementation. + + Parameters + ---------- + clobber: bool, optional + If set to True (default is False) - allow to overwrite existing + entry. + + Raises + ------ + ValueError + """ + name = cls.name + if not clobber and name in caches: + raise ValueError(f"Cache with name {name!r} is already known: {caches[name]}") + caches[name] = cls + + +for c in ( + BaseCache, + MMapCache, + BytesCache, + ReadAheadCache, + BlockCache, + FirstChunkCache, + AllBytes, + KnownPartsOfAFile, + BackgroundBlockCache, +): + register_cache(c) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/callbacks.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..7ca99ca6ac3cd69b28bcd1550f6550e8e648c5fe --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/callbacks.py @@ -0,0 +1,324 @@ +from functools import wraps + + +class Callback: + """ + Base class and interface for callback mechanism + + This class can be used directly for monitoring file transfers by + providing ``callback=Callback(hooks=...)`` (see the ``hooks`` argument, + below), or subclassed for more specialised behaviour. + + Parameters + ---------- + size: int (optional) + Nominal quantity for the value that corresponds to a complete + transfer, e.g., total number of tiles or total number of + bytes + value: int (0) + Starting internal counter value + hooks: dict or None + A dict of named functions to be called on each update. The signature + of these must be ``f(size, value, **kwargs)`` + """ + + def __init__(self, size=None, value=0, hooks=None, **kwargs): + self.size = size + self.value = value + self.hooks = hooks or {} + self.kw = kwargs + + def __enter__(self): + return self + + def __exit__(self, *exc_args): + self.close() + + def close(self): + """Close callback.""" + + def branched(self, path_1, path_2, **kwargs): + """ + Return callback for child transfers + + If this callback is operating at a higher level, e.g., put, which may + trigger transfers that can also be monitored. The function returns a callback + that has to be passed to the child method, e.g., put_file, + as `callback=` argument. + + The implementation uses `callback.branch` for compatibility. + When implementing callbacks, it is recommended to override this function instead + of `branch` and avoid calling `super().branched(...)`. + + Prefer using this function over `branch`. + + Parameters + ---------- + path_1: str + Child's source path + path_2: str + Child's destination path + **kwargs: + Arbitrary keyword arguments + + Returns + ------- + callback: Callback + A callback instance to be passed to the child method + """ + self.branch(path_1, path_2, kwargs) + # mutate kwargs so that we can force the caller to pass "callback=" explicitly + return kwargs.pop("callback", DEFAULT_CALLBACK) + + def branch_coro(self, fn): + """ + Wraps a coroutine, and pass a new child callback to it. + """ + + @wraps(fn) + async def func(path1, path2: str, **kwargs): + with self.branched(path1, path2, **kwargs) as child: + return await fn(path1, path2, callback=child, **kwargs) + + return func + + def set_size(self, size): + """ + Set the internal maximum size attribute + + Usually called if not initially set at instantiation. Note that this + triggers a ``call()``. + + Parameters + ---------- + size: int + """ + self.size = size + self.call() + + def absolute_update(self, value): + """ + Set the internal value state + + Triggers ``call()`` + + Parameters + ---------- + value: int + """ + self.value = value + self.call() + + def relative_update(self, inc=1): + """ + Delta increment the internal counter + + Triggers ``call()`` + + Parameters + ---------- + inc: int + """ + self.value += inc + self.call() + + def call(self, hook_name=None, **kwargs): + """ + Execute hook(s) with current state + + Each function is passed the internal size and current value + + Parameters + ---------- + hook_name: str or None + If given, execute on this hook + kwargs: passed on to (all) hook(s) + """ + if not self.hooks: + return + kw = self.kw.copy() + kw.update(kwargs) + if hook_name: + if hook_name not in self.hooks: + return + return self.hooks[hook_name](self.size, self.value, **kw) + for hook in self.hooks.values() or []: + hook(self.size, self.value, **kw) + + def wrap(self, iterable): + """ + Wrap an iterable to call ``relative_update`` on each iterations + + Parameters + ---------- + iterable: Iterable + The iterable that is being wrapped + """ + for item in iterable: + self.relative_update() + yield item + + def branch(self, path_1, path_2, kwargs): + """ + Set callbacks for child transfers + + If this callback is operating at a higher level, e.g., put, which may + trigger transfers that can also be monitored. The passed kwargs are + to be *mutated* to add ``callback=``, if this class supports branching + to children. + + Parameters + ---------- + path_1: str + Child's source path + path_2: str + Child's destination path + kwargs: dict + arguments passed to child method, e.g., put_file. + + Returns + ------- + + """ + return None + + def no_op(self, *_, **__): + pass + + def __getattr__(self, item): + """ + If undefined methods are called on this class, nothing happens + """ + return self.no_op + + @classmethod + def as_callback(cls, maybe_callback=None): + """Transform callback=... into Callback instance + + For the special value of ``None``, return the global instance of + ``NoOpCallback``. This is an alternative to including + ``callback=DEFAULT_CALLBACK`` directly in a method signature. + """ + if maybe_callback is None: + return DEFAULT_CALLBACK + return maybe_callback + + +class NoOpCallback(Callback): + """ + This implementation of Callback does exactly nothing + """ + + def call(self, *args, **kwargs): + return None + + +class DotPrinterCallback(Callback): + """ + Simple example Callback implementation + + Almost identical to Callback with a hook that prints a char; here we + demonstrate how the outer layer may print "#" and the inner layer "." + """ + + def __init__(self, chr_to_print="#", **kwargs): + self.chr = chr_to_print + super().__init__(**kwargs) + + def branch(self, path_1, path_2, kwargs): + """Mutate kwargs to add new instance with different print char""" + kwargs["callback"] = DotPrinterCallback(".") + + def call(self, **kwargs): + """Just outputs a character""" + print(self.chr, end="") + + +class TqdmCallback(Callback): + """ + A callback to display a progress bar using tqdm + + Parameters + ---------- + tqdm_kwargs : dict, (optional) + Any argument accepted by the tqdm constructor. + See the `tqdm doc `_. + Will be forwarded to `tqdm_cls`. + tqdm_cls: (optional) + subclass of `tqdm.tqdm`. If not passed, it will default to `tqdm.tqdm`. + + Examples + -------- + >>> import fsspec + >>> from fsspec.callbacks import TqdmCallback + >>> fs = fsspec.filesystem("memory") + >>> path2distant_data = "/your-path" + >>> fs.upload( + ".", + path2distant_data, + recursive=True, + callback=TqdmCallback(), + ) + + You can forward args to tqdm using the ``tqdm_kwargs`` parameter. + + >>> fs.upload( + ".", + path2distant_data, + recursive=True, + callback=TqdmCallback(tqdm_kwargs={"desc": "Your tqdm description"}), + ) + + You can also customize the progress bar by passing a subclass of `tqdm`. + + .. code-block:: python + + class TqdmFormat(tqdm): + '''Provides a `total_time` format parameter''' + @property + def format_dict(self): + d = super().format_dict + total_time = d["elapsed"] * (d["total"] or 0) / max(d["n"], 1) + d.update(total_time=self.format_interval(total_time) + " in total") + return d + + >>> with TqdmCallback( + tqdm_kwargs={ + "desc": "desc", + "bar_format": "{total_time}: {percentage:.0f}%|{bar}{r_bar}", + }, + tqdm_cls=TqdmFormat, + ) as callback: + fs.upload(".", path2distant_data, recursive=True, callback=callback) + """ + + def __init__(self, tqdm_kwargs=None, *args, **kwargs): + try: + from tqdm import tqdm + + except ImportError as exce: + raise ImportError( + "Using TqdmCallback requires tqdm to be installed" + ) from exce + + self._tqdm_cls = kwargs.pop("tqdm_cls", tqdm) + self._tqdm_kwargs = tqdm_kwargs or {} + self.tqdm = None + super().__init__(*args, **kwargs) + + def call(self, *args, **kwargs): + if self.tqdm is None: + self.tqdm = self._tqdm_cls(total=self.size, **self._tqdm_kwargs) + self.tqdm.total = self.size + self.tqdm.update(self.value - self.tqdm.n) + + def close(self): + if self.tqdm is not None: + self.tqdm.close() + self.tqdm = None + + def __del__(self): + return self.close() + + +DEFAULT_CALLBACK = _DEFAULT_CALLBACK = NoOpCallback() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/compression.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/compression.py new file mode 100644 index 0000000000000000000000000000000000000000..e21da562bbab49c2ad60e9d9beb546af8dadea45 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/compression.py @@ -0,0 +1,182 @@ +"""Helper functions for a standard streaming compression API""" + +from zipfile import ZipFile + +import fsspec.utils +from fsspec.spec import AbstractBufferedFile + + +def noop_file(file, mode, **kwargs): + return file + + +# TODO: files should also be available as contexts +# should be functions of the form func(infile, mode=, **kwargs) -> file-like +compr = {None: noop_file} + + +def register_compression(name, callback, extensions, force=False): + """Register an "inferable" file compression type. + + Registers transparent file compression type for use with fsspec.open. + Compression can be specified by name in open, or "infer"-ed for any files + ending with the given extensions. + + Args: + name: (str) The compression type name. Eg. "gzip". + callback: A callable of form (infile, mode, **kwargs) -> file-like. + Accepts an input file-like object, the target mode and kwargs. + Returns a wrapped file-like object. + extensions: (str, Iterable[str]) A file extension, or list of file + extensions for which to infer this compression scheme. Eg. "gz". + force: (bool) Force re-registration of compression type or extensions. + + Raises: + ValueError: If name or extensions already registered, and not force. + + """ + if isinstance(extensions, str): + extensions = [extensions] + + # Validate registration + if name in compr and not force: + raise ValueError(f"Duplicate compression registration: {name}") + + for ext in extensions: + if ext in fsspec.utils.compressions and not force: + raise ValueError(f"Duplicate compression file extension: {ext} ({name})") + + compr[name] = callback + + for ext in extensions: + fsspec.utils.compressions[ext] = name + + +def unzip(infile, mode="rb", filename=None, **kwargs): + if "r" not in mode: + filename = filename or "file" + z = ZipFile(infile, mode="w", **kwargs) + fo = z.open(filename, mode="w") + fo.close = lambda closer=fo.close: closer() or z.close() + return fo + z = ZipFile(infile) + if filename is None: + filename = z.namelist()[0] + return z.open(filename, mode="r", **kwargs) + + +register_compression("zip", unzip, "zip") + +try: + from bz2 import BZ2File +except ImportError: + pass +else: + register_compression("bz2", BZ2File, "bz2") + +try: # pragma: no cover + from isal import igzip + + def isal(infile, mode="rb", **kwargs): + return igzip.IGzipFile(fileobj=infile, mode=mode, **kwargs) + + register_compression("gzip", isal, "gz") +except ImportError: + from gzip import GzipFile + + register_compression( + "gzip", lambda f, **kwargs: GzipFile(fileobj=f, **kwargs), "gz" + ) + +try: + from lzma import LZMAFile + + register_compression("lzma", LZMAFile, "lzma") + register_compression("xz", LZMAFile, "xz") +except ImportError: + pass + +try: + import lzmaffi + + register_compression("lzma", lzmaffi.LZMAFile, "lzma", force=True) + register_compression("xz", lzmaffi.LZMAFile, "xz", force=True) +except ImportError: + pass + + +class SnappyFile(AbstractBufferedFile): + def __init__(self, infile, mode, **kwargs): + import snappy + + super().__init__( + fs=None, path="snappy", mode=mode.strip("b") + "b", size=999999999, **kwargs + ) + self.infile = infile + if "r" in mode: + self.codec = snappy.StreamDecompressor() + else: + self.codec = snappy.StreamCompressor() + + def _upload_chunk(self, final=False): + self.buffer.seek(0) + out = self.codec.add_chunk(self.buffer.read()) + self.infile.write(out) + return True + + def seek(self, loc, whence=0): + raise NotImplementedError("SnappyFile is not seekable") + + def seekable(self): + return False + + def _fetch_range(self, start, end): + """Get the specified set of bytes from remote""" + data = self.infile.read(end - start) + return self.codec.decompress(data) + + +try: + import snappy + + snappy.compress(b"") + # Snappy may use the .sz file extension, but this is not part of the + # standard implementation. + register_compression("snappy", SnappyFile, []) + +except (ImportError, NameError, AttributeError): + pass + +try: + import lz4.frame + + register_compression("lz4", lz4.frame.open, "lz4") +except ImportError: + pass + +try: + # zstd in the standard library for python >= 3.14 + from compression.zstd import ZstdFile + + register_compression("zstd", ZstdFile, "zst") + +except ImportError: + try: + import zstandard as zstd + + def zstandard_file(infile, mode="rb"): + if "r" in mode: + cctx = zstd.ZstdDecompressor() + return cctx.stream_reader(infile) + else: + cctx = zstd.ZstdCompressor(level=10) + return cctx.stream_writer(infile) + + register_compression("zstd", zstandard_file, "zst") + except ImportError: + pass + + +def available_compressions(): + """Return a list of the implemented compressions.""" + return list(compr) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/config.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/config.py new file mode 100644 index 0000000000000000000000000000000000000000..76d9af14aaf7df47c4551c169f27b05abf9c269e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/config.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +import configparser +import json +import os +import warnings +from typing import Any + +conf: dict[str, dict[str, Any]] = {} +default_conf_dir = os.path.join(os.path.expanduser("~"), ".config/fsspec") +conf_dir = os.environ.get("FSSPEC_CONFIG_DIR", default_conf_dir) + + +def set_conf_env(conf_dict, envdict=os.environ): + """Set config values from environment variables + + Looks for variables of the form ``FSSPEC_`` and + ``FSSPEC__``. For ``FSSPEC_`` the value is parsed + as a json dictionary and used to ``update`` the config of the + corresponding protocol. For ``FSSPEC__`` there is no + attempt to convert the string value, but the kwarg keys will be lower-cased. + + The ``FSSPEC__`` variables are applied after the + ``FSSPEC_`` ones. + + Parameters + ---------- + conf_dict : dict(str, dict) + This dict will be mutated + envdict : dict-like(str, str) + Source for the values - usually the real environment + """ + kwarg_keys = [] + for key in envdict: + if key.startswith("FSSPEC_") and len(key) > 7 and key[7] != "_": + if key.count("_") > 1: + kwarg_keys.append(key) + continue + try: + value = json.loads(envdict[key]) + except json.decoder.JSONDecodeError as ex: + warnings.warn( + f"Ignoring environment variable {key} due to a parse failure: {ex}" + ) + else: + if isinstance(value, dict): + _, proto = key.split("_", 1) + conf_dict.setdefault(proto.lower(), {}).update(value) + else: + warnings.warn( + f"Ignoring environment variable {key} due to not being a dict:" + f" {type(value)}" + ) + elif key.startswith("FSSPEC"): + warnings.warn( + f"Ignoring environment variable {key} due to having an unexpected name" + ) + + for key in kwarg_keys: + _, proto, kwarg = key.split("_", 2) + conf_dict.setdefault(proto.lower(), {})[kwarg.lower()] = envdict[key] + + +def set_conf_files(cdir, conf_dict): + """Set config values from files + + Scans for INI and JSON files in the given dictionary, and uses their + contents to set the config. In case of repeated values, later values + win. + + In the case of INI files, all values are strings, and these will not + be converted. + + Parameters + ---------- + cdir : str + Directory to search + conf_dict : dict(str, dict) + This dict will be mutated + """ + if not os.path.isdir(cdir): + return + allfiles = sorted(os.listdir(cdir)) + for fn in allfiles: + if fn.endswith(".ini"): + ini = configparser.ConfigParser() + ini.read(os.path.join(cdir, fn)) + for key in ini: + if key == "DEFAULT": + continue + conf_dict.setdefault(key, {}).update(dict(ini[key])) + if fn.endswith(".json"): + with open(os.path.join(cdir, fn)) as f: + js = json.load(f) + for key in js: + conf_dict.setdefault(key, {}).update(dict(js[key])) + + +def apply_config(cls, kwargs, conf_dict=None): + """Supply default values for kwargs when instantiating class + + Augments the passed kwargs, by finding entries in the config dict + which match the classes ``.protocol`` attribute (one or more str) + + Parameters + ---------- + cls : file system implementation + kwargs : dict + conf_dict : dict of dict + Typically this is the global configuration + + Returns + ------- + dict : the modified set of kwargs + """ + if conf_dict is None: + conf_dict = conf + protos = cls.protocol if isinstance(cls.protocol, (tuple, list)) else [cls.protocol] + kw = {} + for proto in protos: + # default kwargs from the current state of the config + if proto in conf_dict: + kw.update(conf_dict[proto]) + # explicit kwargs always win + kw.update(**kwargs) + kwargs = kw + return kwargs + + +set_conf_files(conf_dir, conf) +set_conf_env(conf) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/conftest.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..6874a42c4895c3c7b973dc5d63fd4488a4e60b44 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/conftest.py @@ -0,0 +1,55 @@ +import os +import shutil +import subprocess +import sys +import time + +import pytest + +import fsspec +from fsspec.implementations.cached import CachingFileSystem + + +@pytest.fixture() +def m(): + """ + Fixture providing a memory filesystem. + """ + m = fsspec.filesystem("memory") + m.store.clear() + m.pseudo_dirs.clear() + m.pseudo_dirs.append("") + try: + yield m + finally: + m.store.clear() + m.pseudo_dirs.clear() + m.pseudo_dirs.append("") + + +@pytest.fixture +def ftp_writable(tmpdir): + """ + Fixture providing a writable FTP filesystem. + """ + pytest.importorskip("pyftpdlib") + from fsspec.implementations.ftp import FTPFileSystem + + FTPFileSystem.clear_instance_cache() # remove lingering connections + CachingFileSystem.clear_instance_cache() + d = str(tmpdir) + with open(os.path.join(d, "out"), "wb") as f: + f.write(b"hello" * 10000) + P = subprocess.Popen( + [sys.executable, "-m", "pyftpdlib", "-d", d, "-u", "user", "-P", "pass", "-w"] + ) + try: + time.sleep(1) + yield "localhost", 2121, "user", "pass" + finally: + P.terminate() + P.wait() + try: + shutil.rmtree(tmpdir) + except Exception: + pass diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/core.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/core.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e75572bc0e31b5a12faee73275760e421aadb0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/core.py @@ -0,0 +1,743 @@ +from __future__ import annotations + +import io +import logging +import os +import re +from glob import has_magic +from pathlib import Path + +# for backwards compat, we export cache things from here too +from fsspec.caching import ( # noqa: F401 + BaseCache, + BlockCache, + BytesCache, + MMapCache, + ReadAheadCache, + caches, +) +from fsspec.compression import compr +from fsspec.config import conf +from fsspec.registry import filesystem, get_filesystem_class +from fsspec.utils import ( + _unstrip_protocol, + build_name_function, + infer_compression, + stringify_path, +) + +logger = logging.getLogger("fsspec") + + +class OpenFile: + """ + File-like object to be used in a context + + Can layer (buffered) text-mode and compression over any file-system, which + are typically binary-only. + + These instances are safe to serialize, as the low-level file object + is not created until invoked using ``with``. + + Parameters + ---------- + fs: FileSystem + The file system to use for opening the file. Should be a subclass or duck-type + with ``fsspec.spec.AbstractFileSystem`` + path: str + Location to open + mode: str like 'rb', optional + Mode of the opened file + compression: str or None, optional + Compression to apply + encoding: str or None, optional + The encoding to use if opened in text mode. + errors: str or None, optional + How to handle encoding errors if opened in text mode. + newline: None or str + Passed to TextIOWrapper in text mode, how to handle line endings. + autoopen: bool + If True, calls open() immediately. Mostly used by pickle + pos: int + If given and autoopen is True, seek to this location immediately + """ + + def __init__( + self, + fs, + path, + mode="rb", + compression=None, + encoding=None, + errors=None, + newline=None, + ): + self.fs = fs + self.path = path + self.mode = mode + self.compression = get_compression(path, compression) + self.encoding = encoding + self.errors = errors + self.newline = newline + self.fobjects = [] + + def __reduce__(self): + return ( + OpenFile, + ( + self.fs, + self.path, + self.mode, + self.compression, + self.encoding, + self.errors, + self.newline, + ), + ) + + def __repr__(self): + return f"" + + def __enter__(self): + mode = self.mode.replace("t", "").replace("b", "") + "b" + + try: + f = self.fs.open(self.path, mode=mode) + except FileNotFoundError as e: + if has_magic(self.path): + raise FileNotFoundError( + "%s not found. The URL contains glob characters: you maybe needed\n" + "to pass expand=True in fsspec.open() or the storage_options of \n" + "your library. You can also set the config value 'open_expand'\n" + "before import, or fsspec.core.DEFAULT_EXPAND at runtime, to True.", + self.path, + ) from e + raise + + self.fobjects = [f] + + if self.compression is not None: + compress = compr[self.compression] + f = compress(f, mode=mode[0]) + self.fobjects.append(f) + + if "b" not in self.mode: + # assume, for example, that 'r' is equivalent to 'rt' as in builtin + f = PickleableTextIOWrapper( + f, encoding=self.encoding, errors=self.errors, newline=self.newline + ) + self.fobjects.append(f) + + return self.fobjects[-1] + + def __exit__(self, *args): + self.close() + + @property + def full_name(self): + return _unstrip_protocol(self.path, self.fs) + + def open(self): + """Materialise this as a real open file without context + + The OpenFile object should be explicitly closed to avoid enclosed file + instances persisting. You must, therefore, keep a reference to the OpenFile + during the life of the file-like it generates. + """ + return self.__enter__() + + def close(self): + """Close all encapsulated file objects""" + for f in reversed(self.fobjects): + if "r" not in self.mode and not f.closed: + f.flush() + f.close() + self.fobjects.clear() + + +class OpenFiles(list): + """List of OpenFile instances + + Can be used in a single context, which opens and closes all of the + contained files. Normal list access to get the elements works as + normal. + + A special case is made for caching filesystems - the files will + be down/uploaded together at the start or end of the context, and + this may happen concurrently, if the target filesystem supports it. + """ + + def __init__(self, *args, mode="rb", fs=None): + self.mode = mode + self.fs = fs + self.files = [] + super().__init__(*args) + + def __enter__(self): + if self.fs is None: + raise ValueError("Context has already been used") + + fs = self.fs + while True: + if hasattr(fs, "open_many"): + # check for concurrent cache download; or set up for upload + self.files = fs.open_many(self) + return self.files + if hasattr(fs, "fs") and fs.fs is not None: + fs = fs.fs + else: + break + return [s.__enter__() for s in self] + + def __exit__(self, *args): + fs = self.fs + [s.__exit__(*args) for s in self] + if "r" not in self.mode: + while True: + if hasattr(fs, "open_many"): + # check for concurrent cache upload + fs.commit_many(self.files) + return + if hasattr(fs, "fs") and fs.fs is not None: + fs = fs.fs + else: + break + + def __getitem__(self, item): + out = super().__getitem__(item) + if isinstance(item, slice): + return OpenFiles(out, mode=self.mode, fs=self.fs) + return out + + def __repr__(self): + return f"" + + +def open_files( + urlpath, + mode="rb", + compression=None, + encoding="utf8", + errors=None, + name_function=None, + num=1, + protocol=None, + newline=None, + auto_mkdir=True, + expand=True, + **kwargs, +): + """Given a path or paths, return a list of ``OpenFile`` objects. + + For writing, a str path must contain the "*" character, which will be filled + in by increasing numbers, e.g., "part*" -> "part1", "part2" if num=2. + + For either reading or writing, can instead provide explicit list of paths. + + Parameters + ---------- + urlpath: string or list + Absolute or relative filepath(s). Prefix with a protocol like ``s3://`` + to read from alternative filesystems. To read from multiple files you + can pass a globstring or a list of paths, with the caveat that they + must all have the same protocol. + mode: 'rb', 'wt', etc. + compression: string or None + If given, open file using compression codec. Can either be a compression + name (a key in ``fsspec.compression.compr``) or "infer" to guess the + compression from the filename suffix. + encoding: str + For text mode only + errors: None or str + Passed to TextIOWrapper in text mode + name_function: function or None + if opening a set of files for writing, those files do not yet exist, + so we need to generate their names by formatting the urlpath for + each sequence number + num: int [1] + if writing mode, number of files we expect to create (passed to + name+function) + protocol: str or None + If given, overrides the protocol found in the URL. + newline: bytes or None + Used for line terminator in text mode. If None, uses system default; + if blank, uses no translation. + auto_mkdir: bool (True) + If in write mode, this will ensure the target directory exists before + writing, by calling ``fs.mkdirs(exist_ok=True)``. + expand: bool + **kwargs: dict + Extra options that make sense to a particular storage connection, e.g. + host, port, username, password, etc. + + Examples + -------- + >>> files = open_files('2015-*-*.csv') # doctest: +SKIP + >>> files = open_files( + ... 's3://bucket/2015-*-*.csv.gz', compression='gzip' + ... ) # doctest: +SKIP + + Returns + ------- + An ``OpenFiles`` instance, which is a list of ``OpenFile`` objects that can + be used as a single context + + Notes + ----- + For a full list of the available protocols and the implementations that + they map across to see the latest online documentation: + + - For implementations built into ``fsspec`` see + https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations + - For implementations in separate packages see + https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations + """ + fs, fs_token, paths = get_fs_token_paths( + urlpath, + mode, + num=num, + name_function=name_function, + storage_options=kwargs, + protocol=protocol, + expand=expand, + ) + if fs.protocol == "file": + fs.auto_mkdir = auto_mkdir + elif "r" not in mode and auto_mkdir: + parents = {fs._parent(path) for path in paths} + for parent in parents: + try: + fs.makedirs(parent, exist_ok=True) + except PermissionError: + pass + return OpenFiles( + [ + OpenFile( + fs, + path, + mode=mode, + compression=compression, + encoding=encoding, + errors=errors, + newline=newline, + ) + for path in paths + ], + mode=mode, + fs=fs, + ) + + +def _un_chain(path, kwargs): + # Avoid a circular import + from fsspec.implementations.cached import CachingFileSystem + + if "::" in path: + x = re.compile(".*[^a-z]+.*") # test for non protocol-like single word + bits = [] + for p in path.split("::"): + if "://" in p or x.match(p): + bits.append(p) + else: + bits.append(p + "://") + else: + bits = [path] + # [[url, protocol, kwargs], ...] + out = [] + previous_bit = None + kwargs = kwargs.copy() + for bit in reversed(bits): + protocol = kwargs.pop("protocol", None) or split_protocol(bit)[0] or "file" + cls = get_filesystem_class(protocol) + extra_kwargs = cls._get_kwargs_from_urls(bit) + kws = kwargs.pop(protocol, {}) + if bit is bits[0]: + kws.update(kwargs) + kw = dict( + **{k: v for k, v in extra_kwargs.items() if k not in kws or v != kws[k]}, + **kws, + ) + bit = cls._strip_protocol(bit) + if "target_protocol" not in kw and issubclass(cls, CachingFileSystem): + bit = previous_bit + out.append((bit, protocol, kw)) + previous_bit = bit + out.reverse() + return out + + +def url_to_fs(url, **kwargs): + """ + Turn fully-qualified and potentially chained URL into filesystem instance + + Parameters + ---------- + url : str + The fsspec-compatible URL + **kwargs: dict + Extra options that make sense to a particular storage connection, e.g. + host, port, username, password, etc. + + Returns + ------- + filesystem : FileSystem + The new filesystem discovered from ``url`` and created with + ``**kwargs``. + urlpath : str + The file-systems-specific URL for ``url``. + """ + url = stringify_path(url) + # non-FS arguments that appear in fsspec.open() + # inspect could keep this in sync with open()'s signature + known_kwargs = { + "compression", + "encoding", + "errors", + "expand", + "mode", + "name_function", + "newline", + "num", + } + kwargs = {k: v for k, v in kwargs.items() if k not in known_kwargs} + chain = _un_chain(url, kwargs) + inkwargs = {} + # Reverse iterate the chain, creating a nested target_* structure + for i, ch in enumerate(reversed(chain)): + urls, protocol, kw = ch + if i == len(chain) - 1: + inkwargs = dict(**kw, **inkwargs) + continue + inkwargs["target_options"] = dict(**kw, **inkwargs) + inkwargs["target_protocol"] = protocol + inkwargs["fo"] = urls + urlpath, protocol, _ = chain[0] + fs = filesystem(protocol, **inkwargs) + return fs, urlpath + + +DEFAULT_EXPAND = conf.get("open_expand", False) + + +def open( + urlpath, + mode="rb", + compression=None, + encoding="utf8", + errors=None, + protocol=None, + newline=None, + expand=None, + **kwargs, +): + """Given a path or paths, return one ``OpenFile`` object. + + Parameters + ---------- + urlpath: string or list + Absolute or relative filepath. Prefix with a protocol like ``s3://`` + to read from alternative filesystems. Should not include glob + character(s). + mode: 'rb', 'wt', etc. + compression: string or None + If given, open file using compression codec. Can either be a compression + name (a key in ``fsspec.compression.compr``) or "infer" to guess the + compression from the filename suffix. + encoding: str + For text mode only + errors: None or str + Passed to TextIOWrapper in text mode + protocol: str or None + If given, overrides the protocol found in the URL. + newline: bytes or None + Used for line terminator in text mode. If None, uses system default; + if blank, uses no translation. + expand: bool or None + Whether to regard file paths containing special glob characters as needing + expansion (finding the first match) or absolute. Setting False allows using + paths which do embed such characters. If None (default), this argument + takes its value from the DEFAULT_EXPAND module variable, which takes + its initial value from the "open_expand" config value at startup, which will + be False if not set. + **kwargs: dict + Extra options that make sense to a particular storage connection, e.g. + host, port, username, password, etc. + + Examples + -------- + >>> openfile = open('2015-01-01.csv') # doctest: +SKIP + >>> openfile = open( + ... 's3://bucket/2015-01-01.csv.gz', compression='gzip' + ... ) # doctest: +SKIP + >>> with openfile as f: + ... df = pd.read_csv(f) # doctest: +SKIP + ... + + Returns + ------- + ``OpenFile`` object. + + Notes + ----- + For a full list of the available protocols and the implementations that + they map across to see the latest online documentation: + + - For implementations built into ``fsspec`` see + https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations + - For implementations in separate packages see + https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations + """ + expand = DEFAULT_EXPAND if expand is None else expand + out = open_files( + urlpath=[urlpath], + mode=mode, + compression=compression, + encoding=encoding, + errors=errors, + protocol=protocol, + newline=newline, + expand=expand, + **kwargs, + ) + if not out: + raise FileNotFoundError(urlpath) + return out[0] + + +def open_local( + url: str | list[str] | Path | list[Path], + mode: str = "rb", + **storage_options: dict, +) -> str | list[str]: + """Open file(s) which can be resolved to local + + For files which either are local, or get downloaded upon open + (e.g., by file caching) + + Parameters + ---------- + url: str or list(str) + mode: str + Must be read mode + storage_options: + passed on to FS for or used by open_files (e.g., compression) + """ + if "r" not in mode: + raise ValueError("Can only ensure local files when reading") + of = open_files(url, mode=mode, **storage_options) + if not getattr(of[0].fs, "local_file", False): + raise ValueError( + "open_local can only be used on a filesystem which" + " has attribute local_file=True" + ) + with of as files: + paths = [f.name for f in files] + if (isinstance(url, str) and not has_magic(url)) or isinstance(url, Path): + return paths[0] + return paths + + +def get_compression(urlpath, compression): + if compression == "infer": + compression = infer_compression(urlpath) + if compression is not None and compression not in compr: + raise ValueError(f"Compression type {compression} not supported") + return compression + + +def split_protocol(urlpath): + """Return protocol, path pair""" + urlpath = stringify_path(urlpath) + if "://" in urlpath: + protocol, path = urlpath.split("://", 1) + if len(protocol) > 1: + # excludes Windows paths + return protocol, path + if urlpath.startswith("data:"): + return urlpath.split(":", 1) + return None, urlpath + + +def strip_protocol(urlpath): + """Return only path part of full URL, according to appropriate backend""" + protocol, _ = split_protocol(urlpath) + cls = get_filesystem_class(protocol) + return cls._strip_protocol(urlpath) + + +def expand_paths_if_needed(paths, mode, num, fs, name_function): + """Expand paths if they have a ``*`` in them (write mode) or any of ``*?[]`` + in them (read mode). + + :param paths: list of paths + mode: str + Mode in which to open files. + num: int + If opening in writing mode, number of files we expect to create. + fs: filesystem object + name_function: callable + If opening in writing mode, this callable is used to generate path + names. Names are generated for each partition by + ``urlpath.replace('*', name_function(partition_index))``. + :return: list of paths + """ + expanded_paths = [] + paths = list(paths) + + if "w" in mode: # read mode + if sum(1 for p in paths if "*" in p) > 1: + raise ValueError( + "When writing data, only one filename mask can be specified." + ) + num = max(num, len(paths)) + + for curr_path in paths: + if "*" in curr_path: + # expand using name_function + expanded_paths.extend(_expand_paths(curr_path, name_function, num)) + else: + expanded_paths.append(curr_path) + # if we generated more paths that asked for, trim the list + if len(expanded_paths) > num: + expanded_paths = expanded_paths[:num] + + else: # read mode + for curr_path in paths: + if has_magic(curr_path): + # expand using glob + expanded_paths.extend(fs.glob(curr_path)) + else: + expanded_paths.append(curr_path) + + return expanded_paths + + +def get_fs_token_paths( + urlpath, + mode="rb", + num=1, + name_function=None, + storage_options=None, + protocol=None, + expand=True, +): + """Filesystem, deterministic token, and paths from a urlpath and options. + + Parameters + ---------- + urlpath: string or iterable + Absolute or relative filepath, URL (may include protocols like + ``s3://``), or globstring pointing to data. + mode: str, optional + Mode in which to open files. + num: int, optional + If opening in writing mode, number of files we expect to create. + name_function: callable, optional + If opening in writing mode, this callable is used to generate path + names. Names are generated for each partition by + ``urlpath.replace('*', name_function(partition_index))``. + storage_options: dict, optional + Additional keywords to pass to the filesystem class. + protocol: str or None + To override the protocol specifier in the URL + expand: bool + Expand string paths for writing, assuming the path is a directory + """ + if isinstance(urlpath, (list, tuple, set)): + if not urlpath: + raise ValueError("empty urlpath sequence") + urlpath0 = stringify_path(next(iter(urlpath))) + else: + urlpath0 = stringify_path(urlpath) + storage_options = storage_options or {} + if protocol: + storage_options["protocol"] = protocol + chain = _un_chain(urlpath0, storage_options or {}) + inkwargs = {} + # Reverse iterate the chain, creating a nested target_* structure + for i, ch in enumerate(reversed(chain)): + urls, nested_protocol, kw = ch + if i == len(chain) - 1: + inkwargs = dict(**kw, **inkwargs) + continue + inkwargs["target_options"] = dict(**kw, **inkwargs) + inkwargs["target_protocol"] = nested_protocol + inkwargs["fo"] = urls + paths, protocol, _ = chain[0] + fs = filesystem(protocol, **inkwargs) + if isinstance(urlpath, (list, tuple, set)): + pchains = [ + _un_chain(stringify_path(u), storage_options or {})[0] for u in urlpath + ] + if len({pc[1] for pc in pchains}) > 1: + raise ValueError("Protocol mismatch getting fs from %s", urlpath) + paths = [pc[0] for pc in pchains] + else: + paths = fs._strip_protocol(paths) + if isinstance(paths, (list, tuple, set)): + if expand: + paths = expand_paths_if_needed(paths, mode, num, fs, name_function) + elif not isinstance(paths, list): + paths = list(paths) + else: + if ("w" in mode or "x" in mode) and expand: + paths = _expand_paths(paths, name_function, num) + elif "*" in paths: + paths = [f for f in sorted(fs.glob(paths)) if not fs.isdir(f)] + else: + paths = [paths] + + return fs, fs._fs_token, paths + + +def _expand_paths(path, name_function, num): + if isinstance(path, str): + if path.count("*") > 1: + raise ValueError("Output path spec must contain exactly one '*'.") + elif "*" not in path: + path = os.path.join(path, "*.part") + + if name_function is None: + name_function = build_name_function(num - 1) + + paths = [path.replace("*", name_function(i)) for i in range(num)] + if paths != sorted(paths): + logger.warning( + "In order to preserve order between partitions" + " paths created with ``name_function`` should " + "sort to partition order" + ) + elif isinstance(path, (tuple, list)): + assert len(path) == num + paths = list(path) + else: + raise ValueError( + "Path should be either\n" + "1. A list of paths: ['foo.json', 'bar.json', ...]\n" + "2. A directory: 'foo/\n" + "3. A path with a '*' in it: 'foo.*.json'" + ) + return paths + + +class PickleableTextIOWrapper(io.TextIOWrapper): + """TextIOWrapper cannot be pickled. This solves it. + + Requires that ``buffer`` be pickleable, which all instances of + AbstractBufferedFile are. + """ + + def __init__( + self, + buffer, + encoding=None, + errors=None, + newline=None, + line_buffering=False, + write_through=False, + ): + self.args = buffer, encoding, errors, newline, line_buffering, write_through + super().__init__(*self.args) + + def __reduce__(self): + return PickleableTextIOWrapper, self.args diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/dircache.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/dircache.py new file mode 100644 index 0000000000000000000000000000000000000000..eca19566b135e5a7a4f6e7407d56411ec58bfe44 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/dircache.py @@ -0,0 +1,98 @@ +import time +from collections.abc import MutableMapping +from functools import lru_cache + + +class DirCache(MutableMapping): + """ + Caching of directory listings, in a structure like:: + + {"path0": [ + {"name": "path0/file0", + "size": 123, + "type": "file", + ... + }, + {"name": "path0/file1", + }, + ... + ], + "path1": [...] + } + + Parameters to this class control listing expiry or indeed turn + caching off + """ + + def __init__( + self, + use_listings_cache=True, + listings_expiry_time=None, + max_paths=None, + **kwargs, + ): + """ + + Parameters + ---------- + use_listings_cache: bool + If False, this cache never returns items, but always reports KeyError, + and setting items has no effect + listings_expiry_time: int or float (optional) + Time in seconds that a listing is considered valid. If None, + listings do not expire. + max_paths: int (optional) + The number of most recent listings that are considered valid; 'recent' + refers to when the entry was set. + """ + self._cache = {} + self._times = {} + if max_paths: + self._q = lru_cache(max_paths + 1)(lambda key: self._cache.pop(key, None)) + self.use_listings_cache = use_listings_cache + self.listings_expiry_time = listings_expiry_time + self.max_paths = max_paths + + def __getitem__(self, item): + if self.listings_expiry_time is not None: + if self._times.get(item, 0) - time.time() < -self.listings_expiry_time: + del self._cache[item] + if self.max_paths: + self._q(item) + return self._cache[item] # maybe raises KeyError + + def clear(self): + self._cache.clear() + + def __len__(self): + return len(self._cache) + + def __contains__(self, item): + try: + self[item] + return True + except KeyError: + return False + + def __setitem__(self, key, value): + if not self.use_listings_cache: + return + if self.max_paths: + self._q(key) + self._cache[key] = value + if self.listings_expiry_time is not None: + self._times[key] = time.time() + + def __delitem__(self, key): + del self._cache[key] + + def __iter__(self): + entries = list(self._cache) + + return (k for k in entries if k in self) + + def __reduce__(self): + return ( + DirCache, + (self.use_listings_cache, self.listings_expiry_time, self.max_paths), + ) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/exceptions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..ae8905475f02655f4fc5863931d99ca9da55db78 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/exceptions.py @@ -0,0 +1,18 @@ +""" +fsspec user-defined exception classes +""" + +import asyncio + + +class BlocksizeMismatchError(ValueError): + """ + Raised when a cached file is opened with a different blocksize than it was + written with + """ + + +class FSTimeoutError(asyncio.TimeoutError): + """ + Raised when a fsspec function timed out occurs + """ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/fuse.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/fuse.py new file mode 100644 index 0000000000000000000000000000000000000000..566d520fce3e94e3bbaee48c3c6acc9f1db315a8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/fuse.py @@ -0,0 +1,324 @@ +import argparse +import logging +import os +import stat +import threading +import time +from errno import EIO, ENOENT + +from fuse import FUSE, FuseOSError, LoggingMixIn, Operations + +from fsspec import __version__ +from fsspec.core import url_to_fs + +logger = logging.getLogger("fsspec.fuse") + + +class FUSEr(Operations): + def __init__(self, fs, path, ready_file=False): + self.fs = fs + self.cache = {} + self.root = path.rstrip("/") + "/" + self.counter = 0 + logger.info("Starting FUSE at %s", path) + self._ready_file = ready_file + + def getattr(self, path, fh=None): + logger.debug("getattr %s", path) + if self._ready_file and path in ["/.fuse_ready", ".fuse_ready"]: + return {"type": "file", "st_size": 5} + + path = "".join([self.root, path.lstrip("/")]).rstrip("/") + try: + info = self.fs.info(path) + except FileNotFoundError as exc: + raise FuseOSError(ENOENT) from exc + + data = {"st_uid": info.get("uid", 1000), "st_gid": info.get("gid", 1000)} + perm = info.get("mode", 0o777) + + if info["type"] != "file": + data["st_mode"] = stat.S_IFDIR | perm + data["st_size"] = 0 + data["st_blksize"] = 0 + else: + data["st_mode"] = stat.S_IFREG | perm + data["st_size"] = info["size"] + data["st_blksize"] = 5 * 2**20 + data["st_nlink"] = 1 + data["st_atime"] = info["atime"] if "atime" in info else time.time() + data["st_ctime"] = info["ctime"] if "ctime" in info else time.time() + data["st_mtime"] = info["mtime"] if "mtime" in info else time.time() + return data + + def readdir(self, path, fh): + logger.debug("readdir %s", path) + path = "".join([self.root, path.lstrip("/")]) + files = self.fs.ls(path, False) + files = [os.path.basename(f.rstrip("/")) for f in files] + return [".", ".."] + files + + def mkdir(self, path, mode): + path = "".join([self.root, path.lstrip("/")]) + self.fs.mkdir(path) + return 0 + + def rmdir(self, path): + path = "".join([self.root, path.lstrip("/")]) + self.fs.rmdir(path) + return 0 + + def read(self, path, size, offset, fh): + logger.debug("read %s", (path, size, offset)) + if self._ready_file and path in ["/.fuse_ready", ".fuse_ready"]: + # status indicator + return b"ready" + + f = self.cache[fh] + f.seek(offset) + out = f.read(size) + return out + + def write(self, path, data, offset, fh): + logger.debug("write %s", (path, offset)) + f = self.cache[fh] + f.seek(offset) + f.write(data) + return len(data) + + def create(self, path, flags, fi=None): + logger.debug("create %s", (path, flags)) + fn = "".join([self.root, path.lstrip("/")]) + self.fs.touch(fn) # OS will want to get attributes immediately + f = self.fs.open(fn, "wb") + self.cache[self.counter] = f + self.counter += 1 + return self.counter - 1 + + def open(self, path, flags): + logger.debug("open %s", (path, flags)) + fn = "".join([self.root, path.lstrip("/")]) + if flags % 2 == 0: + # read + mode = "rb" + else: + # write/create + mode = "wb" + self.cache[self.counter] = self.fs.open(fn, mode) + self.counter += 1 + return self.counter - 1 + + def truncate(self, path, length, fh=None): + fn = "".join([self.root, path.lstrip("/")]) + if length != 0: + raise NotImplementedError + # maybe should be no-op since open with write sets size to zero anyway + self.fs.touch(fn) + + def unlink(self, path): + fn = "".join([self.root, path.lstrip("/")]) + try: + self.fs.rm(fn, False) + except (OSError, FileNotFoundError) as exc: + raise FuseOSError(EIO) from exc + + def release(self, path, fh): + try: + if fh in self.cache: + f = self.cache[fh] + f.close() + self.cache.pop(fh) + except Exception as e: + print(e) + return 0 + + def chmod(self, path, mode): + if hasattr(self.fs, "chmod"): + path = "".join([self.root, path.lstrip("/")]) + return self.fs.chmod(path, mode) + raise NotImplementedError + + +def run( + fs, + path, + mount_point, + foreground=True, + threads=False, + ready_file=False, + ops_class=FUSEr, +): + """Mount stuff in a local directory + + This uses fusepy to make it appear as if a given path on an fsspec + instance is in fact resident within the local file-system. + + This requires that fusepy by installed, and that FUSE be available on + the system (typically requiring a package to be installed with + apt, yum, brew, etc.). + + Parameters + ---------- + fs: file-system instance + From one of the compatible implementations + path: str + Location on that file-system to regard as the root directory to + mount. Note that you typically should include the terminating "/" + character. + mount_point: str + An empty directory on the local file-system where the contents of + the remote path will appear. + foreground: bool + Whether or not calling this function will block. Operation will + typically be more stable if True. + threads: bool + Whether or not to create threads when responding to file operations + within the mounter directory. Operation will typically be more + stable if False. + ready_file: bool + Whether the FUSE process is ready. The ``.fuse_ready`` file will + exist in the ``mount_point`` directory if True. Debugging purpose. + ops_class: FUSEr or Subclass of FUSEr + To override the default behavior of FUSEr. For Example, logging + to file. + + """ + func = lambda: FUSE( + ops_class(fs, path, ready_file=ready_file), + mount_point, + nothreads=not threads, + foreground=foreground, + ) + if not foreground: + th = threading.Thread(target=func) + th.daemon = True + th.start() + return th + else: # pragma: no cover + try: + func() + except KeyboardInterrupt: + pass + + +def main(args): + """Mount filesystem from chained URL to MOUNT_POINT. + + Examples: + + python3 -m fsspec.fuse memory /usr/share /tmp/mem + + python3 -m fsspec.fuse local /tmp/source /tmp/local \\ + -l /tmp/fsspecfuse.log + + You can also mount chained-URLs and use special settings: + + python3 -m fsspec.fuse 'filecache::zip::file://data.zip' \\ + / /tmp/zip \\ + -o 'filecache-cache_storage=/tmp/simplecache' + + You can specify the type of the setting by using `[int]` or `[bool]`, + (`true`, `yes`, `1` represents the Boolean value `True`): + + python3 -m fsspec.fuse 'simplecache::ftp://ftp1.at.proftpd.org' \\ + /historic/packages/RPMS /tmp/ftp \\ + -o 'simplecache-cache_storage=/tmp/simplecache' \\ + -o 'simplecache-check_files=false[bool]' \\ + -o 'ftp-listings_expiry_time=60[int]' \\ + -o 'ftp-username=anonymous' \\ + -o 'ftp-password=xieyanbo' + """ + + class RawDescriptionArgumentParser(argparse.ArgumentParser): + def format_help(self): + usage = super().format_help() + parts = usage.split("\n\n") + parts[1] = self.description.rstrip() + return "\n\n".join(parts) + + parser = RawDescriptionArgumentParser(prog="fsspec.fuse", description=main.__doc__) + parser.add_argument("--version", action="version", version=__version__) + parser.add_argument("url", type=str, help="fs url") + parser.add_argument("source_path", type=str, help="source directory in fs") + parser.add_argument("mount_point", type=str, help="local directory") + parser.add_argument( + "-o", + "--option", + action="append", + help="Any options of protocol included in the chained URL", + ) + parser.add_argument( + "-l", "--log-file", type=str, help="Logging FUSE debug info (Default: '')" + ) + parser.add_argument( + "-f", + "--foreground", + action="store_false", + help="Running in foreground or not (Default: False)", + ) + parser.add_argument( + "-t", + "--threads", + action="store_false", + help="Running with threads support (Default: False)", + ) + parser.add_argument( + "-r", + "--ready-file", + action="store_false", + help="The `.fuse_ready` file will exist after FUSE is ready. " + "(Debugging purpose, Default: False)", + ) + args = parser.parse_args(args) + + kwargs = {} + for item in args.option or []: + key, sep, value = item.partition("=") + if not sep: + parser.error(message=f"Wrong option: {item!r}") + val = value.lower() + if val.endswith("[int]"): + value = int(value[: -len("[int]")]) + elif val.endswith("[bool]"): + value = val[: -len("[bool]")] in ["1", "yes", "true"] + + if "-" in key: + fs_name, setting_name = key.split("-", 1) + if fs_name in kwargs: + kwargs[fs_name][setting_name] = value + else: + kwargs[fs_name] = {setting_name: value} + else: + kwargs[key] = value + + if args.log_file: + logging.basicConfig( + level=logging.DEBUG, + filename=args.log_file, + format="%(asctime)s %(message)s", + ) + + class LoggingFUSEr(FUSEr, LoggingMixIn): + pass + + fuser = LoggingFUSEr + else: + fuser = FUSEr + + fs, url_path = url_to_fs(args.url, **kwargs) + logger.debug("Mounting %s to %s", url_path, str(args.mount_point)) + run( + fs, + args.source_path, + args.mount_point, + foreground=args.foreground, + threads=args.threads, + ready_file=args.ready_file, + ops_class=fuser, + ) + + +if __name__ == "__main__": + import sys + + main(sys.argv[1:]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/generic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/generic.py new file mode 100644 index 0000000000000000000000000000000000000000..2156d354a87bcf044bef04a62b4d61f5864cf33c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/generic.py @@ -0,0 +1,394 @@ +from __future__ import annotations + +import inspect +import logging +import os +import shutil +import uuid + +from .asyn import AsyncFileSystem, _run_coros_in_chunks, sync_wrapper +from .callbacks import DEFAULT_CALLBACK +from .core import filesystem, get_filesystem_class, split_protocol, url_to_fs + +_generic_fs = {} +logger = logging.getLogger("fsspec.generic") + + +def set_generic_fs(protocol, **storage_options): + """Populate the dict used for method=="generic" lookups""" + _generic_fs[protocol] = filesystem(protocol, **storage_options) + + +def _resolve_fs(url, method, protocol=None, storage_options=None): + """Pick instance of backend FS""" + url = url[0] if isinstance(url, (list, tuple)) else url + protocol = protocol or split_protocol(url)[0] + storage_options = storage_options or {} + if method == "default": + return filesystem(protocol) + if method == "generic": + return _generic_fs[protocol] + if method == "current": + cls = get_filesystem_class(protocol) + return cls.current() + if method == "options": + fs, _ = url_to_fs(url, **storage_options.get(protocol, {})) + return fs + raise ValueError(f"Unknown FS resolution method: {method}") + + +def rsync( + source, + destination, + delete_missing=False, + source_field="size", + dest_field="size", + update_cond="different", + inst_kwargs=None, + fs=None, + **kwargs, +): + """Sync files between two directory trees + + (experimental) + + Parameters + ---------- + source: str + Root of the directory tree to take files from. This must be a directory, but + do not include any terminating "/" character + destination: str + Root path to copy into. The contents of this location should be + identical to the contents of ``source`` when done. This will be made a + directory, and the terminal "/" should not be included. + delete_missing: bool + If there are paths in the destination that don't exist in the + source and this is True, delete them. Otherwise, leave them alone. + source_field: str | callable + If ``update_field`` is "different", this is the key in the info + of source files to consider for difference. Maybe a function of the + info dict. + dest_field: str | callable + If ``update_field`` is "different", this is the key in the info + of destination files to consider for difference. May be a function of + the info dict. + update_cond: "different"|"always"|"never" + If "always", every file is copied, regardless of whether it exists in + the destination. If "never", files that exist in the destination are + not copied again. If "different" (default), only copy if the info + fields given by ``source_field`` and ``dest_field`` (usually "size") + are different. Other comparisons may be added in the future. + inst_kwargs: dict|None + If ``fs`` is None, use this set of keyword arguments to make a + GenericFileSystem instance + fs: GenericFileSystem|None + Instance to use if explicitly given. The instance defines how to + to make downstream file system instances from paths. + + Returns + ------- + dict of the copy operations that were performed, {source: destination} + """ + fs = fs or GenericFileSystem(**(inst_kwargs or {})) + source = fs._strip_protocol(source) + destination = fs._strip_protocol(destination) + allfiles = fs.find(source, withdirs=True, detail=True) + if not fs.isdir(source): + raise ValueError("Can only rsync on a directory") + otherfiles = fs.find(destination, withdirs=True, detail=True) + dirs = [ + a + for a, v in allfiles.items() + if v["type"] == "directory" and a.replace(source, destination) not in otherfiles + ] + logger.debug(f"{len(dirs)} directories to create") + if dirs: + fs.make_many_dirs( + [dirn.replace(source, destination) for dirn in dirs], exist_ok=True + ) + allfiles = {a: v for a, v in allfiles.items() if v["type"] == "file"} + logger.debug(f"{len(allfiles)} files to consider for copy") + to_delete = [ + o + for o, v in otherfiles.items() + if o.replace(destination, source) not in allfiles and v["type"] == "file" + ] + for k, v in allfiles.copy().items(): + otherfile = k.replace(source, destination) + if otherfile in otherfiles: + if update_cond == "always": + allfiles[k] = otherfile + elif update_cond == "different": + inf1 = source_field(v) if callable(source_field) else v[source_field] + v2 = otherfiles[otherfile] + inf2 = dest_field(v2) if callable(dest_field) else v2[dest_field] + if inf1 != inf2: + # details mismatch, make copy + allfiles[k] = otherfile + else: + # details match, don't copy + allfiles.pop(k) + else: + # file not in target yet + allfiles[k] = otherfile + logger.debug(f"{len(allfiles)} files to copy") + if allfiles: + source_files, target_files = zip(*allfiles.items()) + fs.cp(source_files, target_files, **kwargs) + logger.debug(f"{len(to_delete)} files to delete") + if delete_missing and to_delete: + fs.rm(to_delete) + return allfiles + + +class GenericFileSystem(AsyncFileSystem): + """Wrapper over all other FS types + + + + This implementation is a single unified interface to be able to run FS operations + over generic URLs, and dispatch to the specific implementations using the URL + protocol prefix. + + Note: instances of this FS are always async, even if you never use it with any async + backend. + """ + + protocol = "generic" # there is no real reason to ever use a protocol with this FS + + def __init__(self, default_method="default", storage_options=None, **kwargs): + """ + + Parameters + ---------- + default_method: str (optional) + Defines how to configure backend FS instances. Options are: + - "default": instantiate like FSClass(), with no + extra arguments; this is the default instance of that FS, and can be + configured via the config system + - "generic": takes instances from the `_generic_fs` dict in this module, + which you must populate before use. Keys are by protocol + - "options": expects storage_options, a dict mapping protocol to + kwargs to use when constructing the filesystem + - "current": takes the most recently instantiated version of each FS + """ + self.method = default_method + self.st_opts = storage_options + super().__init__(**kwargs) + + def _parent(self, path): + fs = _resolve_fs(path, self.method, storage_options=self.st_opts) + return fs.unstrip_protocol(fs._parent(path)) + + def _strip_protocol(self, path): + # normalization only + fs = _resolve_fs(path, self.method, storage_options=self.st_opts) + return fs.unstrip_protocol(fs._strip_protocol(path)) + + async def _find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs): + fs = _resolve_fs(path, self.method, storage_options=self.st_opts) + if fs.async_impl: + out = await fs._find( + path, maxdepth=maxdepth, withdirs=withdirs, detail=True, **kwargs + ) + else: + out = fs.find( + path, maxdepth=maxdepth, withdirs=withdirs, detail=True, **kwargs + ) + result = {} + for k, v in out.items(): + v = v.copy() # don't corrupt target FS dircache + name = fs.unstrip_protocol(k) + v["name"] = name + result[name] = v + if detail: + return result + return list(result) + + async def _info(self, url, **kwargs): + fs = _resolve_fs(url, self.method) + if fs.async_impl: + out = await fs._info(url, **kwargs) + else: + out = fs.info(url, **kwargs) + out = out.copy() # don't edit originals + out["name"] = fs.unstrip_protocol(out["name"]) + return out + + async def _ls( + self, + url, + detail=True, + **kwargs, + ): + fs = _resolve_fs(url, self.method) + if fs.async_impl: + out = await fs._ls(url, detail=True, **kwargs) + else: + out = fs.ls(url, detail=True, **kwargs) + out = [o.copy() for o in out] # don't edit originals + for o in out: + o["name"] = fs.unstrip_protocol(o["name"]) + if detail: + return out + else: + return [o["name"] for o in out] + + async def _cat_file( + self, + url, + **kwargs, + ): + fs = _resolve_fs(url, self.method) + if fs.async_impl: + return await fs._cat_file(url, **kwargs) + else: + return fs.cat_file(url, **kwargs) + + async def _pipe_file( + self, + path, + value, + **kwargs, + ): + fs = _resolve_fs(path, self.method, storage_options=self.st_opts) + if fs.async_impl: + return await fs._pipe_file(path, value, **kwargs) + else: + return fs.pipe_file(path, value, **kwargs) + + async def _rm(self, url, **kwargs): + urls = url + if isinstance(urls, str): + urls = [urls] + fs = _resolve_fs(urls[0], self.method) + if fs.async_impl: + await fs._rm(urls, **kwargs) + else: + fs.rm(url, **kwargs) + + async def _makedirs(self, path, exist_ok=False): + logger.debug("Make dir %s", path) + fs = _resolve_fs(path, self.method, storage_options=self.st_opts) + if fs.async_impl: + await fs._makedirs(path, exist_ok=exist_ok) + else: + fs.makedirs(path, exist_ok=exist_ok) + + def rsync(self, source, destination, **kwargs): + """Sync files between two directory trees + + See `func:rsync` for more details. + """ + rsync(source, destination, fs=self, **kwargs) + + async def _cp_file( + self, + url, + url2, + blocksize=2**20, + callback=DEFAULT_CALLBACK, + tempdir: str | None = None, + **kwargs, + ): + fs = _resolve_fs(url, self.method) + fs2 = _resolve_fs(url2, self.method) + if fs is fs2: + # pure remote + if fs.async_impl: + return await fs._copy(url, url2, **kwargs) + else: + return fs.copy(url, url2, **kwargs) + await copy_file_op(fs, [url], fs2, [url2], tempdir, 1, on_error="raise") + + async def _make_many_dirs(self, urls, exist_ok=True): + fs = _resolve_fs(urls[0], self.method) + if fs.async_impl: + coros = [fs._makedirs(u, exist_ok=exist_ok) for u in urls] + await _run_coros_in_chunks(coros) + else: + for u in urls: + fs.makedirs(u, exist_ok=exist_ok) + + make_many_dirs = sync_wrapper(_make_many_dirs) + + async def _copy( + self, + path1: list[str], + path2: list[str], + recursive: bool = False, + on_error: str = "ignore", + maxdepth: int | None = None, + batch_size: int | None = None, + tempdir: str | None = None, + **kwargs, + ): + # TODO: special case for one FS being local, which can use get/put + # TODO: special case for one being memFS, which can use cat/pipe + if recursive: + raise NotImplementedError("Please use fsspec.generic.rsync") + path1 = [path1] if isinstance(path1, str) else path1 + path2 = [path2] if isinstance(path2, str) else path2 + + fs = _resolve_fs(path1, self.method) + fs2 = _resolve_fs(path2, self.method) + + if fs is fs2: + if fs.async_impl: + return await fs._copy(path1, path2, **kwargs) + else: + return fs.copy(path1, path2, **kwargs) + + await copy_file_op( + fs, path1, fs2, path2, tempdir, batch_size, on_error=on_error + ) + + +async def copy_file_op( + fs1, url1, fs2, url2, tempdir=None, batch_size=20, on_error="ignore" +): + import tempfile + + tempdir = tempdir or tempfile.mkdtemp() + try: + coros = [ + _copy_file_op( + fs1, + u1, + fs2, + u2, + os.path.join(tempdir, uuid.uuid4().hex), + ) + for u1, u2 in zip(url1, url2) + ] + out = await _run_coros_in_chunks( + coros, batch_size=batch_size, return_exceptions=True + ) + finally: + shutil.rmtree(tempdir) + if on_error == "return": + return out + elif on_error == "raise": + for o in out: + if isinstance(o, Exception): + raise o + + +async def _copy_file_op(fs1, url1, fs2, url2, local, on_error="ignore"): + if fs1.async_impl: + await fs1._get_file(url1, local) + else: + fs1.get_file(url1, local) + if fs2.async_impl: + await fs2._put_file(local, url2) + else: + fs2.put_file(local, url2) + os.unlink(local) + logger.debug("Copy %s -> %s; done", url1, url2) + + +async def maybe_await(cor): + if inspect.iscoroutine(cor): + return await cor + else: + return cor diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/gui.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/gui.py new file mode 100644 index 0000000000000000000000000000000000000000..9d914c8beb6cabb2c2700eb8eee31028559be2bd --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/gui.py @@ -0,0 +1,417 @@ +import ast +import contextlib +import logging +import os +import re +from collections.abc import Sequence +from typing import ClassVar + +import panel as pn + +from .core import OpenFile, get_filesystem_class, split_protocol +from .registry import known_implementations + +pn.extension() +logger = logging.getLogger("fsspec.gui") + + +class SigSlot: + """Signal-slot mixin, for Panel event passing + + Include this class in a widget manager's superclasses to be able to + register events and callbacks on Panel widgets managed by that class. + + The method ``_register`` should be called as widgets are added, and external + code should call ``connect`` to associate callbacks. + + By default, all signals emit a DEBUG logging statement. + """ + + # names of signals that this class may emit each of which must be + # set by _register for any new instance + signals: ClassVar[Sequence[str]] = [] + # names of actions that this class may respond to + slots: ClassVar[Sequence[str]] = [] + + # each of which must be a method name + + def __init__(self): + self._ignoring_events = False + self._sigs = {} + self._map = {} + self._setup() + + def _setup(self): + """Create GUI elements and register signals""" + self.panel = pn.pane.PaneBase() + # no signals to set up in the base class + + def _register( + self, widget, name, thing="value", log_level=logging.DEBUG, auto=False + ): + """Watch the given attribute of a widget and assign it a named event + + This is normally called at the time a widget is instantiated, in the + class which owns it. + + Parameters + ---------- + widget : pn.layout.Panel or None + Widget to watch. If None, an anonymous signal not associated with + any widget. + name : str + Name of this event + thing : str + Attribute of the given widget to watch + log_level : int + When the signal is triggered, a logging event of the given level + will be fired in the dfviz logger. + auto : bool + If True, automatically connects with a method in this class of the + same name. + """ + if name not in self.signals: + raise ValueError(f"Attempt to assign an undeclared signal: {name}") + self._sigs[name] = { + "widget": widget, + "callbacks": [], + "thing": thing, + "log": log_level, + } + wn = "-".join( + [ + getattr(widget, "name", str(widget)) if widget is not None else "none", + thing, + ] + ) + self._map[wn] = name + if widget is not None: + widget.param.watch(self._signal, thing, onlychanged=True) + if auto and hasattr(self, name): + self.connect(name, getattr(self, name)) + + def _repr_mimebundle_(self, *args, **kwargs): + """Display in a notebook or a server""" + try: + return self.panel._repr_mimebundle_(*args, **kwargs) + except (ValueError, AttributeError) as exc: + raise NotImplementedError( + "Panel does not seem to be set up properly" + ) from exc + + def connect(self, signal, slot): + """Associate call back with given event + + The callback must be a function which takes the "new" value of the + watched attribute as the only parameter. If the callback return False, + this cancels any further processing of the given event. + + Alternatively, the callback can be a string, in which case it means + emitting the correspondingly-named event (i.e., connect to self) + """ + self._sigs[signal]["callbacks"].append(slot) + + def _signal(self, event): + """This is called by a an action on a widget + + Within an self.ignore_events context, nothing happens. + + Tests can execute this method by directly changing the values of + widget components. + """ + if not self._ignoring_events: + wn = "-".join([event.obj.name, event.name]) + if wn in self._map and self._map[wn] in self._sigs: + self._emit(self._map[wn], event.new) + + @contextlib.contextmanager + def ignore_events(self): + """Temporarily turn off events processing in this instance + + (does not propagate to children) + """ + self._ignoring_events = True + try: + yield + finally: + self._ignoring_events = False + + def _emit(self, sig, value=None): + """An event happened, call its callbacks + + This method can be used in tests to simulate message passing without + directly changing visual elements. + + Calling of callbacks will halt whenever one returns False. + """ + logger.log(self._sigs[sig]["log"], f"{sig}: {value}") + for callback in self._sigs[sig]["callbacks"]: + if isinstance(callback, str): + self._emit(callback) + else: + try: + # running callbacks should not break the interface + ret = callback(value) + if ret is False: + break + except Exception as e: + logger.exception( + "Exception (%s) while executing callback for signal: %s", + e, + sig, + ) + + def show(self, threads=False): + """Open a new browser tab and display this instance's interface""" + self.panel.show(threads=threads, verbose=False) + return self + + +class SingleSelect(SigSlot): + """A multiselect which only allows you to select one item for an event""" + + signals = ["_selected", "selected"] # the first is internal + slots = ["set_options", "set_selection", "add", "clear", "select"] + + def __init__(self, **kwargs): + self.kwargs = kwargs + super().__init__() + + def _setup(self): + self.panel = pn.widgets.MultiSelect(**self.kwargs) + self._register(self.panel, "_selected", "value") + self._register(None, "selected") + self.connect("_selected", self.select_one) + + def _signal(self, *args, **kwargs): + super()._signal(*args, **kwargs) + + def select_one(self, *_): + with self.ignore_events(): + val = [self.panel.value[-1]] if self.panel.value else [] + self.panel.value = val + self._emit("selected", self.panel.value) + + def set_options(self, options): + self.panel.options = options + + def clear(self): + self.panel.options = [] + + @property + def value(self): + return self.panel.value + + def set_selection(self, selection): + self.panel.value = [selection] + + +class FileSelector(SigSlot): + """Panel-based graphical file selector widget + + Instances of this widget are interactive and can be displayed in jupyter by having + them as the output of a cell, or in a separate browser tab using ``.show()``. + """ + + signals = [ + "protocol_changed", + "selection_changed", + "directory_entered", + "home_clicked", + "up_clicked", + "go_clicked", + "filters_changed", + ] + slots = ["set_filters", "go_home"] + + def __init__(self, url=None, filters=None, ignore=None, kwargs=None): + """ + + Parameters + ---------- + url : str (optional) + Initial value of the URL to populate the dialog; should include protocol + filters : list(str) (optional) + File endings to include in the listings. If not included, all files are + allowed. Does not affect directories. + If given, the endings will appear as checkboxes in the interface + ignore : list(str) (optional) + Regex(s) of file basename patterns to ignore, e.g., "\\." for typical + hidden files on posix + kwargs : dict (optional) + To pass to file system instance + """ + if url: + self.init_protocol, url = split_protocol(url) + else: + self.init_protocol, url = "file", os.getcwd() + self.init_url = url + self.init_kwargs = (kwargs if isinstance(kwargs, str) else str(kwargs)) or "{}" + self.filters = filters + self.ignore = [re.compile(i) for i in ignore or []] + self._fs = None + super().__init__() + + def _setup(self): + self.url = pn.widgets.TextInput( + name="url", + value=self.init_url, + align="end", + sizing_mode="stretch_width", + width_policy="max", + ) + self.protocol = pn.widgets.Select( + options=sorted(known_implementations), + value=self.init_protocol, + name="protocol", + align="center", + ) + self.kwargs = pn.widgets.TextInput( + name="kwargs", value=self.init_kwargs, align="center" + ) + self.go = pn.widgets.Button(name="⇨", align="end", width=45) + self.main = SingleSelect(size=10) + self.home = pn.widgets.Button(name="🏠", width=40, height=30, align="end") + self.up = pn.widgets.Button(name="‹", width=30, height=30, align="end") + + self._register(self.protocol, "protocol_changed", auto=True) + self._register(self.go, "go_clicked", "clicks", auto=True) + self._register(self.up, "up_clicked", "clicks", auto=True) + self._register(self.home, "home_clicked", "clicks", auto=True) + self._register(None, "selection_changed") + self.main.connect("selected", self.selection_changed) + self._register(None, "directory_entered") + self.prev_protocol = self.protocol.value + self.prev_kwargs = self.storage_options + + self.filter_sel = pn.widgets.CheckBoxGroup( + value=[], options=[], inline=False, align="end", width_policy="min" + ) + self._register(self.filter_sel, "filters_changed", auto=True) + + self.panel = pn.Column( + pn.Row(self.protocol, self.kwargs), + pn.Row(self.home, self.up, self.url, self.go, self.filter_sel), + self.main.panel, + ) + self.set_filters(self.filters) + self.go_clicked() + + def set_filters(self, filters=None): + self.filters = filters + if filters: + self.filter_sel.options = filters + self.filter_sel.value = filters + else: + self.filter_sel.options = [] + self.filter_sel.value = [] + + @property + def storage_options(self): + """Value of the kwargs box as a dictionary""" + return ast.literal_eval(self.kwargs.value) or {} + + @property + def fs(self): + """Current filesystem instance""" + if self._fs is None: + cls = get_filesystem_class(self.protocol.value) + self._fs = cls(**self.storage_options) + return self._fs + + @property + def urlpath(self): + """URL of currently selected item""" + return ( + (f"{self.protocol.value}://{self.main.value[0]}") + if self.main.value + else None + ) + + def open_file(self, mode="rb", compression=None, encoding=None): + """Create OpenFile instance for the currently selected item + + For example, in a notebook you might do something like + + .. code-block:: + + [ ]: sel = FileSelector(); sel + + # user selects their file + + [ ]: with sel.open_file('rb') as f: + ... out = f.read() + + Parameters + ---------- + mode: str (optional) + Open mode for the file. + compression: str (optional) + The interact with the file as compressed. Set to 'infer' to guess + compression from the file ending + encoding: str (optional) + If using text mode, use this encoding; defaults to UTF8. + """ + if self.urlpath is None: + raise ValueError("No file selected") + return OpenFile(self.fs, self.urlpath, mode, compression, encoding) + + def filters_changed(self, values): + self.filters = values + self.go_clicked() + + def selection_changed(self, *_): + if self.urlpath is None: + return + if self.fs.isdir(self.urlpath): + self.url.value = self.fs._strip_protocol(self.urlpath) + self.go_clicked() + + def go_clicked(self, *_): + if ( + self.prev_protocol != self.protocol.value + or self.prev_kwargs != self.storage_options + ): + self._fs = None # causes fs to be recreated + self.prev_protocol = self.protocol.value + self.prev_kwargs = self.storage_options + listing = sorted( + self.fs.ls(self.url.value, detail=True), key=lambda x: x["name"] + ) + listing = [ + l + for l in listing + if not any(i.match(l["name"].rsplit("/", 1)[-1]) for i in self.ignore) + ] + folders = { + "📁 " + o["name"].rsplit("/", 1)[-1]: o["name"] + for o in listing + if o["type"] == "directory" + } + files = { + "📄 " + o["name"].rsplit("/", 1)[-1]: o["name"] + for o in listing + if o["type"] == "file" + } + if self.filters: + files = { + k: v + for k, v in files.items() + if any(v.endswith(ext) for ext in self.filters) + } + self.main.set_options(dict(**folders, **files)) + + def protocol_changed(self, *_): + self._fs = None + self.main.options = [] + self.url.value = "" + + def home_clicked(self, *_): + self.protocol.value = self.init_protocol + self.kwargs.value = self.init_kwargs + self.url.value = self.init_url + self.go_clicked() + + def up_clicked(self, *_): + self.url.value = self.fs._parent(self.url.value) + self.go_clicked() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/arrow.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/arrow.py new file mode 100644 index 0000000000000000000000000000000000000000..530df901a7225bab4afb9f08d06540bc18e91aef --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/arrow.py @@ -0,0 +1,304 @@ +import errno +import io +import os +import secrets +import shutil +from contextlib import suppress +from functools import cached_property, wraps +from urllib.parse import parse_qs + +from fsspec.spec import AbstractFileSystem +from fsspec.utils import ( + get_package_version_without_import, + infer_storage_options, + mirror_from, + tokenize, +) + + +def wrap_exceptions(func): + @wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except OSError as exception: + if not exception.args: + raise + + message, *args = exception.args + if isinstance(message, str) and "does not exist" in message: + raise FileNotFoundError(errno.ENOENT, message) from exception + else: + raise + + return wrapper + + +PYARROW_VERSION = None + + +class ArrowFSWrapper(AbstractFileSystem): + """FSSpec-compatible wrapper of pyarrow.fs.FileSystem. + + Parameters + ---------- + fs : pyarrow.fs.FileSystem + + """ + + root_marker = "/" + + def __init__(self, fs, **kwargs): + global PYARROW_VERSION + PYARROW_VERSION = get_package_version_without_import("pyarrow") + self.fs = fs + super().__init__(**kwargs) + + @property + def protocol(self): + return self.fs.type_name + + @cached_property + def fsid(self): + return "hdfs_" + tokenize(self.fs.host, self.fs.port) + + @classmethod + def _strip_protocol(cls, path): + ops = infer_storage_options(path) + path = ops["path"] + if path.startswith("//"): + # special case for "hdfs://path" (without the triple slash) + path = path[1:] + return path + + def ls(self, path, detail=False, **kwargs): + path = self._strip_protocol(path) + from pyarrow.fs import FileSelector + + entries = [ + self._make_entry(entry) + for entry in self.fs.get_file_info(FileSelector(path)) + ] + if detail: + return entries + else: + return [entry["name"] for entry in entries] + + def info(self, path, **kwargs): + path = self._strip_protocol(path) + [info] = self.fs.get_file_info([path]) + return self._make_entry(info) + + def exists(self, path): + path = self._strip_protocol(path) + try: + self.info(path) + except FileNotFoundError: + return False + else: + return True + + def _make_entry(self, info): + from pyarrow.fs import FileType + + if info.type is FileType.Directory: + kind = "directory" + elif info.type is FileType.File: + kind = "file" + elif info.type is FileType.NotFound: + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), info.path) + else: + kind = "other" + + return { + "name": info.path, + "size": info.size, + "type": kind, + "mtime": info.mtime, + } + + @wrap_exceptions + def cp_file(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1).rstrip("/") + path2 = self._strip_protocol(path2).rstrip("/") + + with self._open(path1, "rb") as lstream: + tmp_fname = f"{path2}.tmp.{secrets.token_hex(6)}" + try: + with self.open(tmp_fname, "wb") as rstream: + shutil.copyfileobj(lstream, rstream) + self.fs.move(tmp_fname, path2) + except BaseException: + with suppress(FileNotFoundError): + self.fs.delete_file(tmp_fname) + raise + + @wrap_exceptions + def mv(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1).rstrip("/") + path2 = self._strip_protocol(path2).rstrip("/") + self.fs.move(path1, path2) + + @wrap_exceptions + def rm_file(self, path): + path = self._strip_protocol(path) + self.fs.delete_file(path) + + @wrap_exceptions + def rm(self, path, recursive=False, maxdepth=None): + path = self._strip_protocol(path).rstrip("/") + if self.isdir(path): + if recursive: + self.fs.delete_dir(path) + else: + raise ValueError("Can't delete directories without recursive=False") + else: + self.fs.delete_file(path) + + @wrap_exceptions + def _open(self, path, mode="rb", block_size=None, seekable=True, **kwargs): + if mode == "rb": + if seekable: + method = self.fs.open_input_file + else: + method = self.fs.open_input_stream + elif mode == "wb": + method = self.fs.open_output_stream + elif mode == "ab": + method = self.fs.open_append_stream + else: + raise ValueError(f"unsupported mode for Arrow filesystem: {mode!r}") + + _kwargs = {} + if mode != "rb" or not seekable: + if int(PYARROW_VERSION.split(".")[0]) >= 4: + # disable compression auto-detection + _kwargs["compression"] = None + stream = method(path, **_kwargs) + + return ArrowFile(self, stream, path, mode, block_size, **kwargs) + + @wrap_exceptions + def mkdir(self, path, create_parents=True, **kwargs): + path = self._strip_protocol(path) + if create_parents: + self.makedirs(path, exist_ok=True) + else: + self.fs.create_dir(path, recursive=False) + + @wrap_exceptions + def makedirs(self, path, exist_ok=False): + path = self._strip_protocol(path) + self.fs.create_dir(path, recursive=True) + + @wrap_exceptions + def rmdir(self, path): + path = self._strip_protocol(path) + self.fs.delete_dir(path) + + @wrap_exceptions + def modified(self, path): + path = self._strip_protocol(path) + return self.fs.get_file_info(path).mtime + + def cat_file(self, path, start=None, end=None, **kwargs): + kwargs["seekable"] = start not in [None, 0] + return super().cat_file(path, start=None, end=None, **kwargs) + + def get_file(self, rpath, lpath, **kwargs): + kwargs["seekable"] = False + super().get_file(rpath, lpath, **kwargs) + + +@mirror_from( + "stream", + [ + "read", + "seek", + "tell", + "write", + "readable", + "writable", + "close", + "size", + "seekable", + ], +) +class ArrowFile(io.IOBase): + def __init__(self, fs, stream, path, mode, block_size=None, **kwargs): + self.path = path + self.mode = mode + + self.fs = fs + self.stream = stream + + self.blocksize = self.block_size = block_size + self.kwargs = kwargs + + def __enter__(self): + return self + + def __exit__(self, *args): + return self.close() + + +class HadoopFileSystem(ArrowFSWrapper): + """A wrapper on top of the pyarrow.fs.HadoopFileSystem + to connect it's interface with fsspec""" + + protocol = "hdfs" + + def __init__( + self, + host="default", + port=0, + user=None, + kerb_ticket=None, + replication=3, + extra_conf=None, + **kwargs, + ): + """ + + Parameters + ---------- + host: str + Hostname, IP or "default" to try to read from Hadoop config + port: int + Port to connect on, or default from Hadoop config if 0 + user: str or None + If given, connect as this username + kerb_ticket: str or None + If given, use this ticket for authentication + replication: int + set replication factor of file for write operations. default value is 3. + extra_conf: None or dict + Passed on to HadoopFileSystem + """ + from pyarrow.fs import HadoopFileSystem + + fs = HadoopFileSystem( + host=host, + port=port, + user=user, + kerb_ticket=kerb_ticket, + replication=replication, + extra_conf=extra_conf, + ) + super().__init__(fs=fs, **kwargs) + + @staticmethod + def _get_kwargs_from_urls(path): + ops = infer_storage_options(path) + out = {} + if ops.get("host", None): + out["host"] = ops["host"] + if ops.get("username", None): + out["user"] = ops["username"] + if ops.get("port", None): + out["port"] = ops["port"] + if ops.get("url_query", None): + queries = parse_qs(ops["url_query"]) + if queries.get("replication", None): + out["replication"] = int(queries["replication"][0]) + return out diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/asyn_wrapper.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/asyn_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..36db9c1b42e1a057c5346f0bedac3f9ff015c401 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/asyn_wrapper.py @@ -0,0 +1,122 @@ +import asyncio +import functools +import inspect + +import fsspec +from fsspec.asyn import AsyncFileSystem, running_async + + +def async_wrapper(func, obj=None, semaphore=None): + """ + Wraps a synchronous function to make it awaitable. + + Parameters + ---------- + func : callable + The synchronous function to wrap. + obj : object, optional + The instance to bind the function to, if applicable. + semaphore : asyncio.Semaphore, optional + A semaphore to limit concurrent calls. + + Returns + ------- + coroutine + An awaitable version of the function. + """ + + @functools.wraps(func) + async def wrapper(*args, **kwargs): + if semaphore: + async with semaphore: + return await asyncio.to_thread(func, *args, **kwargs) + return await asyncio.to_thread(func, *args, **kwargs) + + return wrapper + + +class AsyncFileSystemWrapper(AsyncFileSystem): + """ + A wrapper class to convert a synchronous filesystem into an asynchronous one. + + This class takes an existing synchronous filesystem implementation and wraps all + its methods to provide an asynchronous interface. + + Parameters + ---------- + sync_fs : AbstractFileSystem + The synchronous filesystem instance to wrap. + """ + + protocol = "asyncwrapper", "async_wrapper" + cachable = False + + def __init__( + self, + fs=None, + asynchronous=None, + target_protocol=None, + target_options=None, + semaphore=None, + max_concurrent_tasks=None, + **kwargs, + ): + if asynchronous is None: + asynchronous = running_async() + super().__init__(asynchronous=asynchronous, **kwargs) + if fs is not None: + self.sync_fs = fs + else: + self.sync_fs = fsspec.filesystem(target_protocol, **target_options) + self.protocol = self.sync_fs.protocol + self.semaphore = semaphore + self._wrap_all_sync_methods() + + @property + def fsid(self): + return f"async_{self.sync_fs.fsid}" + + def _wrap_all_sync_methods(self): + """ + Wrap all synchronous methods of the underlying filesystem with asynchronous versions. + """ + excluded_methods = {"open"} + for method_name in dir(self.sync_fs): + if method_name.startswith("_") or method_name in excluded_methods: + continue + + attr = inspect.getattr_static(self.sync_fs, method_name) + if isinstance(attr, property): + continue + + method = getattr(self.sync_fs, method_name) + if callable(method) and not inspect.iscoroutinefunction(method): + async_method = async_wrapper(method, obj=self, semaphore=self.semaphore) + setattr(self, f"_{method_name}", async_method) + + @classmethod + def wrap_class(cls, sync_fs_class): + """ + Create a new class that can be used to instantiate an AsyncFileSystemWrapper + with lazy instantiation of the underlying synchronous filesystem. + + Parameters + ---------- + sync_fs_class : type + The class of the synchronous filesystem to wrap. + + Returns + ------- + type + A new class that wraps the provided synchronous filesystem class. + """ + + class GeneratedAsyncFileSystemWrapper(cls): + def __init__(self, *args, **kwargs): + sync_fs = sync_fs_class(*args, **kwargs) + super().__init__(sync_fs) + + GeneratedAsyncFileSystemWrapper.__name__ = ( + f"Async{sync_fs_class.__name__}Wrapper" + ) + return GeneratedAsyncFileSystemWrapper diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/cache_mapper.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/cache_mapper.py new file mode 100644 index 0000000000000000000000000000000000000000..6e7c7d88afdddf12f77b26bb635bd8bf1e2bd7f1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/cache_mapper.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +import abc +import hashlib + +from fsspec.implementations.local import make_path_posix + + +class AbstractCacheMapper(abc.ABC): + """Abstract super-class for mappers from remote URLs to local cached + basenames. + """ + + @abc.abstractmethod + def __call__(self, path: str) -> str: ... + + def __eq__(self, other: object) -> bool: + # Identity only depends on class. When derived classes have attributes + # they will need to be included. + return isinstance(other, type(self)) + + def __hash__(self) -> int: + # Identity only depends on class. When derived classes have attributes + # they will need to be included. + return hash(type(self)) + + +class BasenameCacheMapper(AbstractCacheMapper): + """Cache mapper that uses the basename of the remote URL and a fixed number + of directory levels above this. + + The default is zero directory levels, meaning different paths with the same + basename will have the same cached basename. + """ + + def __init__(self, directory_levels: int = 0): + if directory_levels < 0: + raise ValueError( + "BasenameCacheMapper requires zero or positive directory_levels" + ) + self.directory_levels = directory_levels + + # Separator for directories when encoded as strings. + self._separator = "_@_" + + def __call__(self, path: str) -> str: + path = make_path_posix(path) + prefix, *bits = path.rsplit("/", self.directory_levels + 1) + if bits: + return self._separator.join(bits) + else: + return prefix # No separator found, simple filename + + def __eq__(self, other: object) -> bool: + return super().__eq__(other) and self.directory_levels == other.directory_levels + + def __hash__(self) -> int: + return super().__hash__() ^ hash(self.directory_levels) + + +class HashCacheMapper(AbstractCacheMapper): + """Cache mapper that uses a hash of the remote URL.""" + + def __call__(self, path: str) -> str: + return hashlib.sha256(path.encode()).hexdigest() + + +def create_cache_mapper(same_names: bool) -> AbstractCacheMapper: + """Factory method to create cache mapper for backward compatibility with + ``CachingFileSystem`` constructor using ``same_names`` kwarg. + """ + if same_names: + return BasenameCacheMapper() + else: + return HashCacheMapper() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/cache_metadata.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/cache_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..4a519158d4aca975dcbcc5978aeb57dab0e53cb0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/cache_metadata.py @@ -0,0 +1,233 @@ +from __future__ import annotations + +import os +import pickle +import time +from typing import TYPE_CHECKING + +from fsspec.utils import atomic_write + +try: + import ujson as json +except ImportError: + if not TYPE_CHECKING: + import json + +if TYPE_CHECKING: + from collections.abc import Iterator + from typing import Any, Literal + + from typing_extensions import TypeAlias + + from .cached import CachingFileSystem + + Detail: TypeAlias = dict[str, Any] + + +class CacheMetadata: + """Cache metadata. + + All reading and writing of cache metadata is performed by this class, + accessing the cached files and blocks is not. + + Metadata is stored in a single file per storage directory in JSON format. + For backward compatibility, also reads metadata stored in pickle format + which is converted to JSON when next saved. + """ + + def __init__(self, storage: list[str]): + """ + + Parameters + ---------- + storage: list[str] + Directories containing cached files, must be at least one. Metadata + is stored in the last of these directories by convention. + """ + if not storage: + raise ValueError("CacheMetadata expects at least one storage location") + + self._storage = storage + self.cached_files: list[Detail] = [{}] + + # Private attribute to force saving of metadata in pickle format rather than + # JSON for use in tests to confirm can read both pickle and JSON formats. + self._force_save_pickle = False + + def _load(self, fn: str) -> Detail: + """Low-level function to load metadata from specific file""" + try: + with open(fn, "r") as f: + loaded = json.load(f) + except ValueError: + with open(fn, "rb") as f: + loaded = pickle.load(f) + for c in loaded.values(): + if isinstance(c.get("blocks"), list): + c["blocks"] = set(c["blocks"]) + return loaded + + def _save(self, metadata_to_save: Detail, fn: str) -> None: + """Low-level function to save metadata to specific file""" + if self._force_save_pickle: + with atomic_write(fn) as f: + pickle.dump(metadata_to_save, f) + else: + with atomic_write(fn, mode="w") as f: + json.dump(metadata_to_save, f) + + def _scan_locations( + self, writable_only: bool = False + ) -> Iterator[tuple[str, str, bool]]: + """Yield locations (filenames) where metadata is stored, and whether + writable or not. + + Parameters + ---------- + writable: bool + Set to True to only yield writable locations. + + Returns + ------- + Yields (str, str, bool) + """ + n = len(self._storage) + for i, storage in enumerate(self._storage): + writable = i == n - 1 + if writable_only and not writable: + continue + yield os.path.join(storage, "cache"), storage, writable + + def check_file( + self, path: str, cfs: CachingFileSystem | None + ) -> Literal[False] | tuple[Detail, str]: + """If path is in cache return its details, otherwise return ``False``. + + If the optional CachingFileSystem is specified then it is used to + perform extra checks to reject possible matches, such as if they are + too old. + """ + for (fn, base, _), cache in zip(self._scan_locations(), self.cached_files): + if path not in cache: + continue + detail = cache[path].copy() + + if cfs is not None: + if cfs.check_files and detail["uid"] != cfs.fs.ukey(path): + # Wrong file as determined by hash of file properties + continue + if cfs.expiry and time.time() - detail["time"] > cfs.expiry: + # Cached file has expired + continue + + fn = os.path.join(base, detail["fn"]) + if os.path.exists(fn): + return detail, fn + return False + + def clear_expired(self, expiry_time: int) -> tuple[list[str], bool]: + """Remove expired metadata from the cache. + + Returns names of files corresponding to expired metadata and a boolean + flag indicating whether the writable cache is empty. Caller is + responsible for deleting the expired files. + """ + expired_files = [] + for path, detail in self.cached_files[-1].copy().items(): + if time.time() - detail["time"] > expiry_time: + fn = detail.get("fn", "") + if not fn: + raise RuntimeError( + f"Cache metadata does not contain 'fn' for {path}" + ) + fn = os.path.join(self._storage[-1], fn) + expired_files.append(fn) + self.cached_files[-1].pop(path) + + if self.cached_files[-1]: + cache_path = os.path.join(self._storage[-1], "cache") + self._save(self.cached_files[-1], cache_path) + + writable_cache_empty = not self.cached_files[-1] + return expired_files, writable_cache_empty + + def load(self) -> None: + """Load all metadata from disk and store in ``self.cached_files``""" + cached_files = [] + for fn, _, _ in self._scan_locations(): + if os.path.exists(fn): + # TODO: consolidate blocks here + cached_files.append(self._load(fn)) + else: + cached_files.append({}) + self.cached_files = cached_files or [{}] + + def on_close_cached_file(self, f: Any, path: str) -> None: + """Perform side-effect actions on closing a cached file. + + The actual closing of the file is the responsibility of the caller. + """ + # File must be writeble, so in self.cached_files[-1] + c = self.cached_files[-1][path] + if c["blocks"] is not True and len(c["blocks"]) * f.blocksize >= f.size: + c["blocks"] = True + + def pop_file(self, path: str) -> str | None: + """Remove metadata of cached file. + + If path is in the cache, return the filename of the cached file, + otherwise return ``None``. Caller is responsible for deleting the + cached file. + """ + details = self.check_file(path, None) + if not details: + return None + _, fn = details + if fn.startswith(self._storage[-1]): + self.cached_files[-1].pop(path) + self.save() + else: + raise PermissionError( + "Can only delete cached file in last, writable cache location" + ) + return fn + + def save(self) -> None: + """Save metadata to disk""" + for (fn, _, writable), cache in zip(self._scan_locations(), self.cached_files): + if not writable: + continue + + if os.path.exists(fn): + cached_files = self._load(fn) + for k, c in cached_files.items(): + if k in cache: + if c["blocks"] is True or cache[k]["blocks"] is True: + c["blocks"] = True + else: + # self.cached_files[*][*]["blocks"] must continue to + # point to the same set object so that updates + # performed by MMapCache are propagated back to + # self.cached_files. + blocks = cache[k]["blocks"] + blocks.update(c["blocks"]) + c["blocks"] = blocks + c["time"] = max(c["time"], cache[k]["time"]) + c["uid"] = cache[k]["uid"] + + # Files can be added to cache after it was written once + for k, c in cache.items(): + if k not in cached_files: + cached_files[k] = c + else: + cached_files = cache + cache = {k: v.copy() for k, v in cached_files.items()} + for c in cache.values(): + if isinstance(c["blocks"], set): + c["blocks"] = list(c["blocks"]) + self._save(cache, fn) + self.cached_files[-1] = cached_files + + def update_file(self, path: str, detail: Detail) -> None: + """Update metadata for specific file in memory, do not save""" + self.cached_files[-1][path] = detail diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/cached.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/cached.py new file mode 100644 index 0000000000000000000000000000000000000000..4847c2ef262b688b25508b2861f394426ba2dd73 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/cached.py @@ -0,0 +1,998 @@ +from __future__ import annotations + +import inspect +import logging +import os +import tempfile +import time +import weakref +from shutil import rmtree +from typing import TYPE_CHECKING, Any, Callable, ClassVar + +from fsspec import AbstractFileSystem, filesystem +from fsspec.callbacks import DEFAULT_CALLBACK +from fsspec.compression import compr +from fsspec.core import BaseCache, MMapCache +from fsspec.exceptions import BlocksizeMismatchError +from fsspec.implementations.cache_mapper import create_cache_mapper +from fsspec.implementations.cache_metadata import CacheMetadata +from fsspec.implementations.local import LocalFileSystem +from fsspec.spec import AbstractBufferedFile +from fsspec.transaction import Transaction +from fsspec.utils import infer_compression + +if TYPE_CHECKING: + from fsspec.implementations.cache_mapper import AbstractCacheMapper + +logger = logging.getLogger("fsspec.cached") + + +class WriteCachedTransaction(Transaction): + def complete(self, commit=True): + rpaths = [f.path for f in self.files] + lpaths = [f.fn for f in self.files] + if commit: + self.fs.put(lpaths, rpaths) + self.files.clear() + self.fs._intrans = False + self.fs._transaction = None + self.fs = None # break cycle + + +class CachingFileSystem(AbstractFileSystem): + """Locally caching filesystem, layer over any other FS + + This class implements chunk-wise local storage of remote files, for quick + access after the initial download. The files are stored in a given + directory with hashes of URLs for the filenames. If no directory is given, + a temporary one is used, which should be cleaned up by the OS after the + process ends. The files themselves are sparse (as implemented in + :class:`~fsspec.caching.MMapCache`), so only the data which is accessed + takes up space. + + Restrictions: + + - the block-size must be the same for each access of a given file, unless + all blocks of the file have already been read + - caching can only be applied to file-systems which produce files + derived from fsspec.spec.AbstractBufferedFile ; LocalFileSystem is also + allowed, for testing + """ + + protocol: ClassVar[str | tuple[str, ...]] = ("blockcache", "cached") + + def __init__( + self, + target_protocol=None, + cache_storage="TMP", + cache_check=10, + check_files=False, + expiry_time=604800, + target_options=None, + fs=None, + same_names: bool | None = None, + compression=None, + cache_mapper: AbstractCacheMapper | None = None, + **kwargs, + ): + """ + + Parameters + ---------- + target_protocol: str (optional) + Target filesystem protocol. Provide either this or ``fs``. + cache_storage: str or list(str) + Location to store files. If "TMP", this is a temporary directory, + and will be cleaned up by the OS when this process ends (or later). + If a list, each location will be tried in the order given, but + only the last will be considered writable. + cache_check: int + Number of seconds between reload of cache metadata + check_files: bool + Whether to explicitly see if the UID of the remote file matches + the stored one before using. Warning: some file systems such as + HTTP cannot reliably give a unique hash of the contents of some + path, so be sure to set this option to False. + expiry_time: int + The time in seconds after which a local copy is considered useless. + Set to falsy to prevent expiry. The default is equivalent to one + week. + target_options: dict or None + Passed to the instantiation of the FS, if fs is None. + fs: filesystem instance + The target filesystem to run against. Provide this or ``protocol``. + same_names: bool (optional) + By default, target URLs are hashed using a ``HashCacheMapper`` so + that files from different backends with the same basename do not + conflict. If this argument is ``true``, a ``BasenameCacheMapper`` + is used instead. Other cache mapper options are available by using + the ``cache_mapper`` keyword argument. Only one of this and + ``cache_mapper`` should be specified. + compression: str (optional) + To decompress on download. Can be 'infer' (guess from the URL name), + one of the entries in ``fsspec.compression.compr``, or None for no + decompression. + cache_mapper: AbstractCacheMapper (optional) + The object use to map from original filenames to cached filenames. + Only one of this and ``same_names`` should be specified. + """ + super().__init__(**kwargs) + if fs is None and target_protocol is None: + raise ValueError( + "Please provide filesystem instance(fs) or target_protocol" + ) + if not (fs is None) ^ (target_protocol is None): + raise ValueError( + "Both filesystems (fs) and target_protocol may not be both given." + ) + if cache_storage == "TMP": + tempdir = tempfile.mkdtemp() + storage = [tempdir] + weakref.finalize(self, self._remove_tempdir, tempdir) + else: + if isinstance(cache_storage, str): + storage = [cache_storage] + else: + storage = cache_storage + os.makedirs(storage[-1], exist_ok=True) + self.storage = storage + self.kwargs = target_options or {} + self.cache_check = cache_check + self.check_files = check_files + self.expiry = expiry_time + self.compression = compression + + # Size of cache in bytes. If None then the size is unknown and will be + # recalculated the next time cache_size() is called. On writes to the + # cache this is reset to None. + self._cache_size = None + + if same_names is not None and cache_mapper is not None: + raise ValueError( + "Cannot specify both same_names and cache_mapper in " + "CachingFileSystem.__init__" + ) + if cache_mapper is not None: + self._mapper = cache_mapper + else: + self._mapper = create_cache_mapper( + same_names if same_names is not None else False + ) + + self.target_protocol = ( + target_protocol + if isinstance(target_protocol, str) + else (fs.protocol if isinstance(fs.protocol, str) else fs.protocol[0]) + ) + self._metadata = CacheMetadata(self.storage) + self.load_cache() + self.fs = fs if fs is not None else filesystem(target_protocol, **self.kwargs) + + def _strip_protocol(path): + # acts as a method, since each instance has a difference target + return self.fs._strip_protocol(type(self)._strip_protocol(path)) + + self._strip_protocol: Callable = _strip_protocol + + @staticmethod + def _remove_tempdir(tempdir): + try: + rmtree(tempdir) + except Exception: + pass + + def _mkcache(self): + os.makedirs(self.storage[-1], exist_ok=True) + + def cache_size(self): + """Return size of cache in bytes. + + If more than one cache directory is in use, only the size of the last + one (the writable cache directory) is returned. + """ + if self._cache_size is None: + cache_dir = self.storage[-1] + self._cache_size = filesystem("file").du(cache_dir, withdirs=True) + return self._cache_size + + def load_cache(self): + """Read set of stored blocks from file""" + self._metadata.load() + self._mkcache() + self.last_cache = time.time() + + def save_cache(self): + """Save set of stored blocks from file""" + self._mkcache() + self._metadata.save() + self.last_cache = time.time() + self._cache_size = None + + def _check_cache(self): + """Reload caches if time elapsed or any disappeared""" + self._mkcache() + if not self.cache_check: + # explicitly told not to bother checking + return + timecond = time.time() - self.last_cache > self.cache_check + existcond = all(os.path.exists(storage) for storage in self.storage) + if timecond or not existcond: + self.load_cache() + + def _check_file(self, path): + """Is path in cache and still valid""" + path = self._strip_protocol(path) + self._check_cache() + return self._metadata.check_file(path, self) + + def clear_cache(self): + """Remove all files and metadata from the cache + + In the case of multiple cache locations, this clears only the last one, + which is assumed to be the read/write one. + """ + rmtree(self.storage[-1]) + self.load_cache() + self._cache_size = None + + def clear_expired_cache(self, expiry_time=None): + """Remove all expired files and metadata from the cache + + In the case of multiple cache locations, this clears only the last one, + which is assumed to be the read/write one. + + Parameters + ---------- + expiry_time: int + The time in seconds after which a local copy is considered useless. + If not defined the default is equivalent to the attribute from the + file caching instantiation. + """ + + if not expiry_time: + expiry_time = self.expiry + + self._check_cache() + + expired_files, writable_cache_empty = self._metadata.clear_expired(expiry_time) + for fn in expired_files: + if os.path.exists(fn): + os.remove(fn) + + if writable_cache_empty: + rmtree(self.storage[-1]) + self.load_cache() + + self._cache_size = None + + def pop_from_cache(self, path): + """Remove cached version of given file + + Deletes local copy of the given (remote) path. If it is found in a cache + location which is not the last, it is assumed to be read-only, and + raises PermissionError + """ + path = self._strip_protocol(path) + fn = self._metadata.pop_file(path) + if fn is not None: + os.remove(fn) + self._cache_size = None + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + """Wrap the target _open + + If the whole file exists in the cache, just open it locally and + return that. + + Otherwise, open the file on the target FS, and make it have a mmap + cache pointing to the location which we determine, in our cache. + The ``blocks`` instance is shared, so as the mmap cache instance + updates, so does the entry in our ``cached_files`` attribute. + We monkey-patch this file, so that when it closes, we call + ``close_and_update`` to save the state of the blocks. + """ + path = self._strip_protocol(path) + + path = self.fs._strip_protocol(path) + if "r" not in mode: + return self.fs._open( + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_options=cache_options, + **kwargs, + ) + detail = self._check_file(path) + if detail: + # file is in cache + detail, fn = detail + hash, blocks = detail["fn"], detail["blocks"] + if blocks is True: + # stored file is complete + logger.debug("Opening local copy of %s", path) + return open(fn, mode) + # TODO: action where partial file exists in read-only cache + logger.debug("Opening partially cached copy of %s", path) + else: + hash = self._mapper(path) + fn = os.path.join(self.storage[-1], hash) + blocks = set() + detail = { + "original": path, + "fn": hash, + "blocks": blocks, + "time": time.time(), + "uid": self.fs.ukey(path), + } + self._metadata.update_file(path, detail) + logger.debug("Creating local sparse file for %s", path) + + # explicitly submitting the size to the open call will avoid extra + # operations when opening. This is particularly relevant + # for any file that is read over a network, e.g. S3. + size = detail.get("size") + + # call target filesystems open + self._mkcache() + f = self.fs._open( + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_options=cache_options, + cache_type="none", + size=size, + **kwargs, + ) + + # set size if not already set + if size is None: + detail["size"] = f.size + self._metadata.update_file(path, detail) + + if self.compression: + comp = ( + infer_compression(path) + if self.compression == "infer" + else self.compression + ) + f = compr[comp](f, mode="rb") + if "blocksize" in detail: + if detail["blocksize"] != f.blocksize: + raise BlocksizeMismatchError( + f"Cached file must be reopened with same block" + f" size as original (old: {detail['blocksize']}," + f" new {f.blocksize})" + ) + else: + detail["blocksize"] = f.blocksize + + def _fetch_ranges(ranges): + return self.fs.cat_ranges( + [path] * len(ranges), + [r[0] for r in ranges], + [r[1] for r in ranges], + **kwargs, + ) + + multi_fetcher = None if self.compression else _fetch_ranges + f.cache = MMapCache( + f.blocksize, f._fetch_range, f.size, fn, blocks, multi_fetcher=multi_fetcher + ) + close = f.close + f.close = lambda: self.close_and_update(f, close) + self.save_cache() + return f + + def _parent(self, path): + return self.fs._parent(path) + + def hash_name(self, path: str, *args: Any) -> str: + # Kept for backward compatibility with downstream libraries. + # Ignores extra arguments, previously same_name boolean. + return self._mapper(path) + + def close_and_update(self, f, close): + """Called when a file is closing, so store the set of blocks""" + if f.closed: + return + path = self._strip_protocol(f.path) + self._metadata.on_close_cached_file(f, path) + try: + logger.debug("going to save") + self.save_cache() + logger.debug("saved") + except OSError: + logger.debug("Cache saving failed while closing file") + except NameError: + logger.debug("Cache save failed due to interpreter shutdown") + close() + f.closed = True + + def ls(self, path, detail=True): + return self.fs.ls(path, detail) + + def __getattribute__(self, item): + if item in { + "load_cache", + "_open", + "save_cache", + "close_and_update", + "__init__", + "__getattribute__", + "__reduce__", + "_make_local_details", + "open", + "cat", + "cat_file", + "_cat_file", + "cat_ranges", + "_cat_ranges", + "get", + "read_block", + "tail", + "head", + "info", + "ls", + "exists", + "isfile", + "isdir", + "_check_file", + "_check_cache", + "_mkcache", + "clear_cache", + "clear_expired_cache", + "pop_from_cache", + "local_file", + "_paths_from_path", + "get_mapper", + "open_many", + "commit_many", + "hash_name", + "__hash__", + "__eq__", + "to_json", + "to_dict", + "cache_size", + "pipe_file", + "pipe", + "start_transaction", + "end_transaction", + }: + # all the methods defined in this class. Note `open` here, since + # it calls `_open`, but is actually in superclass + return lambda *args, **kw: getattr(type(self), item).__get__(self)( + *args, **kw + ) + if item in ["__reduce_ex__"]: + raise AttributeError + if item in ["transaction"]: + # property + return type(self).transaction.__get__(self) + if item in {"_cache", "transaction_type", "protocol"}: + # class attributes + return getattr(type(self), item) + if item == "__class__": + return type(self) + d = object.__getattribute__(self, "__dict__") + fs = d.get("fs", None) # fs is not immediately defined + if item in d: + return d[item] + elif fs is not None: + if item in fs.__dict__: + # attribute of instance + return fs.__dict__[item] + # attributed belonging to the target filesystem + cls = type(fs) + m = getattr(cls, item) + if (inspect.isfunction(m) or inspect.isdatadescriptor(m)) and ( + not hasattr(m, "__self__") or m.__self__ is None + ): + # instance method + return m.__get__(fs, cls) + return m # class method or attribute + else: + # attributes of the superclass, while target is being set up + return super().__getattribute__(item) + + def __eq__(self, other): + """Test for equality.""" + if self is other: + return True + if not isinstance(other, type(self)): + return False + return ( + self.storage == other.storage + and self.kwargs == other.kwargs + and self.cache_check == other.cache_check + and self.check_files == other.check_files + and self.expiry == other.expiry + and self.compression == other.compression + and self._mapper == other._mapper + and self.target_protocol == other.target_protocol + ) + + def __hash__(self): + """Calculate hash.""" + return ( + hash(tuple(self.storage)) + ^ hash(str(self.kwargs)) + ^ hash(self.cache_check) + ^ hash(self.check_files) + ^ hash(self.expiry) + ^ hash(self.compression) + ^ hash(self._mapper) + ^ hash(self.target_protocol) + ) + + +class WholeFileCacheFileSystem(CachingFileSystem): + """Caches whole remote files on first access + + This class is intended as a layer over any other file system, and + will make a local copy of each file accessed, so that all subsequent + reads are local. This is similar to ``CachingFileSystem``, but without + the block-wise functionality and so can work even when sparse files + are not allowed. See its docstring for definition of the init + arguments. + + The class still needs access to the remote store for listing files, + and may refresh cached files. + """ + + protocol = "filecache" + local_file = True + + def open_many(self, open_files, **kwargs): + paths = [of.path for of in open_files] + if "r" in open_files.mode: + self._mkcache() + else: + return [ + LocalTempFile( + self.fs, + path, + mode=open_files.mode, + fn=os.path.join(self.storage[-1], self._mapper(path)), + **kwargs, + ) + for path in paths + ] + + if self.compression: + raise NotImplementedError + details = [self._check_file(sp) for sp in paths] + downpath = [p for p, d in zip(paths, details) if not d] + downfn0 = [ + os.path.join(self.storage[-1], self._mapper(p)) + for p, d in zip(paths, details) + ] # keep these path names for opening later + downfn = [fn for fn, d in zip(downfn0, details) if not d] + if downpath: + # skip if all files are already cached and up to date + self.fs.get(downpath, downfn) + + # update metadata - only happens when downloads are successful + newdetail = [ + { + "original": path, + "fn": self._mapper(path), + "blocks": True, + "time": time.time(), + "uid": self.fs.ukey(path), + } + for path in downpath + ] + for path, detail in zip(downpath, newdetail): + self._metadata.update_file(path, detail) + self.save_cache() + + def firstpart(fn): + # helper to adapt both whole-file and simple-cache + return fn[1] if isinstance(fn, tuple) else fn + + return [ + open(firstpart(fn0) if fn0 else fn1, mode=open_files.mode) + for fn0, fn1 in zip(details, downfn0) + ] + + def commit_many(self, open_files): + self.fs.put([f.fn for f in open_files], [f.path for f in open_files]) + [f.close() for f in open_files] + for f in open_files: + # in case autocommit is off, and so close did not already delete + try: + os.remove(f.name) + except FileNotFoundError: + pass + self._cache_size = None + + def _make_local_details(self, path): + hash = self._mapper(path) + fn = os.path.join(self.storage[-1], hash) + detail = { + "original": path, + "fn": hash, + "blocks": True, + "time": time.time(), + "uid": self.fs.ukey(path), + } + self._metadata.update_file(path, detail) + logger.debug("Copying %s to local cache", path) + return fn + + def cat( + self, + path, + recursive=False, + on_error="raise", + callback=DEFAULT_CALLBACK, + **kwargs, + ): + paths = self.expand_path( + path, recursive=recursive, maxdepth=kwargs.get("maxdepth") + ) + getpaths = [] + storepaths = [] + fns = [] + out = {} + for p in paths.copy(): + try: + detail = self._check_file(p) + if not detail: + fn = self._make_local_details(p) + getpaths.append(p) + storepaths.append(fn) + else: + detail, fn = detail if isinstance(detail, tuple) else (None, detail) + fns.append(fn) + except Exception as e: + if on_error == "raise": + raise + if on_error == "return": + out[p] = e + paths.remove(p) + + if getpaths: + self.fs.get(getpaths, storepaths) + self.save_cache() + + callback.set_size(len(paths)) + for p, fn in zip(paths, fns): + with open(fn, "rb") as f: + out[p] = f.read() + callback.relative_update(1) + if isinstance(path, str) and len(paths) == 1 and recursive is False: + out = out[paths[0]] + return out + + def _open(self, path, mode="rb", **kwargs): + path = self._strip_protocol(path) + if "r" not in mode: + hash = self._mapper(path) + fn = os.path.join(self.storage[-1], hash) + user_specified_kwargs = { + k: v + for k, v in kwargs.items() + # those kwargs were added by open(), we don't want them + if k not in ["autocommit", "block_size", "cache_options"] + } + return LocalTempFile(self, path, mode=mode, fn=fn, **user_specified_kwargs) + detail = self._check_file(path) + if detail: + detail, fn = detail + _, blocks = detail["fn"], detail["blocks"] + if blocks is True: + logger.debug("Opening local copy of %s", path) + + # In order to support downstream filesystems to be able to + # infer the compression from the original filename, like + # the `TarFileSystem`, let's extend the `io.BufferedReader` + # fileobject protocol by adding a dedicated attribute + # `original`. + f = open(fn, mode) + f.original = detail.get("original") + return f + else: + raise ValueError( + f"Attempt to open partially cached file {path}" + f" as a wholly cached file" + ) + else: + fn = self._make_local_details(path) + kwargs["mode"] = mode + + # call target filesystems open + self._mkcache() + if self.compression: + with self.fs._open(path, **kwargs) as f, open(fn, "wb") as f2: + if isinstance(f, AbstractBufferedFile): + # want no type of caching if just downloading whole thing + f.cache = BaseCache(0, f.cache.fetcher, f.size) + comp = ( + infer_compression(path) + if self.compression == "infer" + else self.compression + ) + f = compr[comp](f, mode="rb") + data = True + while data: + block = getattr(f, "blocksize", 5 * 2**20) + data = f.read(block) + f2.write(data) + else: + self.fs.get_file(path, fn) + self.save_cache() + return self._open(path, mode) + + +class SimpleCacheFileSystem(WholeFileCacheFileSystem): + """Caches whole remote files on first access + + This class is intended as a layer over any other file system, and + will make a local copy of each file accessed, so that all subsequent + reads are local. This implementation only copies whole files, and + does not keep any metadata about the download time or file details. + It is therefore safer to use in multi-threaded/concurrent situations. + + This is the only of the caching filesystems that supports write: you will + be given a real local open file, and upon close and commit, it will be + uploaded to the target filesystem; the writability or the target URL is + not checked until that time. + + """ + + protocol = "simplecache" + local_file = True + transaction_type = WriteCachedTransaction + + def __init__(self, **kwargs): + kw = kwargs.copy() + for key in ["cache_check", "expiry_time", "check_files"]: + kw[key] = False + super().__init__(**kw) + for storage in self.storage: + if not os.path.exists(storage): + os.makedirs(storage, exist_ok=True) + + def _check_file(self, path): + self._check_cache() + sha = self._mapper(path) + for storage in self.storage: + fn = os.path.join(storage, sha) + if os.path.exists(fn): + return fn + + def save_cache(self): + pass + + def load_cache(self): + pass + + def pipe_file(self, path, value=None, **kwargs): + if self._intrans: + with self.open(path, "wb") as f: + f.write(value) + else: + super().pipe_file(path, value) + + def ls(self, path, detail=True, **kwargs): + path = self._strip_protocol(path) + details = [] + try: + details = self.fs.ls( + path, detail=True, **kwargs + ).copy() # don't edit original! + except FileNotFoundError as e: + ex = e + else: + ex = None + if self._intrans: + path1 = path.rstrip("/") + "/" + for f in self.transaction.files: + if f.path == path: + details.append( + {"name": path, "size": f.size or f.tell(), "type": "file"} + ) + elif f.path.startswith(path1): + if f.path.count("/") == path1.count("/"): + details.append( + {"name": f.path, "size": f.size or f.tell(), "type": "file"} + ) + else: + dname = "/".join(f.path.split("/")[: path1.count("/") + 1]) + details.append({"name": dname, "size": 0, "type": "directory"}) + if ex is not None and not details: + raise ex + if detail: + return details + return sorted(_["name"] for _ in details) + + def info(self, path, **kwargs): + path = self._strip_protocol(path) + if self._intrans: + f = [_ for _ in self.transaction.files if _.path == path] + if f: + size = os.path.getsize(f[0].fn) if f[0].closed else f[0].tell() + return {"name": path, "size": size, "type": "file"} + f = any(_.path.startswith(path + "/") for _ in self.transaction.files) + if f: + return {"name": path, "size": 0, "type": "directory"} + return self.fs.info(path, **kwargs) + + def pipe(self, path, value=None, **kwargs): + if isinstance(path, str): + self.pipe_file(self._strip_protocol(path), value, **kwargs) + elif isinstance(path, dict): + for k, v in path.items(): + self.pipe_file(self._strip_protocol(k), v, **kwargs) + else: + raise ValueError("path must be str or dict") + + async def _cat_file(self, path, start=None, end=None, **kwargs): + logger.debug("async cat_file %s", path) + path = self._strip_protocol(path) + sha = self._mapper(path) + fn = self._check_file(path) + + if not fn: + fn = os.path.join(self.storage[-1], sha) + await self.fs._get_file(path, fn, **kwargs) + + with open(fn, "rb") as f: # noqa ASYNC230 + if start: + f.seek(start) + size = -1 if end is None else end - f.tell() + return f.read(size) + + async def _cat_ranges( + self, paths, starts, ends, max_gap=None, on_error="return", **kwargs + ): + logger.debug("async cat ranges %s", paths) + lpaths = [] + rset = set() + download = [] + rpaths = [] + for p in paths: + fn = self._check_file(p) + if fn is None and p not in rset: + sha = self._mapper(p) + fn = os.path.join(self.storage[-1], sha) + download.append(fn) + rset.add(p) + rpaths.append(p) + lpaths.append(fn) + if download: + await self.fs._get(rpaths, download, on_error=on_error) + + return LocalFileSystem().cat_ranges( + lpaths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs + ) + + def cat_ranges( + self, paths, starts, ends, max_gap=None, on_error="return", **kwargs + ): + logger.debug("cat ranges %s", paths) + lpaths = [self._check_file(p) for p in paths] + rpaths = [p for l, p in zip(lpaths, paths) if l is False] + lpaths = [l for l, p in zip(lpaths, paths) if l is False] + self.fs.get(rpaths, lpaths) + paths = [self._check_file(p) for p in paths] + return LocalFileSystem().cat_ranges( + paths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs + ) + + def _open(self, path, mode="rb", **kwargs): + path = self._strip_protocol(path) + sha = self._mapper(path) + + if "r" not in mode: + fn = os.path.join(self.storage[-1], sha) + user_specified_kwargs = { + k: v + for k, v in kwargs.items() + if k not in ["autocommit", "block_size", "cache_options"] + } # those were added by open() + return LocalTempFile( + self, + path, + mode=mode, + autocommit=not self._intrans, + fn=fn, + **user_specified_kwargs, + ) + fn = self._check_file(path) + if fn: + return open(fn, mode) + + fn = os.path.join(self.storage[-1], sha) + logger.debug("Copying %s to local cache", path) + kwargs["mode"] = mode + + self._mkcache() + self._cache_size = None + if self.compression: + with self.fs._open(path, **kwargs) as f, open(fn, "wb") as f2: + if isinstance(f, AbstractBufferedFile): + # want no type of caching if just downloading whole thing + f.cache = BaseCache(0, f.cache.fetcher, f.size) + comp = ( + infer_compression(path) + if self.compression == "infer" + else self.compression + ) + f = compr[comp](f, mode="rb") + data = True + while data: + block = getattr(f, "blocksize", 5 * 2**20) + data = f.read(block) + f2.write(data) + else: + self.fs.get_file(path, fn) + return self._open(path, mode) + + +class LocalTempFile: + """A temporary local file, which will be uploaded on commit""" + + def __init__(self, fs, path, fn, mode="wb", autocommit=True, seek=0, **kwargs): + self.fn = fn + self.fh = open(fn, mode) + self.mode = mode + if seek: + self.fh.seek(seek) + self.path = path + self.size = None + self.fs = fs + self.closed = False + self.autocommit = autocommit + self.kwargs = kwargs + + def __reduce__(self): + # always open in r+b to allow continuing writing at a location + return ( + LocalTempFile, + (self.fs, self.path, self.fn, "r+b", self.autocommit, self.tell()), + ) + + def __enter__(self): + return self.fh + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def close(self): + # self.size = self.fh.tell() + if self.closed: + return + self.fh.close() + self.closed = True + if self.autocommit: + self.commit() + + def discard(self): + self.fh.close() + os.remove(self.fn) + + def commit(self): + self.fs.put(self.fn, self.path, **self.kwargs) + # we do not delete the local copy, it's still in the cache. + + @property + def name(self): + return self.fn + + def __repr__(self) -> str: + return f"LocalTempFile: {self.path}" + + def __getattr__(self, item): + return getattr(self.fh, item) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/dask.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/dask.py new file mode 100644 index 0000000000000000000000000000000000000000..3e1276463db6866665e6a0fe114efc247971b57e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/dask.py @@ -0,0 +1,152 @@ +import dask +from distributed.client import Client, _get_global_client +from distributed.worker import Worker + +from fsspec import filesystem +from fsspec.spec import AbstractBufferedFile, AbstractFileSystem +from fsspec.utils import infer_storage_options + + +def _get_client(client): + if client is None: + return _get_global_client() + elif isinstance(client, Client): + return client + else: + # e.g., connection string + return Client(client) + + +def _in_worker(): + return bool(Worker._instances) + + +class DaskWorkerFileSystem(AbstractFileSystem): + """View files accessible to a worker as any other remote file-system + + When instances are run on the worker, uses the real filesystem. When + run on the client, they call the worker to provide information or data. + + **Warning** this implementation is experimental, and read-only for now. + """ + + def __init__( + self, target_protocol=None, target_options=None, fs=None, client=None, **kwargs + ): + super().__init__(**kwargs) + if not (fs is None) ^ (target_protocol is None): + raise ValueError( + "Please provide one of filesystem instance (fs) or" + " target_protocol, not both" + ) + self.target_protocol = target_protocol + self.target_options = target_options + self.worker = None + self.client = client + self.fs = fs + self._determine_worker() + + @staticmethod + def _get_kwargs_from_urls(path): + so = infer_storage_options(path) + if "host" in so and "port" in so: + return {"client": f"{so['host']}:{so['port']}"} + else: + return {} + + def _determine_worker(self): + if _in_worker(): + self.worker = True + if self.fs is None: + self.fs = filesystem( + self.target_protocol, **(self.target_options or {}) + ) + else: + self.worker = False + self.client = _get_client(self.client) + self.rfs = dask.delayed(self) + + def mkdir(self, *args, **kwargs): + if self.worker: + self.fs.mkdir(*args, **kwargs) + else: + self.rfs.mkdir(*args, **kwargs).compute() + + def rm(self, *args, **kwargs): + if self.worker: + self.fs.rm(*args, **kwargs) + else: + self.rfs.rm(*args, **kwargs).compute() + + def copy(self, *args, **kwargs): + if self.worker: + self.fs.copy(*args, **kwargs) + else: + self.rfs.copy(*args, **kwargs).compute() + + def mv(self, *args, **kwargs): + if self.worker: + self.fs.mv(*args, **kwargs) + else: + self.rfs.mv(*args, **kwargs).compute() + + def ls(self, *args, **kwargs): + if self.worker: + return self.fs.ls(*args, **kwargs) + else: + return self.rfs.ls(*args, **kwargs).compute() + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + if self.worker: + return self.fs._open( + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_options=cache_options, + **kwargs, + ) + else: + return DaskFile( + fs=self, + path=path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_options=cache_options, + **kwargs, + ) + + def fetch_range(self, path, mode, start, end): + if self.worker: + with self._open(path, mode) as f: + f.seek(start) + return f.read(end - start) + else: + return self.rfs.fetch_range(path, mode, start, end).compute() + + +class DaskFile(AbstractBufferedFile): + def __init__(self, mode="rb", **kwargs): + if mode != "rb": + raise ValueError('Remote dask files can only be opened in "rb" mode') + super().__init__(**kwargs) + + def _upload_chunk(self, final=False): + pass + + def _initiate_upload(self): + """Create remote file/upload""" + pass + + def _fetch_range(self, start, end): + """Get the specified set of bytes from remote""" + return self.fs.fetch_range(self.path, self.mode, start, end) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/data.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/data.py new file mode 100644 index 0000000000000000000000000000000000000000..519032305bed633f2ba8a6148076433caf81710b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/data.py @@ -0,0 +1,58 @@ +import base64 +import io +from typing import Optional +from urllib.parse import unquote + +from fsspec import AbstractFileSystem + + +class DataFileSystem(AbstractFileSystem): + """A handy decoder for data-URLs + + Example + ------- + >>> with fsspec.open("data:,Hello%2C%20World%21") as f: + ... print(f.read()) + b"Hello, World!" + + See https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs + """ + + protocol = "data" + + def __init__(self, **kwargs): + """No parameters for this filesystem""" + super().__init__(**kwargs) + + def cat_file(self, path, start=None, end=None, **kwargs): + pref, data = path.split(",", 1) + if pref.endswith("base64"): + return base64.b64decode(data)[start:end] + return unquote(data).encode()[start:end] + + def info(self, path, **kwargs): + pref, name = path.split(",", 1) + data = self.cat_file(path) + mime = pref.split(":", 1)[1].split(";", 1)[0] + return {"name": name, "size": len(data), "type": "file", "mimetype": mime} + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + if "r" not in mode: + raise ValueError("Read only filesystem") + return io.BytesIO(self.cat_file(path)) + + @staticmethod + def encode(data: bytes, mime: Optional[str] = None): + """Format the given data into data-URL syntax + + This version always base64 encodes, even when the data is ascii/url-safe. + """ + return f"data:{mime or ''};base64,{base64.b64encode(data).decode()}" diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/dbfs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/dbfs.py new file mode 100644 index 0000000000000000000000000000000000000000..1a7fc93d7389c894ecb5fc6267ce20abe4087068 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/dbfs.py @@ -0,0 +1,496 @@ +from __future__ import annotations + +import base64 +import urllib + +import requests +from requests.adapters import HTTPAdapter, Retry +from typing_extensions import override + +from fsspec import AbstractFileSystem +from fsspec.spec import AbstractBufferedFile + + +class DatabricksException(Exception): + """ + Helper class for exceptions raised in this module. + """ + + def __init__(self, error_code, message, details=None): + """Create a new DatabricksException""" + super().__init__(message) + + self.error_code = error_code + self.message = message + self.details = details + + +class DatabricksFileSystem(AbstractFileSystem): + """ + Get access to the Databricks filesystem implementation over HTTP. + Can be used inside and outside of a databricks cluster. + """ + + def __init__(self, instance, token, **kwargs): + """ + Create a new DatabricksFileSystem. + + Parameters + ---------- + instance: str + The instance URL of the databricks cluster. + For example for an Azure databricks cluster, this + has the form adb-..azuredatabricks.net. + token: str + Your personal token. Find out more + here: https://docs.databricks.com/dev-tools/api/latest/authentication.html + """ + self.instance = instance + self.token = token + self.session = requests.Session() + self.retries = Retry( + total=10, + backoff_factor=0.05, + status_forcelist=[408, 429, 500, 502, 503, 504], + ) + + self.session.mount("https://", HTTPAdapter(max_retries=self.retries)) + self.session.headers.update({"Authorization": f"Bearer {self.token}"}) + + super().__init__(**kwargs) + + @override + def _ls_from_cache(self, path) -> list[dict[str, str | int]] | None: + """Check cache for listing + + Returns listing, if found (may be empty list for a directory that + exists but contains nothing), None if not in cache. + """ + self.dircache.pop(path.rstrip("/"), None) + + parent = self._parent(path) + if parent in self.dircache: + for entry in self.dircache[parent]: + if entry["name"] == path.rstrip("/"): + if entry["type"] != "directory": + return [entry] + return [] + raise FileNotFoundError(path) + + def ls(self, path, detail=True, **kwargs): + """ + List the contents of the given path. + + Parameters + ---------- + path: str + Absolute path + detail: bool + Return not only the list of filenames, + but also additional information on file sizes + and types. + """ + try: + out = self._ls_from_cache(path) + except FileNotFoundError: + # This happens if the `path`'s parent was cached, but `path` is not + # there. This suggests that `path` is new since the parent was + # cached. Attempt to invalidate parent's cache before continuing. + self.dircache.pop(self._parent(path), None) + out = None + + if not out: + try: + r = self._send_to_api( + method="get", endpoint="list", json={"path": path} + ) + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + raise FileNotFoundError(e.message) from e + + raise + files = r.get("files", []) + out = [ + { + "name": o["path"], + "type": "directory" if o["is_dir"] else "file", + "size": o["file_size"], + } + for o in files + ] + self.dircache[path] = out + + if detail: + return out + return [o["name"] for o in out] + + def makedirs(self, path, exist_ok=True): + """ + Create a given absolute path and all of its parents. + + Parameters + ---------- + path: str + Absolute path to create + exist_ok: bool + If false, checks if the folder + exists before creating it (and raises an + Exception if this is the case) + """ + if not exist_ok: + try: + # If the following succeeds, the path is already present + self._send_to_api( + method="get", endpoint="get-status", json={"path": path} + ) + raise FileExistsError(f"Path {path} already exists") + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + pass + + try: + self._send_to_api(method="post", endpoint="mkdirs", json={"path": path}) + except DatabricksException as e: + if e.error_code == "RESOURCE_ALREADY_EXISTS": + raise FileExistsError(e.message) from e + + raise + self.invalidate_cache(self._parent(path)) + + def mkdir(self, path, create_parents=True, **kwargs): + """ + Create a given absolute path and all of its parents. + + Parameters + ---------- + path: str + Absolute path to create + create_parents: bool + Whether to create all parents or not. + "False" is not implemented so far. + """ + if not create_parents: + raise NotImplementedError + + self.mkdirs(path, **kwargs) + + def rm(self, path, recursive=False, **kwargs): + """ + Remove the file or folder at the given absolute path. + + Parameters + ---------- + path: str + Absolute path what to remove + recursive: bool + Recursively delete all files in a folder. + """ + try: + self._send_to_api( + method="post", + endpoint="delete", + json={"path": path, "recursive": recursive}, + ) + except DatabricksException as e: + # This is not really an exception, it just means + # not everything was deleted so far + if e.error_code == "PARTIAL_DELETE": + self.rm(path=path, recursive=recursive) + elif e.error_code == "IO_ERROR": + # Using the same exception as the os module would use here + raise OSError(e.message) from e + + raise + self.invalidate_cache(self._parent(path)) + + def mv( + self, source_path, destination_path, recursive=False, maxdepth=None, **kwargs + ): + """ + Move a source to a destination path. + + A note from the original [databricks API manual] + (https://docs.databricks.com/dev-tools/api/latest/dbfs.html#move). + + When moving a large number of files the API call will time out after + approximately 60s, potentially resulting in partially moved data. + Therefore, for operations that move more than 10k files, we strongly + discourage using the DBFS REST API. + + Parameters + ---------- + source_path: str + From where to move (absolute path) + destination_path: str + To where to move (absolute path) + recursive: bool + Not implemented to far. + maxdepth: + Not implemented to far. + """ + if recursive: + raise NotImplementedError + if maxdepth: + raise NotImplementedError + + try: + self._send_to_api( + method="post", + endpoint="move", + json={"source_path": source_path, "destination_path": destination_path}, + ) + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + raise FileNotFoundError(e.message) from e + elif e.error_code == "RESOURCE_ALREADY_EXISTS": + raise FileExistsError(e.message) from e + + raise + self.invalidate_cache(self._parent(source_path)) + self.invalidate_cache(self._parent(destination_path)) + + def _open(self, path, mode="rb", block_size="default", **kwargs): + """ + Overwrite the base class method to make sure to create a DBFile. + All arguments are copied from the base method. + + Only the default blocksize is allowed. + """ + return DatabricksFile(self, path, mode=mode, block_size=block_size, **kwargs) + + def _send_to_api(self, method, endpoint, json): + """ + Send the given json to the DBFS API + using a get or post request (specified by the argument `method`). + + Parameters + ---------- + method: str + Which http method to use for communication; "get" or "post". + endpoint: str + Where to send the request to (last part of the API URL) + json: dict + Dictionary of information to send + """ + if method == "post": + session_call = self.session.post + elif method == "get": + session_call = self.session.get + else: + raise ValueError(f"Do not understand method {method}") + + url = urllib.parse.urljoin(f"https://{self.instance}/api/2.0/dbfs/", endpoint) + + r = session_call(url, json=json) + + # The DBFS API will return a json, also in case of an exception. + # We want to preserve this information as good as possible. + try: + r.raise_for_status() + except requests.HTTPError as e: + # try to extract json error message + # if that fails, fall back to the original exception + try: + exception_json = e.response.json() + except Exception: + raise e from None + + raise DatabricksException(**exception_json) from e + + return r.json() + + def _create_handle(self, path, overwrite=True): + """ + Internal function to create a handle, which can be used to + write blocks of a file to DBFS. + A handle has a unique identifier which needs to be passed + whenever written during this transaction. + The handle is active for 10 minutes - after that a new + write transaction needs to be created. + Make sure to close the handle after you are finished. + + Parameters + ---------- + path: str + Absolute path for this file. + overwrite: bool + If a file already exist at this location, either overwrite + it or raise an exception. + """ + try: + r = self._send_to_api( + method="post", + endpoint="create", + json={"path": path, "overwrite": overwrite}, + ) + return r["handle"] + except DatabricksException as e: + if e.error_code == "RESOURCE_ALREADY_EXISTS": + raise FileExistsError(e.message) from e + + raise + + def _close_handle(self, handle): + """ + Close a handle, which was opened by :func:`_create_handle`. + + Parameters + ---------- + handle: str + Which handle to close. + """ + try: + self._send_to_api(method="post", endpoint="close", json={"handle": handle}) + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + raise FileNotFoundError(e.message) from e + + raise + + def _add_data(self, handle, data): + """ + Upload data to an already opened file handle + (opened by :func:`_create_handle`). + The maximal allowed data size is 1MB after + conversion to base64. + Remember to close the handle when you are finished. + + Parameters + ---------- + handle: str + Which handle to upload data to. + data: bytes + Block of data to add to the handle. + """ + data = base64.b64encode(data).decode() + try: + self._send_to_api( + method="post", + endpoint="add-block", + json={"handle": handle, "data": data}, + ) + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + raise FileNotFoundError(e.message) from e + elif e.error_code == "MAX_BLOCK_SIZE_EXCEEDED": + raise ValueError(e.message) from e + + raise + + def _get_data(self, path, start, end): + """ + Download data in bytes from a given absolute path in a block + from [start, start+length]. + The maximum number of allowed bytes to read is 1MB. + + Parameters + ---------- + path: str + Absolute path to download data from + start: int + Start position of the block + end: int + End position of the block + """ + try: + r = self._send_to_api( + method="get", + endpoint="read", + json={"path": path, "offset": start, "length": end - start}, + ) + return base64.b64decode(r["data"]) + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + raise FileNotFoundError(e.message) from e + elif e.error_code in ["INVALID_PARAMETER_VALUE", "MAX_READ_SIZE_EXCEEDED"]: + raise ValueError(e.message) from e + + raise + + def invalidate_cache(self, path=None): + if path is None: + self.dircache.clear() + else: + self.dircache.pop(path, None) + super().invalidate_cache(path) + + +class DatabricksFile(AbstractBufferedFile): + """ + Helper class for files referenced in the DatabricksFileSystem. + """ + + DEFAULT_BLOCK_SIZE = 1 * 2**20 # only allowed block size + + def __init__( + self, + fs, + path, + mode="rb", + block_size="default", + autocommit=True, + cache_type="readahead", + cache_options=None, + **kwargs, + ): + """ + Create a new instance of the DatabricksFile. + + The blocksize needs to be the default one. + """ + if block_size is None or block_size == "default": + block_size = self.DEFAULT_BLOCK_SIZE + + assert block_size == self.DEFAULT_BLOCK_SIZE, ( + f"Only the default block size is allowed, not {block_size}" + ) + + super().__init__( + fs, + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_type=cache_type, + cache_options=cache_options or {}, + **kwargs, + ) + + def _initiate_upload(self): + """Internal function to start a file upload""" + self.handle = self.fs._create_handle(self.path) + + def _upload_chunk(self, final=False): + """Internal function to add a chunk of data to a started upload""" + self.buffer.seek(0) + data = self.buffer.getvalue() + + data_chunks = [ + data[start:end] for start, end in self._to_sized_blocks(len(data)) + ] + + for data_chunk in data_chunks: + self.fs._add_data(handle=self.handle, data=data_chunk) + + if final: + self.fs._close_handle(handle=self.handle) + return True + + def _fetch_range(self, start, end): + """Internal function to download a block of data""" + return_buffer = b"" + length = end - start + for chunk_start, chunk_end in self._to_sized_blocks(length, start): + return_buffer += self.fs._get_data( + path=self.path, start=chunk_start, end=chunk_end + ) + + return return_buffer + + def _to_sized_blocks(self, length, start=0): + """Helper function to split a range from 0 to total_length into blocksizes""" + end = start + length + for data_chunk in range(start, end, self.blocksize): + data_start = data_chunk + data_end = min(end, data_chunk + self.blocksize) + yield data_start, data_end diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/dirfs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/dirfs.py new file mode 100644 index 0000000000000000000000000000000000000000..c0623b82fc61ed4780fdbc1d69680f2b96f2b9f3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/dirfs.py @@ -0,0 +1,388 @@ +from .. import filesystem +from ..asyn import AsyncFileSystem + + +class DirFileSystem(AsyncFileSystem): + """Directory prefix filesystem + + The DirFileSystem is a filesystem-wrapper. It assumes every path it is dealing with + is relative to the `path`. After performing the necessary paths operation it + delegates everything to the wrapped filesystem. + """ + + protocol = "dir" + + def __init__( + self, + path=None, + fs=None, + fo=None, + target_protocol=None, + target_options=None, + **storage_options, + ): + """ + Parameters + ---------- + path: str + Path to the directory. + fs: AbstractFileSystem + An instantiated filesystem to wrap. + target_protocol, target_options: + if fs is none, construct it from these + fo: str + Alternate for path; do not provide both + """ + super().__init__(**storage_options) + if fs is None: + fs = filesystem(protocol=target_protocol, **(target_options or {})) + path = path or fo + + if self.asynchronous and not fs.async_impl: + raise ValueError("can't use asynchronous with non-async fs") + + if fs.async_impl and self.asynchronous != fs.asynchronous: + raise ValueError("both dirfs and fs should be in the same sync/async mode") + + self.path = fs._strip_protocol(path) + self.fs = fs + + def _join(self, path): + if isinstance(path, str): + if not self.path: + return path + if not path: + return self.path + return self.fs.sep.join((self.path, self._strip_protocol(path))) + if isinstance(path, dict): + return {self._join(_path): value for _path, value in path.items()} + return [self._join(_path) for _path in path] + + def _relpath(self, path): + if isinstance(path, str): + if not self.path: + return path + # We need to account for S3FileSystem returning paths that do not + # start with a '/' + if path == self.path or ( + self.path.startswith(self.fs.sep) and path == self.path[1:] + ): + return "" + prefix = self.path + self.fs.sep + if self.path.startswith(self.fs.sep) and not path.startswith(self.fs.sep): + prefix = prefix[1:] + assert path.startswith(prefix) + return path[len(prefix) :] + return [self._relpath(_path) for _path in path] + + # Wrappers below + + @property + def sep(self): + return self.fs.sep + + async def set_session(self, *args, **kwargs): + return await self.fs.set_session(*args, **kwargs) + + async def _rm_file(self, path, **kwargs): + return await self.fs._rm_file(self._join(path), **kwargs) + + def rm_file(self, path, **kwargs): + return self.fs.rm_file(self._join(path), **kwargs) + + async def _rm(self, path, *args, **kwargs): + return await self.fs._rm(self._join(path), *args, **kwargs) + + def rm(self, path, *args, **kwargs): + return self.fs.rm(self._join(path), *args, **kwargs) + + async def _cp_file(self, path1, path2, **kwargs): + return await self.fs._cp_file(self._join(path1), self._join(path2), **kwargs) + + def cp_file(self, path1, path2, **kwargs): + return self.fs.cp_file(self._join(path1), self._join(path2), **kwargs) + + async def _copy( + self, + path1, + path2, + *args, + **kwargs, + ): + return await self.fs._copy( + self._join(path1), + self._join(path2), + *args, + **kwargs, + ) + + def copy(self, path1, path2, *args, **kwargs): + return self.fs.copy( + self._join(path1), + self._join(path2), + *args, + **kwargs, + ) + + async def _pipe(self, path, *args, **kwargs): + return await self.fs._pipe(self._join(path), *args, **kwargs) + + def pipe(self, path, *args, **kwargs): + return self.fs.pipe(self._join(path), *args, **kwargs) + + async def _pipe_file(self, path, *args, **kwargs): + return await self.fs._pipe_file(self._join(path), *args, **kwargs) + + def pipe_file(self, path, *args, **kwargs): + return self.fs.pipe_file(self._join(path), *args, **kwargs) + + async def _cat_file(self, path, *args, **kwargs): + return await self.fs._cat_file(self._join(path), *args, **kwargs) + + def cat_file(self, path, *args, **kwargs): + return self.fs.cat_file(self._join(path), *args, **kwargs) + + async def _cat(self, path, *args, **kwargs): + ret = await self.fs._cat( + self._join(path), + *args, + **kwargs, + ) + + if isinstance(ret, dict): + return {self._relpath(key): value for key, value in ret.items()} + + return ret + + def cat(self, path, *args, **kwargs): + ret = self.fs.cat( + self._join(path), + *args, + **kwargs, + ) + + if isinstance(ret, dict): + return {self._relpath(key): value for key, value in ret.items()} + + return ret + + async def _put_file(self, lpath, rpath, **kwargs): + return await self.fs._put_file(lpath, self._join(rpath), **kwargs) + + def put_file(self, lpath, rpath, **kwargs): + return self.fs.put_file(lpath, self._join(rpath), **kwargs) + + async def _put( + self, + lpath, + rpath, + *args, + **kwargs, + ): + return await self.fs._put( + lpath, + self._join(rpath), + *args, + **kwargs, + ) + + def put(self, lpath, rpath, *args, **kwargs): + return self.fs.put( + lpath, + self._join(rpath), + *args, + **kwargs, + ) + + async def _get_file(self, rpath, lpath, **kwargs): + return await self.fs._get_file(self._join(rpath), lpath, **kwargs) + + def get_file(self, rpath, lpath, **kwargs): + return self.fs.get_file(self._join(rpath), lpath, **kwargs) + + async def _get(self, rpath, *args, **kwargs): + return await self.fs._get(self._join(rpath), *args, **kwargs) + + def get(self, rpath, *args, **kwargs): + return self.fs.get(self._join(rpath), *args, **kwargs) + + async def _isfile(self, path): + return await self.fs._isfile(self._join(path)) + + def isfile(self, path): + return self.fs.isfile(self._join(path)) + + async def _isdir(self, path): + return await self.fs._isdir(self._join(path)) + + def isdir(self, path): + return self.fs.isdir(self._join(path)) + + async def _size(self, path): + return await self.fs._size(self._join(path)) + + def size(self, path): + return self.fs.size(self._join(path)) + + async def _exists(self, path): + return await self.fs._exists(self._join(path)) + + def exists(self, path): + return self.fs.exists(self._join(path)) + + async def _info(self, path, **kwargs): + info = await self.fs._info(self._join(path), **kwargs) + info = info.copy() + info["name"] = self._relpath(info["name"]) + return info + + def info(self, path, **kwargs): + info = self.fs.info(self._join(path), **kwargs) + info = info.copy() + info["name"] = self._relpath(info["name"]) + return info + + async def _ls(self, path, detail=True, **kwargs): + ret = (await self.fs._ls(self._join(path), detail=detail, **kwargs)).copy() + if detail: + out = [] + for entry in ret: + entry = entry.copy() + entry["name"] = self._relpath(entry["name"]) + out.append(entry) + return out + + return self._relpath(ret) + + def ls(self, path, detail=True, **kwargs): + ret = self.fs.ls(self._join(path), detail=detail, **kwargs).copy() + if detail: + out = [] + for entry in ret: + entry = entry.copy() + entry["name"] = self._relpath(entry["name"]) + out.append(entry) + return out + + return self._relpath(ret) + + async def _walk(self, path, *args, **kwargs): + async for root, dirs, files in self.fs._walk(self._join(path), *args, **kwargs): + yield self._relpath(root), dirs, files + + def walk(self, path, *args, **kwargs): + for root, dirs, files in self.fs.walk(self._join(path), *args, **kwargs): + yield self._relpath(root), dirs, files + + async def _glob(self, path, **kwargs): + detail = kwargs.get("detail", False) + ret = await self.fs._glob(self._join(path), **kwargs) + if detail: + return {self._relpath(path): info for path, info in ret.items()} + return self._relpath(ret) + + def glob(self, path, **kwargs): + detail = kwargs.get("detail", False) + ret = self.fs.glob(self._join(path), **kwargs) + if detail: + return {self._relpath(path): info for path, info in ret.items()} + return self._relpath(ret) + + async def _du(self, path, *args, **kwargs): + total = kwargs.get("total", True) + ret = await self.fs._du(self._join(path), *args, **kwargs) + if total: + return ret + + return {self._relpath(path): size for path, size in ret.items()} + + def du(self, path, *args, **kwargs): + total = kwargs.get("total", True) + ret = self.fs.du(self._join(path), *args, **kwargs) + if total: + return ret + + return {self._relpath(path): size for path, size in ret.items()} + + async def _find(self, path, *args, **kwargs): + detail = kwargs.get("detail", False) + ret = await self.fs._find(self._join(path), *args, **kwargs) + if detail: + return {self._relpath(path): info for path, info in ret.items()} + return self._relpath(ret) + + def find(self, path, *args, **kwargs): + detail = kwargs.get("detail", False) + ret = self.fs.find(self._join(path), *args, **kwargs) + if detail: + return {self._relpath(path): info for path, info in ret.items()} + return self._relpath(ret) + + async def _expand_path(self, path, *args, **kwargs): + return self._relpath( + await self.fs._expand_path(self._join(path), *args, **kwargs) + ) + + def expand_path(self, path, *args, **kwargs): + return self._relpath(self.fs.expand_path(self._join(path), *args, **kwargs)) + + async def _mkdir(self, path, *args, **kwargs): + return await self.fs._mkdir(self._join(path), *args, **kwargs) + + def mkdir(self, path, *args, **kwargs): + return self.fs.mkdir(self._join(path), *args, **kwargs) + + async def _makedirs(self, path, *args, **kwargs): + return await self.fs._makedirs(self._join(path), *args, **kwargs) + + def makedirs(self, path, *args, **kwargs): + return self.fs.makedirs(self._join(path), *args, **kwargs) + + def rmdir(self, path): + return self.fs.rmdir(self._join(path)) + + def mv(self, path1, path2, **kwargs): + return self.fs.mv( + self._join(path1), + self._join(path2), + **kwargs, + ) + + def touch(self, path, **kwargs): + return self.fs.touch(self._join(path), **kwargs) + + def created(self, path): + return self.fs.created(self._join(path)) + + def modified(self, path): + return self.fs.modified(self._join(path)) + + def sign(self, path, *args, **kwargs): + return self.fs.sign(self._join(path), *args, **kwargs) + + def __repr__(self): + return f"{self.__class__.__qualname__}(path='{self.path}', fs={self.fs})" + + def open( + self, + path, + *args, + **kwargs, + ): + return self.fs.open( + self._join(path), + *args, + **kwargs, + ) + + async def open_async( + self, + path, + *args, + **kwargs, + ): + return await self.fs.open_async( + self._join(path), + *args, + **kwargs, + ) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/ftp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/ftp.py new file mode 100644 index 0000000000000000000000000000000000000000..a3db22b04a00ddf12582253ec19b2938c794c1da --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/ftp.py @@ -0,0 +1,387 @@ +import os +import uuid +from ftplib import FTP, FTP_TLS, Error, error_perm +from typing import Any + +from ..spec import AbstractBufferedFile, AbstractFileSystem +from ..utils import infer_storage_options, isfilelike + + +class FTPFileSystem(AbstractFileSystem): + """A filesystem over classic FTP""" + + root_marker = "/" + cachable = False + protocol = "ftp" + + def __init__( + self, + host, + port=21, + username=None, + password=None, + acct=None, + block_size=None, + tempdir=None, + timeout=30, + encoding="utf-8", + tls=False, + **kwargs, + ): + """ + You can use _get_kwargs_from_urls to get some kwargs from + a reasonable FTP url. + + Authentication will be anonymous if username/password are not + given. + + Parameters + ---------- + host: str + The remote server name/ip to connect to + port: int + Port to connect with + username: str or None + If authenticating, the user's identifier + password: str of None + User's password on the server, if using + acct: str or None + Some servers also need an "account" string for auth + block_size: int or None + If given, the read-ahead or write buffer size. + tempdir: str + Directory on remote to put temporary files when in a transaction + timeout: int + Timeout of the ftp connection in seconds + encoding: str + Encoding to use for directories and filenames in FTP connection + tls: bool + Use FTP-TLS, by default False + """ + super().__init__(**kwargs) + self.host = host + self.port = port + self.tempdir = tempdir or "/tmp" + self.cred = username or "", password or "", acct or "" + self.timeout = timeout + self.encoding = encoding + if block_size is not None: + self.blocksize = block_size + else: + self.blocksize = 2**16 + self.tls = tls + self._connect() + if self.tls: + self.ftp.prot_p() + + def _connect(self): + if self.tls: + ftp_cls = FTP_TLS + else: + ftp_cls = FTP + self.ftp = ftp_cls(timeout=self.timeout, encoding=self.encoding) + self.ftp.connect(self.host, self.port) + self.ftp.login(*self.cred) + + @classmethod + def _strip_protocol(cls, path): + return "/" + infer_storage_options(path)["path"].lstrip("/").rstrip("/") + + @staticmethod + def _get_kwargs_from_urls(urlpath): + out = infer_storage_options(urlpath) + out.pop("path", None) + out.pop("protocol", None) + return out + + def ls(self, path, detail=True, **kwargs): + path = self._strip_protocol(path) + out = [] + if path not in self.dircache: + try: + try: + out = [ + (fn, details) + for (fn, details) in self.ftp.mlsd(path) + if fn not in [".", ".."] + and details["type"] not in ["pdir", "cdir"] + ] + except error_perm: + out = _mlsd2(self.ftp, path) # Not platform independent + for fn, details in out: + details["name"] = "/".join( + ["" if path == "/" else path, fn.lstrip("/")] + ) + if details["type"] == "file": + details["size"] = int(details["size"]) + else: + details["size"] = 0 + if details["type"] == "dir": + details["type"] = "directory" + self.dircache[path] = out + except Error: + try: + info = self.info(path) + if info["type"] == "file": + out = [(path, info)] + except (Error, IndexError) as exc: + raise FileNotFoundError(path) from exc + files = self.dircache.get(path, out) + if not detail: + return sorted([fn for fn, details in files]) + return [details for fn, details in files] + + def info(self, path, **kwargs): + # implement with direct method + path = self._strip_protocol(path) + if path == "/": + # special case, since this dir has no real entry + return {"name": "/", "size": 0, "type": "directory"} + files = self.ls(self._parent(path).lstrip("/"), True) + try: + out = next(f for f in files if f["name"] == path) + except StopIteration as exc: + raise FileNotFoundError(path) from exc + return out + + def get_file(self, rpath, lpath, **kwargs): + if self.isdir(rpath): + if not os.path.exists(lpath): + os.mkdir(lpath) + return + if isfilelike(lpath): + outfile = lpath + else: + outfile = open(lpath, "wb") + + def cb(x): + outfile.write(x) + + self.ftp.retrbinary( + f"RETR {rpath}", + blocksize=self.blocksize, + callback=cb, + ) + if not isfilelike(lpath): + outfile.close() + + def cat_file(self, path, start=None, end=None, **kwargs): + if end is not None: + return super().cat_file(path, start, end, **kwargs) + out = [] + + def cb(x): + out.append(x) + + try: + self.ftp.retrbinary( + f"RETR {path}", + blocksize=self.blocksize, + rest=start, + callback=cb, + ) + except (Error, error_perm) as orig_exc: + raise FileNotFoundError(path) from orig_exc + return b"".join(out) + + def _open( + self, + path, + mode="rb", + block_size=None, + cache_options=None, + autocommit=True, + **kwargs, + ): + path = self._strip_protocol(path) + block_size = block_size or self.blocksize + return FTPFile( + self, + path, + mode=mode, + block_size=block_size, + tempdir=self.tempdir, + autocommit=autocommit, + cache_options=cache_options, + ) + + def _rm(self, path): + path = self._strip_protocol(path) + self.ftp.delete(path) + self.invalidate_cache(self._parent(path)) + + def rm(self, path, recursive=False, maxdepth=None): + paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth) + for p in reversed(paths): + if self.isfile(p): + self.rm_file(p) + else: + self.rmdir(p) + + def mkdir(self, path: str, create_parents: bool = True, **kwargs: Any) -> None: + path = self._strip_protocol(path) + parent = self._parent(path) + if parent != self.root_marker and not self.exists(parent) and create_parents: + self.mkdir(parent, create_parents=create_parents) + + self.ftp.mkd(path) + self.invalidate_cache(self._parent(path)) + + def makedirs(self, path: str, exist_ok: bool = False) -> None: + path = self._strip_protocol(path) + if self.exists(path): + # NB: "/" does not "exist" as it has no directory entry + if not exist_ok: + raise FileExistsError(f"{path} exists without `exist_ok`") + # exists_ok=True -> no-op + else: + self.mkdir(path, create_parents=True) + + def rmdir(self, path): + path = self._strip_protocol(path) + self.ftp.rmd(path) + self.invalidate_cache(self._parent(path)) + + def mv(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1) + path2 = self._strip_protocol(path2) + self.ftp.rename(path1, path2) + self.invalidate_cache(self._parent(path1)) + self.invalidate_cache(self._parent(path2)) + + def __del__(self): + self.ftp.close() + + def invalidate_cache(self, path=None): + if path is None: + self.dircache.clear() + else: + self.dircache.pop(path, None) + super().invalidate_cache(path) + + +class TransferDone(Exception): + """Internal exception to break out of transfer""" + + pass + + +class FTPFile(AbstractBufferedFile): + """Interact with a remote FTP file with read/write buffering""" + + def __init__( + self, + fs, + path, + mode="rb", + block_size="default", + autocommit=True, + cache_type="readahead", + cache_options=None, + **kwargs, + ): + super().__init__( + fs, + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_type=cache_type, + cache_options=cache_options, + **kwargs, + ) + if not autocommit: + self.target = self.path + self.path = "/".join([kwargs["tempdir"], str(uuid.uuid4())]) + + def commit(self): + self.fs.mv(self.path, self.target) + + def discard(self): + self.fs.rm(self.path) + + def _fetch_range(self, start, end): + """Get bytes between given byte limits + + Implemented by raising an exception in the fetch callback when the + number of bytes received reaches the requested amount. + + Will fail if the server does not respect the REST command on + retrieve requests. + """ + out = [] + total = [0] + + def callback(x): + total[0] += len(x) + if total[0] > end - start: + out.append(x[: (end - start) - total[0]]) + if end < self.size: + raise TransferDone + else: + out.append(x) + + if total[0] == end - start and end < self.size: + raise TransferDone + + try: + self.fs.ftp.retrbinary( + f"RETR {self.path}", + blocksize=self.blocksize, + rest=start, + callback=callback, + ) + except TransferDone: + try: + # stop transfer, we got enough bytes for this block + self.fs.ftp.abort() + self.fs.ftp.getmultiline() + except Error: + self.fs._connect() + + return b"".join(out) + + def _upload_chunk(self, final=False): + self.buffer.seek(0) + self.fs.ftp.storbinary( + f"STOR {self.path}", self.buffer, blocksize=self.blocksize, rest=self.offset + ) + return True + + +def _mlsd2(ftp, path="."): + """ + Fall back to using `dir` instead of `mlsd` if not supported. + + This parses a Linux style `ls -l` response to `dir`, but the response may + be platform dependent. + + Parameters + ---------- + ftp: ftplib.FTP + path: str + Expects to be given path, but defaults to ".". + """ + lines = [] + minfo = [] + ftp.dir(path, lines.append) + for line in lines: + split_line = line.split() + if len(split_line) < 9: + continue + this = ( + split_line[-1], + { + "modify": " ".join(split_line[5:8]), + "unix.owner": split_line[2], + "unix.group": split_line[3], + "unix.mode": split_line[0], + "size": split_line[4], + }, + ) + if this[1]["unix.mode"][0] == "d": + this[1]["type"] = "dir" + else: + this[1]["type"] = "file" + minfo.append(this) + return minfo diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/gist.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/gist.py new file mode 100644 index 0000000000000000000000000000000000000000..74117b544b02108fd2a7be06c716df477481ed47 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/gist.py @@ -0,0 +1,232 @@ +import requests + +from ..spec import AbstractFileSystem +from ..utils import infer_storage_options +from .memory import MemoryFile + + +class GistFileSystem(AbstractFileSystem): + """ + Interface to files in a single GitHub Gist. + + Provides read-only access to a gist's files. Gists do not contain + subdirectories, so file listing is straightforward. + + Parameters + ---------- + gist_id : str + The ID of the gist you want to access (the long hex value from the URL). + filenames : list[str] (optional) + If provided, only make a file system representing these files, and do not fetch + the list of all files for this gist. + sha : str (optional) + If provided, fetch a particular revision of the gist. If omitted, + the latest revision is used. + username : str (optional) + GitHub username for authentication (required if token is given). + token : str (optional) + GitHub personal access token (required if username is given). + timeout : (float, float) or float, optional + Connect and read timeouts for requests (default 60s each). + kwargs : dict + Stored on `self.request_kw` and passed to `requests.get` when fetching Gist + metadata or reading ("opening") a file. + """ + + protocol = "gist" + gist_url = "https://api.github.com/gists/{gist_id}" + gist_rev_url = "https://api.github.com/gists/{gist_id}/{sha}" + + def __init__( + self, + gist_id, + filenames=None, + sha=None, + username=None, + token=None, + timeout=None, + **kwargs, + ): + super().__init__() + self.gist_id = gist_id + self.filenames = filenames + self.sha = sha # revision of the gist (optional) + if (username is None) ^ (token is None): + # Both or neither must be set + if username or token: + raise ValueError("Auth requires both username and token, or neither.") + self.username = username + self.token = token + self.request_kw = kwargs + # Default timeouts to 60s connect/read if none provided + self.timeout = timeout if timeout is not None else (60, 60) + + # We use a single-level "directory" cache, because a gist is essentially flat + self.dircache[""] = self._fetch_file_list() + + @property + def kw(self): + """Auth parameters passed to 'requests' if we have username/token.""" + if self.username is not None and self.token is not None: + return {"auth": (self.username, self.token), **self.request_kw} + return self.request_kw + + def _fetch_gist_metadata(self): + """ + Fetch the JSON metadata for this gist (possibly for a specific revision). + """ + if self.sha: + url = self.gist_rev_url.format(gist_id=self.gist_id, sha=self.sha) + else: + url = self.gist_url.format(gist_id=self.gist_id) + + r = requests.get(url, timeout=self.timeout, **self.kw) + if r.status_code == 404: + raise FileNotFoundError( + f"Gist not found: {self.gist_id}@{self.sha or 'latest'}" + ) + r.raise_for_status() + return r.json() + + def _fetch_file_list(self): + """ + Returns a list of dicts describing each file in the gist. These get stored + in self.dircache[""]. + """ + meta = self._fetch_gist_metadata() + if self.filenames: + available_files = meta.get("files", {}) + files = {} + for fn in self.filenames: + if fn not in available_files: + raise FileNotFoundError(fn) + files[fn] = available_files[fn] + else: + files = meta.get("files", {}) + + out = [] + for fname, finfo in files.items(): + if finfo is None: + # Occasionally GitHub returns a file entry with null if it was deleted + continue + # Build a directory entry + out.append( + { + "name": fname, # file's name + "type": "file", # gists have no subdirectories + "size": finfo.get("size", 0), # file size in bytes + "raw_url": finfo.get("raw_url"), + } + ) + return out + + @classmethod + def _strip_protocol(cls, path): + """ + Remove 'gist://' from the path, if present. + """ + # The default infer_storage_options can handle gist://username:token@id/file + # or gist://id/file, but let's ensure we handle a normal usage too. + # We'll just strip the protocol prefix if it exists. + path = infer_storage_options(path).get("path", path) + return path.lstrip("/") + + @staticmethod + def _get_kwargs_from_urls(path): + """ + Parse 'gist://' style URLs into GistFileSystem constructor kwargs. + For example: + gist://:TOKEN@/file.txt + gist://username:TOKEN@/file.txt + """ + so = infer_storage_options(path) + out = {} + if "username" in so and so["username"]: + out["username"] = so["username"] + if "password" in so and so["password"]: + out["token"] = so["password"] + if "host" in so and so["host"]: + # We interpret 'host' as the gist ID + out["gist_id"] = so["host"] + + # Extract SHA and filename from path + if "path" in so and so["path"]: + path_parts = so["path"].rsplit("/", 2)[-2:] + if len(path_parts) == 2: + if path_parts[0]: # SHA present + out["sha"] = path_parts[0] + if path_parts[1]: # filename also present + out["filenames"] = [path_parts[1]] + + return out + + def ls(self, path="", detail=False, **kwargs): + """ + List files in the gist. Gists are single-level, so any 'path' is basically + the filename, or empty for all files. + + Parameters + ---------- + path : str, optional + The filename to list. If empty, returns all files in the gist. + detail : bool, default False + If True, return a list of dicts; if False, return a list of filenames. + """ + path = self._strip_protocol(path or "") + # If path is empty, return all + if path == "": + results = self.dircache[""] + else: + # We want just the single file with this name + all_files = self.dircache[""] + results = [f for f in all_files if f["name"] == path] + if not results: + raise FileNotFoundError(path) + if detail: + return results + else: + return sorted(f["name"] for f in results) + + def _open(self, path, mode="rb", block_size=None, **kwargs): + """ + Read a single file from the gist. + """ + if mode != "rb": + raise NotImplementedError("GitHub Gist FS is read-only (no write).") + + path = self._strip_protocol(path) + # Find the file entry in our dircache + matches = [f for f in self.dircache[""] if f["name"] == path] + if not matches: + raise FileNotFoundError(path) + finfo = matches[0] + + raw_url = finfo.get("raw_url") + if not raw_url: + raise FileNotFoundError(f"No raw_url for file: {path}") + + r = requests.get(raw_url, timeout=self.timeout, **self.kw) + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + return MemoryFile(path, None, r.content) + + def cat(self, path, recursive=False, on_error="raise", **kwargs): + """ + Return {path: contents} for the given file or files. If 'recursive' is True, + and path is empty, returns all files in the gist. + """ + paths = self.expand_path(path, recursive=recursive) + out = {} + for p in paths: + try: + with self.open(p, "rb") as f: + out[p] = f.read() + except FileNotFoundError as e: + if on_error == "raise": + raise e + elif on_error == "omit": + pass # skip + else: + out[p] = e + return out diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/git.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/git.py new file mode 100644 index 0000000000000000000000000000000000000000..808d293a1c991ea87d19a2129f3e56d9b813daaa --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/git.py @@ -0,0 +1,114 @@ +import os + +import pygit2 + +from fsspec.spec import AbstractFileSystem + +from .memory import MemoryFile + + +class GitFileSystem(AbstractFileSystem): + """Browse the files of a local git repo at any hash/tag/branch + + (experimental backend) + """ + + root_marker = "" + cachable = True + + def __init__(self, path=None, fo=None, ref=None, **kwargs): + """ + + Parameters + ---------- + path: str (optional) + Local location of the repo (uses current directory if not given). + May be deprecated in favour of ``fo``. When used with a higher + level function such as fsspec.open(), may be of the form + "git://[path-to-repo[:]][ref@]path/to/file" (but the actual + file path should not contain "@" or ":"). + fo: str (optional) + Same as ``path``, but passed as part of a chained URL. This one + takes precedence if both are given. + ref: str (optional) + Reference to work with, could be a hash, tag or branch name. Defaults + to current working tree. Note that ``ls`` and ``open`` also take hash, + so this becomes the default for those operations + kwargs + """ + super().__init__(**kwargs) + self.repo = pygit2.Repository(fo or path or os.getcwd()) + self.ref = ref or "master" + + @classmethod + def _strip_protocol(cls, path): + path = super()._strip_protocol(path).lstrip("/") + if ":" in path: + path = path.split(":", 1)[1] + if "@" in path: + path = path.split("@", 1)[1] + return path.lstrip("/") + + def _path_to_object(self, path, ref): + comm, ref = self.repo.resolve_refish(ref or self.ref) + parts = path.split("/") + tree = comm.tree + for part in parts: + if part and isinstance(tree, pygit2.Tree): + if part not in tree: + raise FileNotFoundError(path) + tree = tree[part] + return tree + + @staticmethod + def _get_kwargs_from_urls(path): + path = path.removeprefix("git://") + out = {} + if ":" in path: + out["path"], path = path.split(":", 1) + if "@" in path: + out["ref"], path = path.split("@", 1) + return out + + @staticmethod + def _object_to_info(obj, path=None): + # obj.name and obj.filemode are None for the root tree! + is_dir = isinstance(obj, pygit2.Tree) + return { + "type": "directory" if is_dir else "file", + "name": ( + "/".join([path, obj.name or ""]).lstrip("/") if path else obj.name + ), + "hex": str(obj.id), + "mode": "100644" if obj.filemode is None else f"{obj.filemode:o}", + "size": 0 if is_dir else obj.size, + } + + def ls(self, path, detail=True, ref=None, **kwargs): + tree = self._path_to_object(self._strip_protocol(path), ref) + return [ + GitFileSystem._object_to_info(obj, path) + if detail + else GitFileSystem._object_to_info(obj, path)["name"] + for obj in (tree if isinstance(tree, pygit2.Tree) else [tree]) + ] + + def info(self, path, ref=None, **kwargs): + tree = self._path_to_object(self._strip_protocol(path), ref) + return GitFileSystem._object_to_info(tree, path) + + def ukey(self, path, ref=None): + return self.info(path, ref=ref)["hex"] + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + ref=None, + **kwargs, + ): + obj = self._path_to_object(path, ref or self.ref) + return MemoryFile(data=obj.data) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/github.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/github.py new file mode 100644 index 0000000000000000000000000000000000000000..3630f6db54413e2c396f6cc1b6b10cd379200043 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/github.py @@ -0,0 +1,333 @@ +import base64 +import re + +import requests + +from ..spec import AbstractFileSystem +from ..utils import infer_storage_options +from .memory import MemoryFile + + +class GithubFileSystem(AbstractFileSystem): + """Interface to files in github + + An instance of this class provides the files residing within a remote github + repository. You may specify a point in the repos history, by SHA, branch + or tag (default is current master). + + For files less than 1 MB in size, file content is returned directly in a + MemoryFile. For larger files, or for files tracked by git-lfs, file content + is returned as an HTTPFile wrapping the ``download_url`` provided by the + GitHub API. + + When using fsspec.open, allows URIs of the form: + + - "github://path/file", in which case you must specify org, repo and + may specify sha in the extra args + - 'github://org:repo@/precip/catalog.yml', where the org and repo are + part of the URI + - 'github://org:repo@sha/precip/catalog.yml', where the sha is also included + + ``sha`` can be the full or abbreviated hex of the commit you want to fetch + from, or a branch or tag name (so long as it doesn't contain special characters + like "/", "?", which would have to be HTTP-encoded). + + For authorised access, you must provide username and token, which can be made + at https://github.com/settings/tokens + """ + + url = "https://api.github.com/repos/{org}/{repo}/git/trees/{sha}" + content_url = "https://api.github.com/repos/{org}/{repo}/contents/{path}?ref={sha}" + protocol = "github" + timeout = (60, 60) # connect, read timeouts + + def __init__( + self, org, repo, sha=None, username=None, token=None, timeout=None, **kwargs + ): + super().__init__(**kwargs) + self.org = org + self.repo = repo + if (username is None) ^ (token is None): + raise ValueError("Auth required both username and token") + self.username = username + self.token = token + if timeout is not None: + self.timeout = timeout + if sha is None: + # look up default branch (not necessarily "master") + u = "https://api.github.com/repos/{org}/{repo}" + r = requests.get( + u.format(org=org, repo=repo), timeout=self.timeout, **self.kw + ) + r.raise_for_status() + sha = r.json()["default_branch"] + + self.root = sha + self.ls("") + try: + from .http import HTTPFileSystem + + self.http_fs = HTTPFileSystem(**kwargs) + except ImportError: + self.http_fs = None + + @property + def kw(self): + if self.username: + return {"auth": (self.username, self.token)} + return {} + + @classmethod + def repos(cls, org_or_user, is_org=True): + """List repo names for given org or user + + This may become the top level of the FS + + Parameters + ---------- + org_or_user: str + Name of the github org or user to query + is_org: bool (default True) + Whether the name is an organisation (True) or user (False) + + Returns + ------- + List of string + """ + r = requests.get( + f"https://api.github.com/{['users', 'orgs'][is_org]}/{org_or_user}/repos", + timeout=cls.timeout, + ) + r.raise_for_status() + return [repo["name"] for repo in r.json()] + + @property + def tags(self): + """Names of tags in the repo""" + r = requests.get( + f"https://api.github.com/repos/{self.org}/{self.repo}/tags", + timeout=self.timeout, + **self.kw, + ) + r.raise_for_status() + return [t["name"] for t in r.json()] + + @property + def branches(self): + """Names of branches in the repo""" + r = requests.get( + f"https://api.github.com/repos/{self.org}/{self.repo}/branches", + timeout=self.timeout, + **self.kw, + ) + r.raise_for_status() + return [t["name"] for t in r.json()] + + @property + def refs(self): + """Named references, tags and branches""" + return {"tags": self.tags, "branches": self.branches} + + def ls(self, path, detail=False, sha=None, _sha=None, **kwargs): + """List files at given path + + Parameters + ---------- + path: str + Location to list, relative to repo root + detail: bool + If True, returns list of dicts, one per file; if False, returns + list of full filenames only + sha: str (optional) + List at the given point in the repo history, branch or tag name or commit + SHA + _sha: str (optional) + List this specific tree object (used internally to descend into trees) + """ + path = self._strip_protocol(path) + if path == "": + _sha = sha or self.root + if _sha is None: + parts = path.rstrip("/").split("/") + so_far = "" + _sha = sha or self.root + for part in parts: + out = self.ls(so_far, True, sha=sha, _sha=_sha) + so_far += "/" + part if so_far else part + out = [o for o in out if o["name"] == so_far] + if not out: + raise FileNotFoundError(path) + out = out[0] + if out["type"] == "file": + if detail: + return [out] + else: + return path + _sha = out["sha"] + if path not in self.dircache or sha not in [self.root, None]: + r = requests.get( + self.url.format(org=self.org, repo=self.repo, sha=_sha), + timeout=self.timeout, + **self.kw, + ) + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + types = {"blob": "file", "tree": "directory"} + out = [ + { + "name": path + "/" + f["path"] if path else f["path"], + "mode": f["mode"], + "type": types[f["type"]], + "size": f.get("size", 0), + "sha": f["sha"], + } + for f in r.json()["tree"] + if f["type"] in types + ] + if sha in [self.root, None]: + self.dircache[path] = out + else: + out = self.dircache[path] + if detail: + return out + else: + return sorted([f["name"] for f in out]) + + def invalidate_cache(self, path=None): + self.dircache.clear() + + @classmethod + def _strip_protocol(cls, path): + opts = infer_storage_options(path) + if "username" not in opts: + return super()._strip_protocol(path) + return opts["path"].lstrip("/") + + @staticmethod + def _get_kwargs_from_urls(path): + opts = infer_storage_options(path) + if "username" not in opts: + return {} + out = {"org": opts["username"], "repo": opts["password"]} + if opts["host"]: + out["sha"] = opts["host"] + return out + + def _open( + self, + path, + mode="rb", + block_size=None, + cache_options=None, + sha=None, + **kwargs, + ): + if mode != "rb": + raise NotImplementedError + + # construct a url to hit the GitHub API's repo contents API + url = self.content_url.format( + org=self.org, repo=self.repo, path=path, sha=sha or self.root + ) + + # make a request to this API, and parse the response as JSON + r = requests.get(url, timeout=self.timeout, **self.kw) + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + content_json = r.json() + + # if the response's content key is not empty, try to parse it as base64 + if content_json["content"]: + content = base64.b64decode(content_json["content"]) + + # as long as the content does not start with the string + # "version https://git-lfs.github.com/" + # then it is probably not a git-lfs pointer and we can just return + # the content directly + if not content.startswith(b"version https://git-lfs.github.com/"): + return MemoryFile(None, None, content) + + # we land here if the content was not present in the first response + # (regular file over 1MB or git-lfs tracked file) + # in this case, we get let the HTTPFileSystem handle the download + if self.http_fs is None: + raise ImportError( + "Please install fsspec[http] to access github files >1 MB " + "or git-lfs tracked files." + ) + return self.http_fs.open( + content_json["download_url"], + mode=mode, + block_size=block_size, + cache_options=cache_options, + **kwargs, + ) + + def rm(self, path, recursive=False, maxdepth=None, message=None): + path = self.expand_path(path, recursive=recursive, maxdepth=maxdepth) + for p in reversed(path): + self.rm_file(p, message=message) + + def rm_file(self, path, message=None, **kwargs): + """ + Remove a file from a specified branch using a given commit message. + + Since Github DELETE operation requires a branch name, and we can't reliably + determine whether the provided SHA refers to a branch, tag, or commit, we + assume it's a branch. If it's not, the user will encounter an error when + attempting to retrieve the file SHA or delete the file. + + Parameters + ---------- + path: str + The file's location relative to the repository root. + message: str, optional + The commit message for the deletion. + """ + + if not self.username: + raise ValueError("Authentication required") + + path = self._strip_protocol(path) + + # Attempt to get SHA from cache or Github API + sha = self._get_sha_from_cache(path) + if not sha: + url = self.content_url.format( + org=self.org, repo=self.repo, path=path.lstrip("/"), sha=self.root + ) + r = requests.get(url, timeout=self.timeout, **self.kw) + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + sha = r.json()["sha"] + + # Delete the file + delete_url = self.content_url.format( + org=self.org, repo=self.repo, path=path, sha=self.root + ) + branch = self.root + data = { + "message": message or f"Delete {path}", + "sha": sha, + **({"branch": branch} if branch else {}), + } + + r = requests.delete(delete_url, json=data, timeout=self.timeout, **self.kw) + error_message = r.json().get("message", "") + if re.search(r"Branch .+ not found", error_message): + error = "Remove only works when the filesystem is initialised from a branch or default (None)" + raise ValueError(error) + r.raise_for_status() + + self.invalidate_cache(path) + + def _get_sha_from_cache(self, path): + for entries in self.dircache.values(): + for entry in entries: + entry_path = entry.get("name") + if entry_path and entry_path == path and "sha" in entry: + return entry["sha"] + return None diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/http.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/http.py new file mode 100644 index 0000000000000000000000000000000000000000..093fa29bea8f0296bf003a4fa1f25b99fc219831 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/http.py @@ -0,0 +1,890 @@ +import asyncio +import io +import logging +import re +import weakref +from copy import copy +from urllib.parse import urlparse + +import aiohttp +import yarl + +from fsspec.asyn import AbstractAsyncStreamedFile, AsyncFileSystem, sync, sync_wrapper +from fsspec.callbacks import DEFAULT_CALLBACK +from fsspec.exceptions import FSTimeoutError +from fsspec.spec import AbstractBufferedFile +from fsspec.utils import ( + DEFAULT_BLOCK_SIZE, + glob_translate, + isfilelike, + nullcontext, + tokenize, +) + +from ..caching import AllBytes + +# https://stackoverflow.com/a/15926317/3821154 +ex = re.compile(r"""<(a|A)\s+(?:[^>]*?\s+)?(href|HREF)=["'](?P[^"']+)""") +ex2 = re.compile(r"""(?Phttp[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""") +logger = logging.getLogger("fsspec.http") + + +async def get_client(**kwargs): + return aiohttp.ClientSession(**kwargs) + + +class HTTPFileSystem(AsyncFileSystem): + """ + Simple File-System for fetching data via HTTP(S) + + ``ls()`` is implemented by loading the parent page and doing a regex + match on the result. If simple_link=True, anything of the form + "http(s)://server.com/stuff?thing=other"; otherwise only links within + HTML href tags will be used. + """ + + sep = "/" + + def __init__( + self, + simple_links=True, + block_size=None, + same_scheme=True, + size_policy=None, + cache_type="bytes", + cache_options=None, + asynchronous=False, + loop=None, + client_kwargs=None, + get_client=get_client, + encoded=False, + **storage_options, + ): + """ + NB: if this is called async, you must await set_client + + Parameters + ---------- + block_size: int + Blocks to read bytes; if 0, will default to raw requests file-like + objects instead of HTTPFile instances + simple_links: bool + If True, will consider both HTML tags and anything that looks + like a URL; if False, will consider only the former. + same_scheme: True + When doing ls/glob, if this is True, only consider paths that have + http/https matching the input URLs. + size_policy: this argument is deprecated + client_kwargs: dict + Passed to aiohttp.ClientSession, see + https://docs.aiohttp.org/en/stable/client_reference.html + For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}`` + get_client: Callable[..., aiohttp.ClientSession] + A callable, which takes keyword arguments and constructs + an aiohttp.ClientSession. Its state will be managed by + the HTTPFileSystem class. + storage_options: key-value + Any other parameters passed on to requests + cache_type, cache_options: defaults used in open() + """ + super().__init__(self, asynchronous=asynchronous, loop=loop, **storage_options) + self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE + self.simple_links = simple_links + self.same_schema = same_scheme + self.cache_type = cache_type + self.cache_options = cache_options + self.client_kwargs = client_kwargs or {} + self.get_client = get_client + self.encoded = encoded + self.kwargs = storage_options + self._session = None + + # Clean caching-related parameters from `storage_options` + # before propagating them as `request_options` through `self.kwargs`. + # TODO: Maybe rename `self.kwargs` to `self.request_options` to make + # it clearer. + request_options = copy(storage_options) + self.use_listings_cache = request_options.pop("use_listings_cache", False) + request_options.pop("listings_expiry_time", None) + request_options.pop("max_paths", None) + request_options.pop("skip_instance_cache", None) + self.kwargs = request_options + + @property + def fsid(self): + return "http" + + def encode_url(self, url): + return yarl.URL(url, encoded=self.encoded) + + @staticmethod + def close_session(loop, session): + if loop is not None and loop.is_running(): + try: + sync(loop, session.close, timeout=0.1) + return + except (TimeoutError, FSTimeoutError, NotImplementedError): + pass + connector = getattr(session, "_connector", None) + if connector is not None: + # close after loop is dead + connector._close() + + async def set_session(self): + if self._session is None: + self._session = await self.get_client(loop=self.loop, **self.client_kwargs) + if not self.asynchronous: + weakref.finalize(self, self.close_session, self.loop, self._session) + return self._session + + @classmethod + def _strip_protocol(cls, path): + """For HTTP, we always want to keep the full URL""" + return path + + @classmethod + def _parent(cls, path): + # override, since _strip_protocol is different for URLs + par = super()._parent(path) + if len(par) > 7: # "http://..." + return par + return "" + + async def _ls_real(self, url, detail=True, **kwargs): + # ignoring URL-encoded arguments + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(url) + session = await self.set_session() + async with session.get(self.encode_url(url), **self.kwargs) as r: + self._raise_not_found_for_status(r, url) + + if "Content-Type" in r.headers: + mimetype = r.headers["Content-Type"].partition(";")[0] + else: + mimetype = None + + if mimetype in ("text/html", None): + try: + text = await r.text(errors="ignore") + if self.simple_links: + links = ex2.findall(text) + [u[2] for u in ex.findall(text)] + else: + links = [u[2] for u in ex.findall(text)] + except UnicodeDecodeError: + links = [] # binary, not HTML + else: + links = [] + + out = set() + parts = urlparse(url) + for l in links: + if isinstance(l, tuple): + l = l[1] + if l.startswith("/") and len(l) > 1: + # absolute URL on this server + l = f"{parts.scheme}://{parts.netloc}{l}" + if l.startswith("http"): + if self.same_schema and l.startswith(url.rstrip("/") + "/"): + out.add(l) + elif l.replace("https", "http").startswith( + url.replace("https", "http").rstrip("/") + "/" + ): + # allowed to cross http <-> https + out.add(l) + else: + if l not in ["..", "../"]: + # Ignore FTP-like "parent" + out.add("/".join([url.rstrip("/"), l.lstrip("/")])) + if not out and url.endswith("/"): + out = await self._ls_real(url.rstrip("/"), detail=False) + if detail: + return [ + { + "name": u, + "size": None, + "type": "directory" if u.endswith("/") else "file", + } + for u in out + ] + else: + return sorted(out) + + async def _ls(self, url, detail=True, **kwargs): + if self.use_listings_cache and url in self.dircache: + out = self.dircache[url] + else: + out = await self._ls_real(url, detail=detail, **kwargs) + self.dircache[url] = out + return out + + ls = sync_wrapper(_ls) + + def _raise_not_found_for_status(self, response, url): + """ + Raises FileNotFoundError for 404s, otherwise uses raise_for_status. + """ + if response.status == 404: + raise FileNotFoundError(url) + response.raise_for_status() + + async def _cat_file(self, url, start=None, end=None, **kwargs): + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(url) + + if start is not None or end is not None: + if start == end: + return b"" + headers = kw.pop("headers", {}).copy() + + headers["Range"] = await self._process_limits(url, start, end) + kw["headers"] = headers + session = await self.set_session() + async with session.get(self.encode_url(url), **kw) as r: + out = await r.read() + self._raise_not_found_for_status(r, url) + return out + + async def _get_file( + self, rpath, lpath, chunk_size=5 * 2**20, callback=DEFAULT_CALLBACK, **kwargs + ): + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(rpath) + session = await self.set_session() + async with session.get(self.encode_url(rpath), **kw) as r: + try: + size = int(r.headers["content-length"]) + except (ValueError, KeyError): + size = None + + callback.set_size(size) + self._raise_not_found_for_status(r, rpath) + if isfilelike(lpath): + outfile = lpath + else: + outfile = open(lpath, "wb") # noqa: ASYNC230 + + try: + chunk = True + while chunk: + chunk = await r.content.read(chunk_size) + outfile.write(chunk) + callback.relative_update(len(chunk)) + finally: + if not isfilelike(lpath): + outfile.close() + + async def _put_file( + self, + lpath, + rpath, + chunk_size=5 * 2**20, + callback=DEFAULT_CALLBACK, + method="post", + mode="overwrite", + **kwargs, + ): + if mode != "overwrite": + raise NotImplementedError("Exclusive write") + + async def gen_chunks(): + # Support passing arbitrary file-like objects + # and use them instead of streams. + if isinstance(lpath, io.IOBase): + context = nullcontext(lpath) + use_seek = False # might not support seeking + else: + context = open(lpath, "rb") # noqa: ASYNC230 + use_seek = True + + with context as f: + if use_seek: + callback.set_size(f.seek(0, 2)) + f.seek(0) + else: + callback.set_size(getattr(f, "size", None)) + + chunk = f.read(chunk_size) + while chunk: + yield chunk + callback.relative_update(len(chunk)) + chunk = f.read(chunk_size) + + kw = self.kwargs.copy() + kw.update(kwargs) + session = await self.set_session() + + method = method.lower() + if method not in ("post", "put"): + raise ValueError( + f"method has to be either 'post' or 'put', not: {method!r}" + ) + + meth = getattr(session, method) + async with meth(self.encode_url(rpath), data=gen_chunks(), **kw) as resp: + self._raise_not_found_for_status(resp, rpath) + + async def _exists(self, path, **kwargs): + kw = self.kwargs.copy() + kw.update(kwargs) + try: + logger.debug(path) + session = await self.set_session() + r = await session.get(self.encode_url(path), **kw) + async with r: + return r.status < 400 + except aiohttp.ClientError: + return False + + async def _isfile(self, path, **kwargs): + return await self._exists(path, **kwargs) + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=None, # XXX: This differs from the base class. + cache_type=None, + cache_options=None, + size=None, + **kwargs, + ): + """Make a file-like object + + Parameters + ---------- + path: str + Full URL with protocol + mode: string + must be "rb" + block_size: int or None + Bytes to download in one request; use instance value if None. If + zero, will return a streaming Requests file-like instance. + kwargs: key-value + Any other parameters, passed to requests calls + """ + if mode != "rb": + raise NotImplementedError + block_size = block_size if block_size is not None else self.block_size + kw = self.kwargs.copy() + kw["asynchronous"] = self.asynchronous + kw.update(kwargs) + info = {} + size = size or info.update(self.info(path, **kwargs)) or info["size"] + session = sync(self.loop, self.set_session) + if block_size and size and info.get("partial", True): + return HTTPFile( + self, + path, + session=session, + block_size=block_size, + mode=mode, + size=size, + cache_type=cache_type or self.cache_type, + cache_options=cache_options or self.cache_options, + loop=self.loop, + **kw, + ) + else: + return HTTPStreamFile( + self, + path, + mode=mode, + loop=self.loop, + session=session, + **kw, + ) + + async def open_async(self, path, mode="rb", size=None, **kwargs): + session = await self.set_session() + if size is None: + try: + size = (await self._info(path, **kwargs))["size"] + except FileNotFoundError: + pass + return AsyncStreamFile( + self, + path, + loop=self.loop, + session=session, + size=size, + **kwargs, + ) + + def ukey(self, url): + """Unique identifier; assume HTTP files are static, unchanging""" + return tokenize(url, self.kwargs, self.protocol) + + async def _info(self, url, **kwargs): + """Get info of URL + + Tries to access location via HEAD, and then GET methods, but does + not fetch the data. + + It is possible that the server does not supply any size information, in + which case size will be given as None (and certain operations on the + corresponding file will not work). + """ + info = {} + session = await self.set_session() + + for policy in ["head", "get"]: + try: + info.update( + await _file_info( + self.encode_url(url), + size_policy=policy, + session=session, + **self.kwargs, + **kwargs, + ) + ) + if info.get("size") is not None: + break + except Exception as exc: + if policy == "get": + # If get failed, then raise a FileNotFoundError + raise FileNotFoundError(url) from exc + logger.debug("", exc_info=exc) + + return {"name": url, "size": None, **info, "type": "file"} + + async def _glob(self, path, maxdepth=None, **kwargs): + """ + Find files by glob-matching. + + This implementation is idntical to the one in AbstractFileSystem, + but "?" is not considered as a character for globbing, because it is + so common in URLs, often identifying the "query" part. + """ + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + import re + + ends_with_slash = path.endswith("/") # _strip_protocol strips trailing slash + path = self._strip_protocol(path) + append_slash_to_dirname = ends_with_slash or path.endswith(("/**", "/*")) + idx_star = path.find("*") if path.find("*") >= 0 else len(path) + idx_brace = path.find("[") if path.find("[") >= 0 else len(path) + + min_idx = min(idx_star, idx_brace) + + detail = kwargs.pop("detail", False) + + if not has_magic(path): + if await self._exists(path, **kwargs): + if not detail: + return [path] + else: + return {path: await self._info(path, **kwargs)} + else: + if not detail: + return [] # glob of non-existent returns empty + else: + return {} + elif "/" in path[:min_idx]: + min_idx = path[:min_idx].rindex("/") + root = path[: min_idx + 1] + depth = path[min_idx + 1 :].count("/") + 1 + else: + root = "" + depth = path[min_idx + 1 :].count("/") + 1 + + if "**" in path: + if maxdepth is not None: + idx_double_stars = path.find("**") + depth_double_stars = path[idx_double_stars:].count("/") + 1 + depth = depth - depth_double_stars + maxdepth + else: + depth = None + + allpaths = await self._find( + root, maxdepth=depth, withdirs=True, detail=True, **kwargs + ) + + pattern = glob_translate(path + ("/" if ends_with_slash else "")) + pattern = re.compile(pattern) + + out = { + ( + p.rstrip("/") + if not append_slash_to_dirname + and info["type"] == "directory" + and p.endswith("/") + else p + ): info + for p, info in sorted(allpaths.items()) + if pattern.match(p.rstrip("/")) + } + + if detail: + return out + else: + return list(out) + + async def _isdir(self, path): + # override, since all URLs are (also) files + try: + return bool(await self._ls(path)) + except (FileNotFoundError, ValueError): + return False + + async def _pipe_file(self, path, value, mode="overwrite", **kwargs): + """ + Write bytes to a remote file over HTTP. + + Parameters + ---------- + path : str + Target URL where the data should be written + value : bytes + Data to be written + mode : str + How to write to the file - 'overwrite' or 'append' + **kwargs : dict + Additional parameters to pass to the HTTP request + """ + url = self._strip_protocol(path) + headers = kwargs.pop("headers", {}) + headers["Content-Length"] = str(len(value)) + + session = await self.set_session() + + async with session.put(url, data=value, headers=headers, **kwargs) as r: + r.raise_for_status() + + +class HTTPFile(AbstractBufferedFile): + """ + A file-like object pointing to a remote HTTP(S) resource + + Supports only reading, with read-ahead of a predetermined block-size. + + In the case that the server does not supply the filesize, only reading of + the complete file in one go is supported. + + Parameters + ---------- + url: str + Full URL of the remote resource, including the protocol + session: aiohttp.ClientSession or None + All calls will be made within this session, to avoid restarting + connections where the server allows this + block_size: int or None + The amount of read-ahead to do, in bytes. Default is 5MB, or the value + configured for the FileSystem creating this file + size: None or int + If given, this is the size of the file in bytes, and we don't attempt + to call the server to find the value. + kwargs: all other key-values are passed to requests calls. + """ + + def __init__( + self, + fs, + url, + session=None, + block_size=None, + mode="rb", + cache_type="bytes", + cache_options=None, + size=None, + loop=None, + asynchronous=False, + **kwargs, + ): + if mode != "rb": + raise NotImplementedError("File mode not supported") + self.asynchronous = asynchronous + self.loop = loop + self.url = url + self.session = session + self.details = {"name": url, "size": size, "type": "file"} + super().__init__( + fs=fs, + path=url, + mode=mode, + block_size=block_size, + cache_type=cache_type, + cache_options=cache_options, + **kwargs, + ) + + def read(self, length=-1): + """Read bytes from file + + Parameters + ---------- + length: int + Read up to this many bytes. If negative, read all content to end of + file. If the server has not supplied the filesize, attempting to + read only part of the data will raise a ValueError. + """ + if ( + (length < 0 and self.loc == 0) # explicit read all + # but not when the size is known and fits into a block anyways + and not (self.size is not None and self.size <= self.blocksize) + ): + self._fetch_all() + if self.size is None: + if length < 0: + self._fetch_all() + else: + length = min(self.size - self.loc, length) + return super().read(length) + + async def async_fetch_all(self): + """Read whole file in one shot, without caching + + This is only called when position is still at zero, + and read() is called without a byte-count. + """ + logger.debug(f"Fetch all for {self}") + if not isinstance(self.cache, AllBytes): + r = await self.session.get(self.fs.encode_url(self.url), **self.kwargs) + async with r: + r.raise_for_status() + out = await r.read() + self.cache = AllBytes( + size=len(out), fetcher=None, blocksize=None, data=out + ) + self.size = len(out) + + _fetch_all = sync_wrapper(async_fetch_all) + + def _parse_content_range(self, headers): + """Parse the Content-Range header""" + s = headers.get("Content-Range", "") + m = re.match(r"bytes (\d+-\d+|\*)/(\d+|\*)", s) + if not m: + return None, None, None + + if m[1] == "*": + start = end = None + else: + start, end = [int(x) for x in m[1].split("-")] + total = None if m[2] == "*" else int(m[2]) + return start, end, total + + async def async_fetch_range(self, start, end): + """Download a block of data + + The expectation is that the server returns only the requested bytes, + with HTTP code 206. If this is not the case, we first check the headers, + and then stream the output - if the data size is bigger than we + requested, an exception is raised. + """ + logger.debug(f"Fetch range for {self}: {start}-{end}") + kwargs = self.kwargs.copy() + headers = kwargs.pop("headers", {}).copy() + headers["Range"] = f"bytes={start}-{end - 1}" + logger.debug(f"{self.url} : {headers['Range']}") + r = await self.session.get( + self.fs.encode_url(self.url), headers=headers, **kwargs + ) + async with r: + if r.status == 416: + # range request outside file + return b"" + r.raise_for_status() + + # If the server has handled the range request, it should reply + # with status 206 (partial content). But we'll guess that a suitable + # Content-Range header or a Content-Length no more than the + # requested range also mean we have got the desired range. + response_is_range = ( + r.status == 206 + or self._parse_content_range(r.headers)[0] == start + or int(r.headers.get("Content-Length", end + 1)) <= end - start + ) + + if response_is_range: + # partial content, as expected + out = await r.read() + elif start > 0: + raise ValueError( + "The HTTP server doesn't appear to support range requests. " + "Only reading this file from the beginning is supported. " + "Open with block_size=0 for a streaming file interface." + ) + else: + # Response is not a range, but we want the start of the file, + # so we can read the required amount anyway. + cl = 0 + out = [] + while True: + chunk = await r.content.read(2**20) + # data size unknown, let's read until we have enough + if chunk: + out.append(chunk) + cl += len(chunk) + if cl > end - start: + break + else: + break + out = b"".join(out)[: end - start] + return out + + _fetch_range = sync_wrapper(async_fetch_range) + + +magic_check = re.compile("([*[])") + + +def has_magic(s): + match = magic_check.search(s) + return match is not None + + +class HTTPStreamFile(AbstractBufferedFile): + def __init__(self, fs, url, mode="rb", loop=None, session=None, **kwargs): + self.asynchronous = kwargs.pop("asynchronous", False) + self.url = url + self.loop = loop + self.session = session + if mode != "rb": + raise ValueError + self.details = {"name": url, "size": None} + super().__init__(fs=fs, path=url, mode=mode, cache_type="none", **kwargs) + + async def cor(): + r = await self.session.get(self.fs.encode_url(url), **kwargs).__aenter__() + self.fs._raise_not_found_for_status(r, url) + return r + + self.r = sync(self.loop, cor) + self.loop = fs.loop + + def seek(self, loc, whence=0): + if loc == 0 and whence == 1: + return + if loc == self.loc and whence == 0: + return + raise ValueError("Cannot seek streaming HTTP file") + + async def _read(self, num=-1): + out = await self.r.content.read(num) + self.loc += len(out) + return out + + read = sync_wrapper(_read) + + async def _close(self): + self.r.close() + + def close(self): + asyncio.run_coroutine_threadsafe(self._close(), self.loop) + super().close() + + +class AsyncStreamFile(AbstractAsyncStreamedFile): + def __init__( + self, fs, url, mode="rb", loop=None, session=None, size=None, **kwargs + ): + self.url = url + self.session = session + self.r = None + if mode != "rb": + raise ValueError + self.details = {"name": url, "size": None} + self.kwargs = kwargs + super().__init__(fs=fs, path=url, mode=mode, cache_type="none") + self.size = size + + async def read(self, num=-1): + if self.r is None: + r = await self.session.get( + self.fs.encode_url(self.url), **self.kwargs + ).__aenter__() + self.fs._raise_not_found_for_status(r, self.url) + self.r = r + out = await self.r.content.read(num) + self.loc += len(out) + return out + + async def close(self): + if self.r is not None: + self.r.close() + self.r = None + await super().close() + + +async def get_range(session, url, start, end, file=None, **kwargs): + # explicit get a range when we know it must be safe + kwargs = kwargs.copy() + headers = kwargs.pop("headers", {}).copy() + headers["Range"] = f"bytes={start}-{end - 1}" + r = await session.get(url, headers=headers, **kwargs) + r.raise_for_status() + async with r: + out = await r.read() + if file: + with open(file, "r+b") as f: # noqa: ASYNC230 + f.seek(start) + f.write(out) + else: + return out + + +async def _file_info(url, session, size_policy="head", **kwargs): + """Call HEAD on the server to get details about the file (size/checksum etc.) + + Default operation is to explicitly allow redirects and use encoding + 'identity' (no compression) to get the true size of the target. + """ + logger.debug("Retrieve file size for %s", url) + kwargs = kwargs.copy() + ar = kwargs.pop("allow_redirects", True) + head = kwargs.get("headers", {}).copy() + head["Accept-Encoding"] = "identity" + kwargs["headers"] = head + + info = {} + if size_policy == "head": + r = await session.head(url, allow_redirects=ar, **kwargs) + elif size_policy == "get": + r = await session.get(url, allow_redirects=ar, **kwargs) + else: + raise TypeError(f'size_policy must be "head" or "get", got {size_policy}') + async with r: + r.raise_for_status() + + if "Content-Length" in r.headers: + # Some servers may choose to ignore Accept-Encoding and return + # compressed content, in which case the returned size is unreliable. + if "Content-Encoding" not in r.headers or r.headers["Content-Encoding"] in [ + "identity", + "", + ]: + info["size"] = int(r.headers["Content-Length"]) + elif "Content-Range" in r.headers: + info["size"] = int(r.headers["Content-Range"].split("/")[1]) + + if "Content-Type" in r.headers: + info["mimetype"] = r.headers["Content-Type"].partition(";")[0] + + if r.headers.get("Accept-Ranges") == "none": + # Some servers may explicitly discourage partial content requests, but + # the lack of "Accept-Ranges" does not always indicate they would fail + info["partial"] = False + + info["url"] = str(r.url) + + for checksum_field in ["ETag", "Content-MD5", "Digest", "Last-Modified"]: + if r.headers.get(checksum_field): + info[checksum_field] = r.headers[checksum_field] + + return info + + +async def _file_size(url, session=None, *args, **kwargs): + if session is None: + session = await get_client() + info = await _file_info(url, session=session, *args, **kwargs) + return info.get("size") + + +file_size = sync_wrapper(_file_size) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/http_sync.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/http_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..08799f20acde91b19dcdb4fbb02313bc64f9257a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/http_sync.py @@ -0,0 +1,931 @@ +"""This file is largely copied from http.py""" + +import io +import logging +import re +import urllib.error +import urllib.parse +from copy import copy +from json import dumps, loads +from urllib.parse import urlparse + +try: + import yarl +except (ImportError, ModuleNotFoundError, OSError): + yarl = False + +from fsspec.callbacks import _DEFAULT_CALLBACK +from fsspec.registry import register_implementation +from fsspec.spec import AbstractBufferedFile, AbstractFileSystem +from fsspec.utils import DEFAULT_BLOCK_SIZE, isfilelike, nullcontext, tokenize + +from ..caching import AllBytes + +# https://stackoverflow.com/a/15926317/3821154 +ex = re.compile(r"""<(a|A)\s+(?:[^>]*?\s+)?(href|HREF)=["'](?P[^"']+)""") +ex2 = re.compile(r"""(?Phttp[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""") +logger = logging.getLogger("fsspec.http") + + +class JsHttpException(urllib.error.HTTPError): ... + + +class StreamIO(io.BytesIO): + # fake class, so you can set attributes on it + # will eventually actually stream + ... + + +class ResponseProxy: + """Looks like a requests response""" + + def __init__(self, req, stream=False): + self.request = req + self.stream = stream + self._data = None + self._headers = None + + @property + def raw(self): + if self._data is None: + b = self.request.response.to_bytes() + if self.stream: + self._data = StreamIO(b) + else: + self._data = b + return self._data + + def close(self): + if hasattr(self, "_data"): + del self._data + + @property + def headers(self): + if self._headers is None: + self._headers = dict( + [ + _.split(": ") + for _ in self.request.getAllResponseHeaders().strip().split("\r\n") + ] + ) + return self._headers + + @property + def status_code(self): + return int(self.request.status) + + def raise_for_status(self): + if not self.ok: + raise JsHttpException( + self.url, self.status_code, self.reason, self.headers, None + ) + + def iter_content(self, chunksize, *_, **__): + while True: + out = self.raw.read(chunksize) + if out: + yield out + else: + break + + @property + def reason(self): + return self.request.statusText + + @property + def ok(self): + return self.status_code < 400 + + @property + def url(self): + return self.request.response.responseURL + + @property + def text(self): + # TODO: encoding from headers + return self.content.decode() + + @property + def content(self): + self.stream = False + return self.raw + + def json(self): + return loads(self.text) + + +class RequestsSessionShim: + def __init__(self): + self.headers = {} + + def request( + self, + method, + url, + params=None, + data=None, + headers=None, + cookies=None, + files=None, + auth=None, + timeout=None, + allow_redirects=None, + proxies=None, + hooks=None, + stream=None, + verify=None, + cert=None, + json=None, + ): + from js import Blob, XMLHttpRequest + + logger.debug("JS request: %s %s", method, url) + + if cert or verify or proxies or files or cookies or hooks: + raise NotImplementedError + if data and json: + raise ValueError("Use json= or data=, not both") + req = XMLHttpRequest.new() + extra = auth if auth else () + if params: + url = f"{url}?{urllib.parse.urlencode(params)}" + req.open(method, url, False, *extra) + if timeout: + req.timeout = timeout + if headers: + for k, v in headers.items(): + req.setRequestHeader(k, v) + + req.setRequestHeader("Accept", "application/octet-stream") + req.responseType = "arraybuffer" + if json: + blob = Blob.new([dumps(data)], {type: "application/json"}) + req.send(blob) + elif data: + if isinstance(data, io.IOBase): + data = data.read() + blob = Blob.new([data], {type: "application/octet-stream"}) + req.send(blob) + else: + req.send(None) + return ResponseProxy(req, stream=stream) + + def get(self, url, **kwargs): + return self.request("GET", url, **kwargs) + + def head(self, url, **kwargs): + return self.request("HEAD", url, **kwargs) + + def post(self, url, **kwargs): + return self.request("POST}", url, **kwargs) + + def put(self, url, **kwargs): + return self.request("PUT", url, **kwargs) + + def patch(self, url, **kwargs): + return self.request("PATCH", url, **kwargs) + + def delete(self, url, **kwargs): + return self.request("DELETE", url, **kwargs) + + +class HTTPFileSystem(AbstractFileSystem): + """ + Simple File-System for fetching data via HTTP(S) + + This is the BLOCKING version of the normal HTTPFileSystem. It uses + requests in normal python and the JS runtime in pyodide. + + ***This implementation is extremely experimental, do not use unless + you are testing pyodide/pyscript integration*** + """ + + protocol = ("http", "https", "sync-http", "sync-https") + sep = "/" + + def __init__( + self, + simple_links=True, + block_size=None, + same_scheme=True, + cache_type="readahead", + cache_options=None, + client_kwargs=None, + encoded=False, + **storage_options, + ): + """ + + Parameters + ---------- + block_size: int + Blocks to read bytes; if 0, will default to raw requests file-like + objects instead of HTTPFile instances + simple_links: bool + If True, will consider both HTML tags and anything that looks + like a URL; if False, will consider only the former. + same_scheme: True + When doing ls/glob, if this is True, only consider paths that have + http/https matching the input URLs. + size_policy: this argument is deprecated + client_kwargs: dict + Passed to aiohttp.ClientSession, see + https://docs.aiohttp.org/en/stable/client_reference.html + For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}`` + storage_options: key-value + Any other parameters passed on to requests + cache_type, cache_options: defaults used in open + """ + super().__init__(self, **storage_options) + self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE + self.simple_links = simple_links + self.same_schema = same_scheme + self.cache_type = cache_type + self.cache_options = cache_options + self.client_kwargs = client_kwargs or {} + self.encoded = encoded + self.kwargs = storage_options + + try: + import js # noqa: F401 + + logger.debug("Starting JS session") + self.session = RequestsSessionShim() + self.js = True + except Exception as e: + import requests + + logger.debug("Starting cpython session because of: %s", e) + self.session = requests.Session(**(client_kwargs or {})) + self.js = False + + request_options = copy(storage_options) + self.use_listings_cache = request_options.pop("use_listings_cache", False) + request_options.pop("listings_expiry_time", None) + request_options.pop("max_paths", None) + request_options.pop("skip_instance_cache", None) + self.kwargs = request_options + + @property + def fsid(self): + return "sync-http" + + def encode_url(self, url): + if yarl: + return yarl.URL(url, encoded=self.encoded) + return url + + @classmethod + def _strip_protocol(cls, path: str) -> str: + """For HTTP, we always want to keep the full URL""" + path = path.replace("sync-http://", "http://").replace( + "sync-https://", "https://" + ) + return path + + @classmethod + def _parent(cls, path): + # override, since _strip_protocol is different for URLs + par = super()._parent(path) + if len(par) > 7: # "http://..." + return par + return "" + + def _ls_real(self, url, detail=True, **kwargs): + # ignoring URL-encoded arguments + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(url) + r = self.session.get(self.encode_url(url), **self.kwargs) + self._raise_not_found_for_status(r, url) + text = r.text + if self.simple_links: + links = ex2.findall(text) + [u[2] for u in ex.findall(text)] + else: + links = [u[2] for u in ex.findall(text)] + out = set() + parts = urlparse(url) + for l in links: + if isinstance(l, tuple): + l = l[1] + if l.startswith("/") and len(l) > 1: + # absolute URL on this server + l = parts.scheme + "://" + parts.netloc + l + if l.startswith("http"): + if self.same_schema and l.startswith(url.rstrip("/") + "/"): + out.add(l) + elif l.replace("https", "http").startswith( + url.replace("https", "http").rstrip("/") + "/" + ): + # allowed to cross http <-> https + out.add(l) + else: + if l not in ["..", "../"]: + # Ignore FTP-like "parent" + out.add("/".join([url.rstrip("/"), l.lstrip("/")])) + if not out and url.endswith("/"): + out = self._ls_real(url.rstrip("/"), detail=False) + if detail: + return [ + { + "name": u, + "size": None, + "type": "directory" if u.endswith("/") else "file", + } + for u in out + ] + else: + return sorted(out) + + def ls(self, url, detail=True, **kwargs): + if self.use_listings_cache and url in self.dircache: + out = self.dircache[url] + else: + out = self._ls_real(url, detail=detail, **kwargs) + self.dircache[url] = out + return out + + def _raise_not_found_for_status(self, response, url): + """ + Raises FileNotFoundError for 404s, otherwise uses raise_for_status. + """ + if response.status_code == 404: + raise FileNotFoundError(url) + response.raise_for_status() + + def cat_file(self, url, start=None, end=None, **kwargs): + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(url) + + if start is not None or end is not None: + if start == end: + return b"" + headers = kw.pop("headers", {}).copy() + + headers["Range"] = self._process_limits(url, start, end) + kw["headers"] = headers + r = self.session.get(self.encode_url(url), **kw) + self._raise_not_found_for_status(r, url) + return r.content + + def get_file( + self, rpath, lpath, chunk_size=5 * 2**20, callback=_DEFAULT_CALLBACK, **kwargs + ): + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(rpath) + r = self.session.get(self.encode_url(rpath), **kw) + try: + size = int( + r.headers.get("content-length", None) + or r.headers.get("Content-Length", None) + ) + except (ValueError, KeyError, TypeError): + size = None + + callback.set_size(size) + self._raise_not_found_for_status(r, rpath) + if not isfilelike(lpath): + lpath = open(lpath, "wb") + for chunk in r.iter_content(chunk_size, decode_unicode=False): + lpath.write(chunk) + callback.relative_update(len(chunk)) + + def put_file( + self, + lpath, + rpath, + chunk_size=5 * 2**20, + callback=_DEFAULT_CALLBACK, + method="post", + **kwargs, + ): + def gen_chunks(): + # Support passing arbitrary file-like objects + # and use them instead of streams. + if isinstance(lpath, io.IOBase): + context = nullcontext(lpath) + use_seek = False # might not support seeking + else: + context = open(lpath, "rb") + use_seek = True + + with context as f: + if use_seek: + callback.set_size(f.seek(0, 2)) + f.seek(0) + else: + callback.set_size(getattr(f, "size", None)) + + chunk = f.read(chunk_size) + while chunk: + yield chunk + callback.relative_update(len(chunk)) + chunk = f.read(chunk_size) + + kw = self.kwargs.copy() + kw.update(kwargs) + + method = method.lower() + if method not in ("post", "put"): + raise ValueError( + f"method has to be either 'post' or 'put', not: {method!r}" + ) + + meth = getattr(self.session, method) + resp = meth(rpath, data=gen_chunks(), **kw) + self._raise_not_found_for_status(resp, rpath) + + def _process_limits(self, url, start, end): + """Helper for "Range"-based _cat_file""" + size = None + suff = False + if start is not None and start < 0: + # if start is negative and end None, end is the "suffix length" + if end is None: + end = -start + start = "" + suff = True + else: + size = size or self.info(url)["size"] + start = size + start + elif start is None: + start = 0 + if not suff: + if end is not None and end < 0: + if start is not None: + size = size or self.info(url)["size"] + end = size + end + elif end is None: + end = "" + if isinstance(end, int): + end -= 1 # bytes range is inclusive + return f"bytes={start}-{end}" + + def exists(self, path, **kwargs): + kw = self.kwargs.copy() + kw.update(kwargs) + try: + logger.debug(path) + r = self.session.get(self.encode_url(path), **kw) + return r.status_code < 400 + except Exception: + return False + + def isfile(self, path, **kwargs): + return self.exists(path, **kwargs) + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=None, # XXX: This differs from the base class. + cache_type=None, + cache_options=None, + size=None, + **kwargs, + ): + """Make a file-like object + + Parameters + ---------- + path: str + Full URL with protocol + mode: string + must be "rb" + block_size: int or None + Bytes to download in one request; use instance value if None. If + zero, will return a streaming Requests file-like instance. + kwargs: key-value + Any other parameters, passed to requests calls + """ + if mode != "rb": + raise NotImplementedError + block_size = block_size if block_size is not None else self.block_size + kw = self.kwargs.copy() + kw.update(kwargs) + size = size or self.info(path, **kwargs)["size"] + if block_size and size: + return HTTPFile( + self, + path, + session=self.session, + block_size=block_size, + mode=mode, + size=size, + cache_type=cache_type or self.cache_type, + cache_options=cache_options or self.cache_options, + **kw, + ) + else: + return HTTPStreamFile( + self, + path, + mode=mode, + session=self.session, + **kw, + ) + + def ukey(self, url): + """Unique identifier; assume HTTP files are static, unchanging""" + return tokenize(url, self.kwargs, self.protocol) + + def info(self, url, **kwargs): + """Get info of URL + + Tries to access location via HEAD, and then GET methods, but does + not fetch the data. + + It is possible that the server does not supply any size information, in + which case size will be given as None (and certain operations on the + corresponding file will not work). + """ + info = {} + for policy in ["head", "get"]: + try: + info.update( + _file_info( + self.encode_url(url), + size_policy=policy, + session=self.session, + **self.kwargs, + **kwargs, + ) + ) + if info.get("size") is not None: + break + except Exception as exc: + if policy == "get": + # If get failed, then raise a FileNotFoundError + raise FileNotFoundError(url) from exc + logger.debug(str(exc)) + + return {"name": url, "size": None, **info, "type": "file"} + + def glob(self, path, maxdepth=None, **kwargs): + """ + Find files by glob-matching. + + This implementation is idntical to the one in AbstractFileSystem, + but "?" is not considered as a character for globbing, because it is + so common in URLs, often identifying the "query" part. + """ + import re + + ends = path.endswith("/") + path = self._strip_protocol(path) + indstar = path.find("*") if path.find("*") >= 0 else len(path) + indbrace = path.find("[") if path.find("[") >= 0 else len(path) + + ind = min(indstar, indbrace) + + detail = kwargs.pop("detail", False) + + if not has_magic(path): + root = path + depth = 1 + if ends: + path += "/*" + elif self.exists(path): + if not detail: + return [path] + else: + return {path: self.info(path)} + else: + if not detail: + return [] # glob of non-existent returns empty + else: + return {} + elif "/" in path[:ind]: + ind2 = path[:ind].rindex("/") + root = path[: ind2 + 1] + depth = None if "**" in path else path[ind2 + 1 :].count("/") + 1 + else: + root = "" + depth = None if "**" in path else path[ind + 1 :].count("/") + 1 + + allpaths = self.find( + root, maxdepth=maxdepth or depth, withdirs=True, detail=True, **kwargs + ) + # Escape characters special to python regex, leaving our supported + # special characters in place. + # See https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html + # for shell globbing details. + pattern = ( + "^" + + ( + path.replace("\\", r"\\") + .replace(".", r"\.") + .replace("+", r"\+") + .replace("//", "/") + .replace("(", r"\(") + .replace(")", r"\)") + .replace("|", r"\|") + .replace("^", r"\^") + .replace("$", r"\$") + .replace("{", r"\{") + .replace("}", r"\}") + .rstrip("/") + ) + + "$" + ) + pattern = re.sub("[*]{2}", "=PLACEHOLDER=", pattern) + pattern = re.sub("[*]", "[^/]*", pattern) + pattern = re.compile(pattern.replace("=PLACEHOLDER=", ".*")) + out = { + p: allpaths[p] + for p in sorted(allpaths) + if pattern.match(p.replace("//", "/").rstrip("/")) + } + if detail: + return out + else: + return list(out) + + def isdir(self, path): + # override, since all URLs are (also) files + try: + return bool(self.ls(path)) + except (FileNotFoundError, ValueError): + return False + + +class HTTPFile(AbstractBufferedFile): + """ + A file-like object pointing to a remove HTTP(S) resource + + Supports only reading, with read-ahead of a predermined block-size. + + In the case that the server does not supply the filesize, only reading of + the complete file in one go is supported. + + Parameters + ---------- + url: str + Full URL of the remote resource, including the protocol + session: requests.Session or None + All calls will be made within this session, to avoid restarting + connections where the server allows this + block_size: int or None + The amount of read-ahead to do, in bytes. Default is 5MB, or the value + configured for the FileSystem creating this file + size: None or int + If given, this is the size of the file in bytes, and we don't attempt + to call the server to find the value. + kwargs: all other key-values are passed to requests calls. + """ + + def __init__( + self, + fs, + url, + session=None, + block_size=None, + mode="rb", + cache_type="bytes", + cache_options=None, + size=None, + **kwargs, + ): + if mode != "rb": + raise NotImplementedError("File mode not supported") + self.url = url + self.session = session + self.details = {"name": url, "size": size, "type": "file"} + super().__init__( + fs=fs, + path=url, + mode=mode, + block_size=block_size, + cache_type=cache_type, + cache_options=cache_options, + **kwargs, + ) + + def read(self, length=-1): + """Read bytes from file + + Parameters + ---------- + length: int + Read up to this many bytes. If negative, read all content to end of + file. If the server has not supplied the filesize, attempting to + read only part of the data will raise a ValueError. + """ + if ( + (length < 0 and self.loc == 0) # explicit read all + # but not when the size is known and fits into a block anyways + and not (self.size is not None and self.size <= self.blocksize) + ): + self._fetch_all() + if self.size is None: + if length < 0: + self._fetch_all() + else: + length = min(self.size - self.loc, length) + return super().read(length) + + def _fetch_all(self): + """Read whole file in one shot, without caching + + This is only called when position is still at zero, + and read() is called without a byte-count. + """ + logger.debug(f"Fetch all for {self}") + if not isinstance(self.cache, AllBytes): + r = self.session.get(self.fs.encode_url(self.url), **self.kwargs) + r.raise_for_status() + out = r.content + self.cache = AllBytes(size=len(out), fetcher=None, blocksize=None, data=out) + self.size = len(out) + + def _parse_content_range(self, headers): + """Parse the Content-Range header""" + s = headers.get("Content-Range", "") + m = re.match(r"bytes (\d+-\d+|\*)/(\d+|\*)", s) + if not m: + return None, None, None + + if m[1] == "*": + start = end = None + else: + start, end = [int(x) for x in m[1].split("-")] + total = None if m[2] == "*" else int(m[2]) + return start, end, total + + def _fetch_range(self, start, end): + """Download a block of data + + The expectation is that the server returns only the requested bytes, + with HTTP code 206. If this is not the case, we first check the headers, + and then stream the output - if the data size is bigger than we + requested, an exception is raised. + """ + logger.debug(f"Fetch range for {self}: {start}-{end}") + kwargs = self.kwargs.copy() + headers = kwargs.pop("headers", {}).copy() + headers["Range"] = f"bytes={start}-{end - 1}" + logger.debug("%s : %s", self.url, headers["Range"]) + r = self.session.get(self.fs.encode_url(self.url), headers=headers, **kwargs) + if r.status_code == 416: + # range request outside file + return b"" + r.raise_for_status() + + # If the server has handled the range request, it should reply + # with status 206 (partial content). But we'll guess that a suitable + # Content-Range header or a Content-Length no more than the + # requested range also mean we have got the desired range. + cl = r.headers.get("Content-Length", r.headers.get("content-length", end + 1)) + response_is_range = ( + r.status_code == 206 + or self._parse_content_range(r.headers)[0] == start + or int(cl) <= end - start + ) + + if response_is_range: + # partial content, as expected + out = r.content + elif start > 0: + raise ValueError( + "The HTTP server doesn't appear to support range requests. " + "Only reading this file from the beginning is supported. " + "Open with block_size=0 for a streaming file interface." + ) + else: + # Response is not a range, but we want the start of the file, + # so we can read the required amount anyway. + cl = 0 + out = [] + for chunk in r.iter_content(2**20, False): + out.append(chunk) + cl += len(chunk) + out = b"".join(out)[: end - start] + return out + + +magic_check = re.compile("([*[])") + + +def has_magic(s): + match = magic_check.search(s) + return match is not None + + +class HTTPStreamFile(AbstractBufferedFile): + def __init__(self, fs, url, mode="rb", session=None, **kwargs): + self.url = url + self.session = session + if mode != "rb": + raise ValueError + self.details = {"name": url, "size": None} + super().__init__(fs=fs, path=url, mode=mode, cache_type="readahead", **kwargs) + + r = self.session.get(self.fs.encode_url(url), stream=True, **kwargs) + self.fs._raise_not_found_for_status(r, url) + self.it = r.iter_content(1024, False) + self.leftover = b"" + + self.r = r + + def seek(self, *args, **kwargs): + raise ValueError("Cannot seek streaming HTTP file") + + def read(self, num=-1): + bufs = [self.leftover] + leng = len(self.leftover) + while leng < num or num < 0: + try: + out = self.it.__next__() + except StopIteration: + break + if out: + bufs.append(out) + else: + break + leng += len(out) + out = b"".join(bufs) + if num >= 0: + self.leftover = out[num:] + out = out[:num] + else: + self.leftover = b"" + self.loc += len(out) + return out + + def close(self): + self.r.close() + self.closed = True + + +def get_range(session, url, start, end, **kwargs): + # explicit get a range when we know it must be safe + kwargs = kwargs.copy() + headers = kwargs.pop("headers", {}).copy() + headers["Range"] = f"bytes={start}-{end - 1}" + r = session.get(url, headers=headers, **kwargs) + r.raise_for_status() + return r.content + + +def _file_info(url, session, size_policy="head", **kwargs): + """Call HEAD on the server to get details about the file (size/checksum etc.) + + Default operation is to explicitly allow redirects and use encoding + 'identity' (no compression) to get the true size of the target. + """ + logger.debug("Retrieve file size for %s", url) + kwargs = kwargs.copy() + ar = kwargs.pop("allow_redirects", True) + head = kwargs.get("headers", {}).copy() + # TODO: not allowed in JS + # head["Accept-Encoding"] = "identity" + kwargs["headers"] = head + + info = {} + if size_policy == "head": + r = session.head(url, allow_redirects=ar, **kwargs) + elif size_policy == "get": + r = session.get(url, allow_redirects=ar, **kwargs) + else: + raise TypeError(f'size_policy must be "head" or "get", got {size_policy}') + r.raise_for_status() + + # TODO: + # recognise lack of 'Accept-Ranges', + # or 'Accept-Ranges': 'none' (not 'bytes') + # to mean streaming only, no random access => return None + if "Content-Length" in r.headers: + info["size"] = int(r.headers["Content-Length"]) + elif "Content-Range" in r.headers: + info["size"] = int(r.headers["Content-Range"].split("/")[1]) + elif "content-length" in r.headers: + info["size"] = int(r.headers["content-length"]) + elif "content-range" in r.headers: + info["size"] = int(r.headers["content-range"].split("/")[1]) + + for checksum_field in ["ETag", "Content-MD5", "Digest"]: + if r.headers.get(checksum_field): + info[checksum_field] = r.headers[checksum_field] + + return info + + +# importing this is enough to register it +def register(): + register_implementation("http", HTTPFileSystem, clobber=True) + register_implementation("https", HTTPFileSystem, clobber=True) + register_implementation("sync-http", HTTPFileSystem, clobber=True) + register_implementation("sync-https", HTTPFileSystem, clobber=True) + + +register() + + +def unregister(): + from fsspec.implementations.http import HTTPFileSystem + + register_implementation("http", HTTPFileSystem, clobber=True) + register_implementation("https", HTTPFileSystem, clobber=True) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/jupyter.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/jupyter.py new file mode 100644 index 0000000000000000000000000000000000000000..2839f4c1feea56dddd54bdc00f0b884c8461d29e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/jupyter.py @@ -0,0 +1,124 @@ +import base64 +import io +import re + +import requests + +import fsspec + + +class JupyterFileSystem(fsspec.AbstractFileSystem): + """View of the files as seen by a Jupyter server (notebook or lab)""" + + protocol = ("jupyter", "jlab") + + def __init__(self, url, tok=None, **kwargs): + """ + + Parameters + ---------- + url : str + Base URL of the server, like "http://127.0.0.1:8888". May include + token in the string, which is given by the process when starting up + tok : str + If the token is obtained separately, can be given here + kwargs + """ + if "?" in url: + if tok is None: + try: + tok = re.findall("token=([a-z0-9]+)", url)[0] + except IndexError as e: + raise ValueError("Could not determine token") from e + url = url.split("?", 1)[0] + self.url = url.rstrip("/") + "/api/contents" + self.session = requests.Session() + if tok: + self.session.headers["Authorization"] = f"token {tok}" + + super().__init__(**kwargs) + + def ls(self, path, detail=True, **kwargs): + path = self._strip_protocol(path) + r = self.session.get(f"{self.url}/{path}") + if r.status_code == 404: + return FileNotFoundError(path) + r.raise_for_status() + out = r.json() + + if out["type"] == "directory": + out = out["content"] + else: + out = [out] + for o in out: + o["name"] = o.pop("path") + o.pop("content") + if o["type"] == "notebook": + o["type"] = "file" + if detail: + return out + return [o["name"] for o in out] + + def cat_file(self, path, start=None, end=None, **kwargs): + path = self._strip_protocol(path) + r = self.session.get(f"{self.url}/{path}") + if r.status_code == 404: + return FileNotFoundError(path) + r.raise_for_status() + out = r.json() + if out["format"] == "text": + # data should be binary + b = out["content"].encode() + else: + b = base64.b64decode(out["content"]) + return b[start:end] + + def pipe_file(self, path, value, **_): + path = self._strip_protocol(path) + json = { + "name": path.rsplit("/", 1)[-1], + "path": path, + "size": len(value), + "content": base64.b64encode(value).decode(), + "format": "base64", + "type": "file", + } + self.session.put(f"{self.url}/{path}", json=json) + + def mkdir(self, path, create_parents=True, **kwargs): + path = self._strip_protocol(path) + if create_parents and "/" in path: + self.mkdir(path.rsplit("/", 1)[0], True) + json = { + "name": path.rsplit("/", 1)[-1], + "path": path, + "size": None, + "content": None, + "type": "directory", + } + self.session.put(f"{self.url}/{path}", json=json) + + def _rm(self, path): + path = self._strip_protocol(path) + self.session.delete(f"{self.url}/{path}") + + def _open(self, path, mode="rb", **kwargs): + path = self._strip_protocol(path) + if mode == "rb": + data = self.cat_file(path) + return io.BytesIO(data) + else: + return SimpleFileWriter(self, path, mode="wb") + + +class SimpleFileWriter(fsspec.spec.AbstractBufferedFile): + def _upload_chunk(self, final=False): + """Never uploads a chunk until file is done + + Not suitable for large files + """ + if final is False: + return False + self.buffer.seek(0) + data = self.buffer.read() + self.fs.pipe_file(self.path, data) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/libarchive.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/libarchive.py new file mode 100644 index 0000000000000000000000000000000000000000..eb6f145352e1989e0477e259be02d8d7f4d729e2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/libarchive.py @@ -0,0 +1,213 @@ +from contextlib import contextmanager +from ctypes import ( + CFUNCTYPE, + POINTER, + c_int, + c_longlong, + c_void_p, + cast, + create_string_buffer, +) + +import libarchive +import libarchive.ffi as ffi + +from fsspec import open_files +from fsspec.archive import AbstractArchiveFileSystem +from fsspec.implementations.memory import MemoryFile +from fsspec.utils import DEFAULT_BLOCK_SIZE + +# Libarchive requires seekable files or memory only for certain archive +# types. However, since we read the directory first to cache the contents +# and also allow random access to any file, the file-like object needs +# to be seekable no matter what. + +# Seek call-backs (not provided in the libarchive python wrapper) +SEEK_CALLBACK = CFUNCTYPE(c_longlong, c_int, c_void_p, c_longlong, c_int) +read_set_seek_callback = ffi.ffi( + "read_set_seek_callback", [ffi.c_archive_p, SEEK_CALLBACK], c_int, ffi.check_int +) +new_api = hasattr(ffi, "NO_OPEN_CB") + + +@contextmanager +def custom_reader(file, format_name="all", filter_name="all", block_size=ffi.page_size): + """Read an archive from a seekable file-like object. + + The `file` object must support the standard `readinto` and 'seek' methods. + """ + buf = create_string_buffer(block_size) + buf_p = cast(buf, c_void_p) + + def read_func(archive_p, context, ptrptr): + # readinto the buffer, returns number of bytes read + length = file.readinto(buf) + # write the address of the buffer into the pointer + ptrptr = cast(ptrptr, POINTER(c_void_p)) + ptrptr[0] = buf_p + # tell libarchive how much data was written into the buffer + return length + + def seek_func(archive_p, context, offset, whence): + file.seek(offset, whence) + # tell libarchvie the current position + return file.tell() + + read_cb = ffi.READ_CALLBACK(read_func) + seek_cb = SEEK_CALLBACK(seek_func) + + if new_api: + open_cb = ffi.NO_OPEN_CB + close_cb = ffi.NO_CLOSE_CB + else: + open_cb = libarchive.read.OPEN_CALLBACK(ffi.VOID_CB) + close_cb = libarchive.read.CLOSE_CALLBACK(ffi.VOID_CB) + + with libarchive.read.new_archive_read(format_name, filter_name) as archive_p: + read_set_seek_callback(archive_p, seek_cb) + ffi.read_open(archive_p, None, open_cb, read_cb, close_cb) + yield libarchive.read.ArchiveRead(archive_p) + + +class LibArchiveFileSystem(AbstractArchiveFileSystem): + """Compressed archives as a file-system (read-only) + + Supports the following formats: + tar, pax , cpio, ISO9660, zip, mtree, shar, ar, raw, xar, lha/lzh, rar + Microsoft CAB, 7-Zip, WARC + + See the libarchive documentation for further restrictions. + https://www.libarchive.org/ + + Keeps file object open while instance lives. It only works in seekable + file-like objects. In case the filesystem does not support this kind of + file object, it is recommended to cache locally. + + This class is pickleable, but not necessarily thread-safe (depends on the + platform). See libarchive documentation for details. + """ + + root_marker = "" + protocol = "libarchive" + cachable = False + + def __init__( + self, + fo="", + mode="r", + target_protocol=None, + target_options=None, + block_size=DEFAULT_BLOCK_SIZE, + **kwargs, + ): + """ + Parameters + ---------- + fo: str or file-like + Contains ZIP, and must exist. If a str, will fetch file using + :meth:`~fsspec.open_files`, which must return one file exactly. + mode: str + Currently, only 'r' accepted + target_protocol: str (optional) + If ``fo`` is a string, this value can be used to override the + FS protocol inferred from a URL + target_options: dict (optional) + Kwargs passed when instantiating the target FS, if ``fo`` is + a string. + """ + super().__init__(self, **kwargs) + if mode != "r": + raise ValueError("Only read from archive files accepted") + if isinstance(fo, str): + files = open_files(fo, protocol=target_protocol, **(target_options or {})) + if len(files) != 1: + raise ValueError( + f'Path "{fo}" did not resolve to exactly one file: "{files}"' + ) + fo = files[0] + self.of = fo + self.fo = fo.__enter__() # the whole instance is a context + self.block_size = block_size + self.dir_cache = None + + @contextmanager + def _open_archive(self): + self.fo.seek(0) + with custom_reader(self.fo, block_size=self.block_size) as arc: + yield arc + + @classmethod + def _strip_protocol(cls, path): + # file paths are always relative to the archive root + return super()._strip_protocol(path).lstrip("/") + + def _get_dirs(self): + fields = { + "name": "pathname", + "size": "size", + "created": "ctime", + "mode": "mode", + "uid": "uid", + "gid": "gid", + "mtime": "mtime", + } + + if self.dir_cache is not None: + return + + self.dir_cache = {} + list_names = [] + with self._open_archive() as arc: + for entry in arc: + if not entry.isdir and not entry.isfile: + # Skip symbolic links, fifo entries, etc. + continue + self.dir_cache.update( + { + dirname: {"name": dirname, "size": 0, "type": "directory"} + for dirname in self._all_dirnames(set(entry.name)) + } + ) + f = {key: getattr(entry, fields[key]) for key in fields} + f["type"] = "directory" if entry.isdir else "file" + list_names.append(entry.name) + + self.dir_cache[f["name"]] = f + # libarchive does not seem to return an entry for the directories (at least + # not in all formats), so get the directories names from the files names + self.dir_cache.update( + { + dirname: {"name": dirname, "size": 0, "type": "directory"} + for dirname in self._all_dirnames(list_names) + } + ) + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + path = self._strip_protocol(path) + if mode != "rb": + raise NotImplementedError + + data = bytes() + with self._open_archive() as arc: + for entry in arc: + if entry.pathname != path: + continue + + if entry.size == 0: + # empty file, so there are no blocks + break + + for block in entry.get_blocks(entry.size): + data = block + break + else: + raise ValueError + return MemoryFile(fs=self, path=path, data=data) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/local.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/local.py new file mode 100644 index 0000000000000000000000000000000000000000..64dc8bb21956e9c5024b47d46d9e9550931891d8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/local.py @@ -0,0 +1,514 @@ +import datetime +import io +import logging +import os +import os.path as osp +import shutil +import stat +import tempfile +from functools import lru_cache + +from fsspec import AbstractFileSystem +from fsspec.compression import compr +from fsspec.core import get_compression +from fsspec.utils import isfilelike, stringify_path + +logger = logging.getLogger("fsspec.local") + + +class LocalFileSystem(AbstractFileSystem): + """Interface to files on local storage + + Parameters + ---------- + auto_mkdir: bool + Whether, when opening a file, the directory containing it should + be created (if it doesn't already exist). This is assumed by pyarrow + code. + """ + + root_marker = "/" + protocol = "file", "local" + local_file = True + + def __init__(self, auto_mkdir=False, **kwargs): + super().__init__(**kwargs) + self.auto_mkdir = auto_mkdir + + @property + def fsid(self): + return "local" + + def mkdir(self, path, create_parents=True, **kwargs): + path = self._strip_protocol(path) + if self.exists(path): + raise FileExistsError(path) + if create_parents: + self.makedirs(path, exist_ok=True) + else: + os.mkdir(path, **kwargs) + + def makedirs(self, path, exist_ok=False): + path = self._strip_protocol(path) + os.makedirs(path, exist_ok=exist_ok) + + def rmdir(self, path): + path = self._strip_protocol(path) + os.rmdir(path) + + def ls(self, path, detail=False, **kwargs): + path = self._strip_protocol(path) + path_info = self.info(path) + infos = [] + if path_info["type"] == "directory": + with os.scandir(path) as it: + for f in it: + try: + # Only get the info if requested since it is a bit expensive (the stat call inside) + # The strip_protocol is also used in info() and calls make_path_posix to always return posix paths + info = self.info(f) if detail else self._strip_protocol(f.path) + infos.append(info) + except FileNotFoundError: + pass + else: + infos = [path_info] if detail else [path_info["name"]] + + return infos + + def info(self, path, **kwargs): + if isinstance(path, os.DirEntry): + # scandir DirEntry + out = path.stat(follow_symlinks=False) + link = path.is_symlink() + if path.is_dir(follow_symlinks=False): + t = "directory" + elif path.is_file(follow_symlinks=False): + t = "file" + else: + t = "other" + + size = out.st_size + if link: + try: + out2 = path.stat(follow_symlinks=True) + size = out2.st_size + except OSError: + size = 0 + path = self._strip_protocol(path.path) + else: + # str or path-like + path = self._strip_protocol(path) + out = os.stat(path, follow_symlinks=False) + link = stat.S_ISLNK(out.st_mode) + if link: + out = os.stat(path, follow_symlinks=True) + size = out.st_size + if stat.S_ISDIR(out.st_mode): + t = "directory" + elif stat.S_ISREG(out.st_mode): + t = "file" + else: + t = "other" + + # Check for the 'st_birthtime' attribute, which is not always present; fallback to st_ctime + created_time = getattr(out, "st_birthtime", out.st_ctime) + + result = { + "name": path, + "size": size, + "type": t, + "created": created_time, + "islink": link, + } + for field in ["mode", "uid", "gid", "mtime", "ino", "nlink"]: + result[field] = getattr(out, f"st_{field}") + if link: + result["destination"] = os.readlink(path) + return result + + def lexists(self, path, **kwargs): + return osp.lexists(path) + + def cp_file(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1) + path2 = self._strip_protocol(path2) + if self.auto_mkdir: + self.makedirs(self._parent(path2), exist_ok=True) + if self.isfile(path1): + shutil.copyfile(path1, path2) + elif self.isdir(path1): + self.mkdirs(path2, exist_ok=True) + else: + raise FileNotFoundError(path1) + + def isfile(self, path): + path = self._strip_protocol(path) + return os.path.isfile(path) + + def isdir(self, path): + path = self._strip_protocol(path) + return os.path.isdir(path) + + def get_file(self, path1, path2, callback=None, **kwargs): + if isfilelike(path2): + with open(path1, "rb") as f: + shutil.copyfileobj(f, path2) + else: + return self.cp_file(path1, path2, **kwargs) + + def put_file(self, path1, path2, callback=None, **kwargs): + return self.cp_file(path1, path2, **kwargs) + + def mv(self, path1, path2, recursive: bool = True, **kwargs): + """Move files/directories + For the specific case of local, all ops on directories are recursive and + the recursive= kwarg is ignored. + """ + path1 = self._strip_protocol(path1) + path2 = self._strip_protocol(path2) + shutil.move(path1, path2) + + def link(self, src, dst, **kwargs): + src = self._strip_protocol(src) + dst = self._strip_protocol(dst) + os.link(src, dst, **kwargs) + + def symlink(self, src, dst, **kwargs): + src = self._strip_protocol(src) + dst = self._strip_protocol(dst) + os.symlink(src, dst, **kwargs) + + def islink(self, path) -> bool: + return os.path.islink(self._strip_protocol(path)) + + def rm_file(self, path): + os.remove(self._strip_protocol(path)) + + def rm(self, path, recursive=False, maxdepth=None): + if not isinstance(path, list): + path = [path] + + for p in path: + p = self._strip_protocol(p) + if self.isdir(p): + if not recursive: + raise ValueError("Cannot delete directory, set recursive=True") + if osp.abspath(p) == os.getcwd(): + raise ValueError("Cannot delete current working directory") + shutil.rmtree(p) + else: + os.remove(p) + + def unstrip_protocol(self, name): + name = self._strip_protocol(name) # normalise for local/win/... + return f"file://{name}" + + def _open(self, path, mode="rb", block_size=None, **kwargs): + path = self._strip_protocol(path) + if self.auto_mkdir and "w" in mode: + self.makedirs(self._parent(path), exist_ok=True) + return LocalFileOpener(path, mode, fs=self, **kwargs) + + def touch(self, path, truncate=True, **kwargs): + path = self._strip_protocol(path) + if self.auto_mkdir: + self.makedirs(self._parent(path), exist_ok=True) + if self.exists(path): + os.utime(path, None) + else: + open(path, "a").close() + if truncate: + os.truncate(path, 0) + + def created(self, path): + info = self.info(path=path) + return datetime.datetime.fromtimestamp( + info["created"], tz=datetime.timezone.utc + ) + + def modified(self, path): + info = self.info(path=path) + return datetime.datetime.fromtimestamp(info["mtime"], tz=datetime.timezone.utc) + + @classmethod + def _parent(cls, path): + path = cls._strip_protocol(path) + if os.sep == "/": + # posix native + return path.rsplit("/", 1)[0] or "/" + else: + # NT + path_ = path.rsplit("/", 1)[0] + if len(path_) <= 3: + if path_[1:2] == ":": + # nt root (something like c:/) + return path_[0] + ":/" + # More cases may be required here + return path_ + + @classmethod + def _strip_protocol(cls, path): + path = stringify_path(path) + if path.startswith("file://"): + path = path[7:] + elif path.startswith("file:"): + path = path[5:] + elif path.startswith("local://"): + path = path[8:] + elif path.startswith("local:"): + path = path[6:] + + path = make_path_posix(path) + if os.sep != "/": + # This code-path is a stripped down version of + # > drive, path = ntpath.splitdrive(path) + if path[1:2] == ":": + # Absolute drive-letter path, e.g. X:\Windows + # Relative path with drive, e.g. X:Windows + drive, path = path[:2], path[2:] + elif path[:2] == "//": + # UNC drives, e.g. \\server\share or \\?\UNC\server\share + # Device drives, e.g. \\.\device or \\?\device + if (index1 := path.find("/", 2)) == -1 or ( + index2 := path.find("/", index1 + 1) + ) == -1: + drive, path = path, "" + else: + drive, path = path[:index2], path[index2:] + else: + # Relative path, e.g. Windows + drive = "" + + path = path.rstrip("/") or cls.root_marker + return drive + path + + else: + return path.rstrip("/") or cls.root_marker + + def _isfilestore(self): + # Inheriting from DaskFileSystem makes this False (S3, etc. were) + # the original motivation. But we are a posix-like file system. + # See https://github.com/dask/dask/issues/5526 + return True + + def chmod(self, path, mode): + path = stringify_path(path) + return os.chmod(path, mode) + + +def make_path_posix(path): + """Make path generic and absolute for current OS""" + if not isinstance(path, str): + if isinstance(path, (list, set, tuple)): + return type(path)(make_path_posix(p) for p in path) + else: + path = stringify_path(path) + if not isinstance(path, str): + raise TypeError(f"could not convert {path!r} to string") + if os.sep == "/": + # Native posix + if path.startswith("/"): + # most common fast case for posix + return path + elif path.startswith("~"): + return osp.expanduser(path) + elif path.startswith("./"): + path = path[2:] + elif path == ".": + path = "" + return f"{os.getcwd()}/{path}" + else: + # NT handling + if path[0:1] == "/" and path[2:3] == ":": + # path is like "/c:/local/path" + path = path[1:] + if path[1:2] == ":": + # windows full path like "C:\\local\\path" + if len(path) <= 3: + # nt root (something like c:/) + return path[0] + ":/" + path = path.replace("\\", "/") + return path + elif path[0:1] == "~": + return make_path_posix(osp.expanduser(path)) + elif path.startswith(("\\\\", "//")): + # windows UNC/DFS-style paths + return "//" + path[2:].replace("\\", "/") + elif path.startswith(("\\", "/")): + # windows relative path with root + path = path.replace("\\", "/") + return f"{osp.splitdrive(os.getcwd())[0]}{path}" + else: + path = path.replace("\\", "/") + if path.startswith("./"): + path = path[2:] + elif path == ".": + path = "" + return f"{make_path_posix(os.getcwd())}/{path}" + + +def trailing_sep(path): + """Return True if the path ends with a path separator. + + A forward slash is always considered a path separator, even on Operating + Systems that normally use a backslash. + """ + # TODO: if all incoming paths were posix-compliant then separator would + # always be a forward slash, simplifying this function. + # See https://github.com/fsspec/filesystem_spec/pull/1250 + return path.endswith(os.sep) or (os.altsep is not None and path.endswith(os.altsep)) + + +@lru_cache(maxsize=1) +def get_umask(mask: int = 0o666) -> int: + """Get the current umask. + + Follows https://stackoverflow.com/a/44130549 to get the umask. + Temporarily sets the umask to the given value, and then resets it to the + original value. + """ + value = os.umask(mask) + os.umask(value) + return value + + +class LocalFileOpener(io.IOBase): + def __init__( + self, path, mode, autocommit=True, fs=None, compression=None, **kwargs + ): + logger.debug("open file: %s", path) + self.path = path + self.mode = mode + self.fs = fs + self.f = None + self.autocommit = autocommit + self.compression = get_compression(path, compression) + self.blocksize = io.DEFAULT_BUFFER_SIZE + self._open() + + def _open(self): + if self.f is None or self.f.closed: + if self.autocommit or "w" not in self.mode: + self.f = open(self.path, mode=self.mode) + if self.compression: + compress = compr[self.compression] + self.f = compress(self.f, mode=self.mode) + else: + # TODO: check if path is writable? + i, name = tempfile.mkstemp() + os.close(i) # we want normal open and normal buffered file + self.temp = name + self.f = open(name, mode=self.mode) + if "w" not in self.mode: + self.size = self.f.seek(0, 2) + self.f.seek(0) + self.f.size = self.size + + def _fetch_range(self, start, end): + # probably only used by cached FS + if "r" not in self.mode: + raise ValueError + self._open() + self.f.seek(start) + return self.f.read(end - start) + + def __setstate__(self, state): + self.f = None + loc = state.pop("loc", None) + self.__dict__.update(state) + if "r" in state["mode"]: + self.f = None + self._open() + self.f.seek(loc) + + def __getstate__(self): + d = self.__dict__.copy() + d.pop("f") + if "r" in self.mode: + d["loc"] = self.f.tell() + else: + if not self.f.closed: + raise ValueError("Cannot serialise open write-mode local file") + return d + + def commit(self): + if self.autocommit: + raise RuntimeError("Can only commit if not already set to autocommit") + try: + shutil.move(self.temp, self.path) + except PermissionError as e: + # shutil.move raises PermissionError if os.rename + # and the default copy2 fallback with shutil.copystats fail. + # The file should be there nonetheless, but without copied permissions. + # If it doesn't exist, there was no permission to create the file. + if not os.path.exists(self.path): + raise e + else: + # If PermissionError is not raised, permissions can be set. + try: + mask = 0o666 + os.chmod(self.path, mask & ~get_umask(mask)) + except RuntimeError: + pass + + def discard(self): + if self.autocommit: + raise RuntimeError("Cannot discard if set to autocommit") + os.remove(self.temp) + + def readable(self) -> bool: + return True + + def writable(self) -> bool: + return "r" not in self.mode + + def read(self, *args, **kwargs): + return self.f.read(*args, **kwargs) + + def write(self, *args, **kwargs): + return self.f.write(*args, **kwargs) + + def tell(self, *args, **kwargs): + return self.f.tell(*args, **kwargs) + + def seek(self, *args, **kwargs): + return self.f.seek(*args, **kwargs) + + def seekable(self, *args, **kwargs): + return self.f.seekable(*args, **kwargs) + + def readline(self, *args, **kwargs): + return self.f.readline(*args, **kwargs) + + def readlines(self, *args, **kwargs): + return self.f.readlines(*args, **kwargs) + + def close(self): + return self.f.close() + + def truncate(self, size=None) -> int: + return self.f.truncate(size) + + @property + def closed(self): + return self.f.closed + + def fileno(self): + return self.raw.fileno() + + def flush(self) -> None: + self.f.flush() + + def __iter__(self): + return self.f.__iter__() + + def __getattr__(self, item): + return getattr(self.f, item) + + def __enter__(self): + self._incontext = True + return self + + def __exit__(self, exc_type, exc_value, traceback): + self._incontext = False + self.f.__exit__(exc_type, exc_value, traceback) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/memory.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..838876d1f87faa28ed05f02454e210fa534b736e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/memory.py @@ -0,0 +1,311 @@ +from __future__ import annotations + +import logging +from datetime import datetime, timezone +from errno import ENOTEMPTY +from io import BytesIO +from pathlib import PurePath, PureWindowsPath +from typing import Any, ClassVar + +from fsspec import AbstractFileSystem +from fsspec.implementations.local import LocalFileSystem +from fsspec.utils import stringify_path + +logger = logging.getLogger("fsspec.memoryfs") + + +class MemoryFileSystem(AbstractFileSystem): + """A filesystem based on a dict of BytesIO objects + + This is a global filesystem so instances of this class all point to the same + in memory filesystem. + """ + + store: ClassVar[dict[str, Any]] = {} # global, do not overwrite! + pseudo_dirs = [""] # global, do not overwrite! + protocol = "memory" + root_marker = "/" + + @classmethod + def _strip_protocol(cls, path): + if isinstance(path, PurePath): + if isinstance(path, PureWindowsPath): + return LocalFileSystem._strip_protocol(path) + else: + path = stringify_path(path) + + path = path.removeprefix("memory://") + if "::" in path or "://" in path: + return path.rstrip("/") + path = path.lstrip("/").rstrip("/") + return "/" + path if path else "" + + def ls(self, path, detail=True, **kwargs): + path = self._strip_protocol(path) + if path in self.store: + # there is a key with this exact name + if not detail: + return [path] + return [ + { + "name": path, + "size": self.store[path].size, + "type": "file", + "created": self.store[path].created.timestamp(), + } + ] + paths = set() + starter = path + "/" + out = [] + for p2 in tuple(self.store): + if p2.startswith(starter): + if "/" not in p2[len(starter) :]: + # exact child + out.append( + { + "name": p2, + "size": self.store[p2].size, + "type": "file", + "created": self.store[p2].created.timestamp(), + } + ) + elif len(p2) > len(starter): + # implied child directory + ppath = starter + p2[len(starter) :].split("/", 1)[0] + if ppath not in paths: + out = out or [] + out.append( + { + "name": ppath, + "size": 0, + "type": "directory", + } + ) + paths.add(ppath) + for p2 in self.pseudo_dirs: + if p2.startswith(starter): + if "/" not in p2[len(starter) :]: + # exact child pdir + if p2 not in paths: + out.append({"name": p2, "size": 0, "type": "directory"}) + paths.add(p2) + else: + # directory implied by deeper pdir + ppath = starter + p2[len(starter) :].split("/", 1)[0] + if ppath not in paths: + out.append({"name": ppath, "size": 0, "type": "directory"}) + paths.add(ppath) + if not out: + if path in self.pseudo_dirs: + # empty dir + return [] + raise FileNotFoundError(path) + if detail: + return out + return sorted([f["name"] for f in out]) + + def mkdir(self, path, create_parents=True, **kwargs): + path = self._strip_protocol(path) + if path in self.store or path in self.pseudo_dirs: + raise FileExistsError(path) + if self._parent(path).strip("/") and self.isfile(self._parent(path)): + raise NotADirectoryError(self._parent(path)) + if create_parents and self._parent(path).strip("/"): + try: + self.mkdir(self._parent(path), create_parents, **kwargs) + except FileExistsError: + pass + if path and path not in self.pseudo_dirs: + self.pseudo_dirs.append(path) + + def makedirs(self, path, exist_ok=False): + try: + self.mkdir(path, create_parents=True) + except FileExistsError: + if not exist_ok: + raise + + def pipe_file(self, path, value, mode="overwrite", **kwargs): + """Set the bytes of given file + + Avoids copies of the data if possible + """ + mode = "xb" if mode == "create" else "wb" + self.open(path, mode=mode, data=value) + + def rmdir(self, path): + path = self._strip_protocol(path) + if path == "": + # silently avoid deleting FS root + return + if path in self.pseudo_dirs: + if not self.ls(path): + self.pseudo_dirs.remove(path) + else: + raise OSError(ENOTEMPTY, "Directory not empty", path) + else: + raise FileNotFoundError(path) + + def info(self, path, **kwargs): + logger.debug("info: %s", path) + path = self._strip_protocol(path) + if path in self.pseudo_dirs or any( + p.startswith(path + "/") for p in list(self.store) + self.pseudo_dirs + ): + return { + "name": path, + "size": 0, + "type": "directory", + } + elif path in self.store: + filelike = self.store[path] + return { + "name": path, + "size": filelike.size, + "type": "file", + "created": getattr(filelike, "created", None), + } + else: + raise FileNotFoundError(path) + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + path = self._strip_protocol(path) + if "x" in mode and self.exists(path): + raise FileExistsError + if path in self.pseudo_dirs: + raise IsADirectoryError(path) + parent = path + while len(parent) > 1: + parent = self._parent(parent) + if self.isfile(parent): + raise FileExistsError(parent) + if mode in ["rb", "ab", "r+b"]: + if path in self.store: + f = self.store[path] + if mode == "ab": + # position at the end of file + f.seek(0, 2) + else: + # position at the beginning of file + f.seek(0) + return f + else: + raise FileNotFoundError(path) + elif mode in {"wb", "xb"}: + if mode == "xb" and self.exists(path): + raise FileExistsError + m = MemoryFile(self, path, kwargs.get("data")) + if not self._intrans: + m.commit() + return m + else: + name = self.__class__.__name__ + raise ValueError(f"unsupported file mode for {name}: {mode!r}") + + def cp_file(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1) + path2 = self._strip_protocol(path2) + if self.isfile(path1): + self.store[path2] = MemoryFile( + self, path2, self.store[path1].getvalue() + ) # implicit copy + elif self.isdir(path1): + if path2 not in self.pseudo_dirs: + self.pseudo_dirs.append(path2) + else: + raise FileNotFoundError(path1) + + def cat_file(self, path, start=None, end=None, **kwargs): + logger.debug("cat: %s", path) + path = self._strip_protocol(path) + try: + return bytes(self.store[path].getbuffer()[start:end]) + except KeyError as e: + raise FileNotFoundError(path) from e + + def _rm(self, path): + path = self._strip_protocol(path) + try: + del self.store[path] + except KeyError as e: + raise FileNotFoundError(path) from e + + def modified(self, path): + path = self._strip_protocol(path) + try: + return self.store[path].modified + except KeyError as e: + raise FileNotFoundError(path) from e + + def created(self, path): + path = self._strip_protocol(path) + try: + return self.store[path].created + except KeyError as e: + raise FileNotFoundError(path) from e + + def isfile(self, path): + path = self._strip_protocol(path) + return path in self.store + + def rm(self, path, recursive=False, maxdepth=None): + if isinstance(path, str): + path = self._strip_protocol(path) + else: + path = [self._strip_protocol(p) for p in path] + paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth) + for p in reversed(paths): + if self.isfile(p): + self.rm_file(p) + # If the expanded path doesn't exist, it is only because the expanded + # path was a directory that does not exist in self.pseudo_dirs. This + # is possible if you directly create files without making the + # directories first. + elif not self.exists(p): + continue + else: + self.rmdir(p) + + +class MemoryFile(BytesIO): + """A BytesIO which can't close and works as a context manager + + Can initialise with data. Each path should only be active once at any moment. + + No need to provide fs, path if auto-committing (default) + """ + + def __init__(self, fs=None, path=None, data=None): + logger.debug("open file %s", path) + self.fs = fs + self.path = path + self.created = datetime.now(tz=timezone.utc) + self.modified = datetime.now(tz=timezone.utc) + if data: + super().__init__(data) + self.seek(0) + + @property + def size(self): + return self.getbuffer().nbytes + + def __enter__(self): + return self + + def close(self): + pass + + def discard(self): + pass + + def commit(self): + self.fs.store[self.path] = self + self.modified = datetime.now(tz=timezone.utc) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/reference.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..66be6ec7ca1cbebc5d80a328f7ed78becaeb0a37 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/reference.py @@ -0,0 +1,1305 @@ +import base64 +import collections +import io +import itertools +import logging +import math +import os +from functools import lru_cache +from itertools import chain +from typing import TYPE_CHECKING, Literal + +import fsspec.core +from fsspec.spec import AbstractBufferedFile + +try: + import ujson as json +except ImportError: + if not TYPE_CHECKING: + import json + +from fsspec.asyn import AsyncFileSystem +from fsspec.callbacks import DEFAULT_CALLBACK +from fsspec.core import filesystem, open, split_protocol +from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper +from fsspec.utils import isfilelike, merge_offset_ranges, other_paths + +logger = logging.getLogger("fsspec.reference") + + +class ReferenceNotReachable(RuntimeError): + def __init__(self, reference, target, *args): + super().__init__(*args) + self.reference = reference + self.target = target + + def __str__(self): + return f'Reference "{self.reference}" failed to fetch target {self.target}' + + +def _first(d): + return next(iter(d.values())) + + +def _prot_in_references(path, references): + ref = references.get(path) + if isinstance(ref, (list, tuple)) and isinstance(ref[0], str): + return split_protocol(ref[0])[0] if ref[0] else ref[0] + + +def _protocol_groups(paths, references): + if isinstance(paths, str): + return {_prot_in_references(paths, references): [paths]} + out = {} + for path in paths: + protocol = _prot_in_references(path, references) + out.setdefault(protocol, []).append(path) + return out + + +class RefsValuesView(collections.abc.ValuesView): + def __iter__(self): + for val in self._mapping.zmetadata.values(): + yield json.dumps(val).encode() + yield from self._mapping._items.values() + for field in self._mapping.listdir(): + chunk_sizes = self._mapping._get_chunk_sizes(field) + if len(chunk_sizes) == 0: + yield self._mapping[field + "/0"] + continue + yield from self._mapping._generate_all_records(field) + + +class RefsItemsView(collections.abc.ItemsView): + def __iter__(self): + return zip(self._mapping.keys(), self._mapping.values()) + + +def ravel_multi_index(idx, sizes): + val = 0 + mult = 1 + for i, s in zip(idx[::-1], sizes[::-1]): + val += i * mult + mult *= s + return val + + +class LazyReferenceMapper(collections.abc.MutableMapping): + """This interface can be used to read/write references from Parquet stores. + It is not intended for other types of references. + It can be used with Kerchunk's MultiZarrToZarr method to combine + references into a parquet store. + Examples of this use-case can be found here: + https://fsspec.github.io/kerchunk/advanced.html?highlight=parquet#parquet-storage""" + + # import is class level to prevent numpy dep requirement for fsspec + @property + def np(self): + import numpy as np + + return np + + @property + def pd(self): + import pandas as pd + + return pd + + def __init__( + self, + root, + fs=None, + out_root=None, + cache_size=128, + categorical_threshold=10, + engine: Literal["fastparquet", "pyarrow"] = "fastparquet", + ): + """ + + This instance will be writable, storing changes in memory until full partitions + are accumulated or .flush() is called. + + To create an empty lazy store, use .create() + + Parameters + ---------- + root : str + Root of parquet store + fs : fsspec.AbstractFileSystem + fsspec filesystem object, default is local filesystem. + cache_size : int, default=128 + Maximum size of LRU cache, where cache_size*record_size denotes + the total number of references that can be loaded in memory at once. + categorical_threshold : int + Encode urls as pandas.Categorical to reduce memory footprint if the ratio + of the number of unique urls to total number of refs for each variable + is greater than or equal to this number. (default 10) + engine: Literal["fastparquet","pyarrow"] + Engine choice for reading parquet files. (default is "fastparquet") + """ + + self.root = root + self.chunk_sizes = {} + self.cat_thresh = categorical_threshold + self.engine = engine + self.cache_size = cache_size + self.url = self.root + "/{field}/refs.{record}.parq" + # TODO: derive fs from `root` + self.fs = fsspec.filesystem("file") if fs is None else fs + self.out_root = self.fs.unstrip_protocol(out_root or self.root) + + from importlib.util import find_spec + + if self.engine == "pyarrow" and find_spec("pyarrow") is None: + raise ImportError("engine choice `pyarrow` is not installed.") + + def __getattr__(self, item): + if item in ("_items", "record_size", "zmetadata"): + self.setup() + # avoid possible recursion if setup fails somehow + return self.__dict__[item] + raise AttributeError(item) + + def setup(self): + self._items = {} + self._items[".zmetadata"] = self.fs.cat_file( + "/".join([self.root, ".zmetadata"]) + ) + met = json.loads(self._items[".zmetadata"]) + self.record_size = met["record_size"] + self.zmetadata = met["metadata"] + + # Define function to open and decompress refs + @lru_cache(maxsize=self.cache_size) + def open_refs(field, record): + """cached parquet file loader""" + path = self.url.format(field=field, record=record) + data = io.BytesIO(self.fs.cat_file(path)) + try: + df = self.pd.read_parquet(data, engine=self.engine) + refs = {c: df[c].to_numpy() for c in df.columns} + except OSError: + refs = None + return refs + + self.open_refs = open_refs + + @staticmethod + def create(root, storage_options=None, fs=None, record_size=10000, **kwargs): + """Make empty parquet reference set + + First deletes the contents of the given directory, if it exists. + + Parameters + ---------- + root: str + Directory to contain the output; will be created + storage_options: dict | None + For making the filesystem to use for writing is fs is None + fs: FileSystem | None + Filesystem for writing + record_size: int + Number of references per parquet file + kwargs: passed to __init__ + + Returns + ------- + LazyReferenceMapper instance + """ + met = {"metadata": {}, "record_size": record_size} + if fs is None: + fs, root = fsspec.core.url_to_fs(root, **(storage_options or {})) + if fs.exists(root): + fs.rm(root, recursive=True) + fs.makedirs(root, exist_ok=True) + fs.pipe("/".join([root, ".zmetadata"]), json.dumps(met).encode()) + return LazyReferenceMapper(root, fs, **kwargs) + + @lru_cache() + def listdir(self): + """List top-level directories""" + dirs = (p.rsplit("/", 1)[0] for p in self.zmetadata if not p.startswith(".z")) + return set(dirs) + + def ls(self, path="", detail=True): + """Shortcut file listings""" + path = path.rstrip("/") + pathdash = path + "/" if path else "" + dirnames = self.listdir() + dirs = [ + d + for d in dirnames + if d.startswith(pathdash) and "/" not in d.lstrip(pathdash) + ] + if dirs: + others = { + f + for f in chain( + [".zmetadata"], + (name for name in self.zmetadata), + (name for name in self._items), + ) + if f.startswith(pathdash) and "/" not in f.lstrip(pathdash) + } + if detail is False: + others.update(dirs) + return sorted(others) + dirinfo = [{"name": name, "type": "directory", "size": 0} for name in dirs] + fileinfo = [ + { + "name": name, + "type": "file", + "size": len( + json.dumps(self.zmetadata[name]) + if name in self.zmetadata + else self._items[name] + ), + } + for name in others + ] + return sorted(dirinfo + fileinfo, key=lambda s: s["name"]) + field = path + others = set( + [name for name in self.zmetadata if name.startswith(f"{path}/")] + + [name for name in self._items if name.startswith(f"{path}/")] + ) + fileinfo = [ + { + "name": name, + "type": "file", + "size": len( + json.dumps(self.zmetadata[name]) + if name in self.zmetadata + else self._items[name] + ), + } + for name in others + ] + keys = self._keys_in_field(field) + + if detail is False: + return list(others) + list(keys) + recs = self._generate_all_records(field) + recinfo = [ + {"name": name, "type": "file", "size": rec[-1]} + for name, rec in zip(keys, recs) + if rec[0] # filters out path==None, deleted/missing + ] + return fileinfo + recinfo + + def _load_one_key(self, key): + """Get the reference for one key + + Returns bytes, one-element list or three-element list. + """ + if key in self._items: + return self._items[key] + elif key in self.zmetadata: + return json.dumps(self.zmetadata[key]).encode() + elif "/" not in key or self._is_meta(key): + raise KeyError(key) + field, _ = key.rsplit("/", 1) + record, ri, chunk_size = self._key_to_record(key) + maybe = self._items.get((field, record), {}).get(ri, False) + if maybe is None: + # explicitly deleted + raise KeyError + elif maybe: + return maybe + elif chunk_size == 0: + return b"" + + # Chunk keys can be loaded from row group and cached in LRU cache + try: + refs = self.open_refs(field, record) + except (ValueError, TypeError, FileNotFoundError) as exc: + raise KeyError(key) from exc + columns = ["path", "offset", "size", "raw"] + selection = [refs[c][ri] if c in refs else None for c in columns] + raw = selection[-1] + if raw is not None: + return raw + if selection[0] is None: + raise KeyError("This reference does not exist or has been deleted") + if selection[1:3] == [0, 0]: + # URL only + return selection[:1] + # URL, offset, size + return selection[:3] + + @lru_cache(4096) + def _key_to_record(self, key): + """Details needed to construct a reference for one key""" + field, chunk = key.rsplit("/", 1) + chunk_sizes = self._get_chunk_sizes(field) + if len(chunk_sizes) == 0: + return 0, 0, 0 + chunk_idx = [int(c) for c in chunk.split(".")] + chunk_number = ravel_multi_index(chunk_idx, chunk_sizes) + record = chunk_number // self.record_size + ri = chunk_number % self.record_size + return record, ri, len(chunk_sizes) + + def _get_chunk_sizes(self, field): + """The number of chunks along each axis for a given field""" + if field not in self.chunk_sizes: + zarray = self.zmetadata[f"{field}/.zarray"] + size_ratio = [ + math.ceil(s / c) for s, c in zip(zarray["shape"], zarray["chunks"]) + ] + self.chunk_sizes[field] = size_ratio or [1] + return self.chunk_sizes[field] + + def _generate_record(self, field, record): + """The references for a given parquet file of a given field""" + refs = self.open_refs(field, record) + it = iter(zip(*refs.values())) + if len(refs) == 3: + # All urls + return (list(t) for t in it) + elif len(refs) == 1: + # All raws + return refs["raw"] + else: + # Mix of urls and raws + return (list(t[:3]) if not t[3] else t[3] for t in it) + + def _generate_all_records(self, field): + """Load all the references within a field by iterating over the parquet files""" + nrec = 1 + for ch in self._get_chunk_sizes(field): + nrec *= ch + nrec = math.ceil(nrec / self.record_size) + for record in range(nrec): + yield from self._generate_record(field, record) + + def values(self): + return RefsValuesView(self) + + def items(self): + return RefsItemsView(self) + + def __hash__(self): + return id(self) + + def __getitem__(self, key): + return self._load_one_key(key) + + def __setitem__(self, key, value): + if "/" in key and not self._is_meta(key): + field, chunk = key.rsplit("/", 1) + record, i, _ = self._key_to_record(key) + subdict = self._items.setdefault((field, record), {}) + subdict[i] = value + if len(subdict) == self.record_size: + self.write(field, record) + else: + # metadata or top-level + if hasattr(value, "to_bytes"): + val = value.to_bytes().decode() + elif isinstance(value, bytes): + val = value.decode() + else: + val = value + self._items[key] = val + new_value = json.loads(val) + self.zmetadata[key] = {**self.zmetadata.get(key, {}), **new_value} + + @staticmethod + def _is_meta(key): + return key.startswith(".z") or "/.z" in key + + def __delitem__(self, key): + if key in self._items: + del self._items[key] + elif key in self.zmetadata: + del self.zmetadata[key] + else: + if "/" in key and not self._is_meta(key): + field, _ = key.rsplit("/", 1) + record, i, _ = self._key_to_record(key) + subdict = self._items.setdefault((field, record), {}) + subdict[i] = None + if len(subdict) == self.record_size: + self.write(field, record) + else: + # metadata or top-level + self._items[key] = None + + def write(self, field, record, base_url=None, storage_options=None): + # extra requirements if writing + import kerchunk.df + import numpy as np + import pandas as pd + + partition = self._items[(field, record)] + original = False + if len(partition) < self.record_size: + try: + original = self.open_refs(field, record) + except OSError: + pass + + if original: + paths = original["path"] + offsets = original["offset"] + sizes = original["size"] + raws = original["raw"] + else: + paths = np.full(self.record_size, np.nan, dtype="O") + offsets = np.zeros(self.record_size, dtype="int64") + sizes = np.zeros(self.record_size, dtype="int64") + raws = np.full(self.record_size, np.nan, dtype="O") + for j, data in partition.items(): + if isinstance(data, list): + if ( + str(paths.dtype) == "category" + and data[0] not in paths.dtype.categories + ): + paths = paths.add_categories(data[0]) + paths[j] = data[0] + if len(data) > 1: + offsets[j] = data[1] + sizes[j] = data[2] + elif data is None: + # delete + paths[j] = None + offsets[j] = 0 + sizes[j] = 0 + raws[j] = None + else: + # this is the only call into kerchunk, could remove + raws[j] = kerchunk.df._proc_raw(data) + # TODO: only save needed columns + df = pd.DataFrame( + { + "path": paths, + "offset": offsets, + "size": sizes, + "raw": raws, + }, + copy=False, + ) + if df.path.count() / (df.path.nunique() or 1) > self.cat_thresh: + df["path"] = df["path"].astype("category") + object_encoding = {"raw": "bytes", "path": "utf8"} + has_nulls = ["path", "raw"] + + fn = f"{base_url or self.out_root}/{field}/refs.{record}.parq" + self.fs.mkdirs(f"{base_url or self.out_root}/{field}", exist_ok=True) + + if self.engine == "pyarrow": + df_backend_kwargs = {"write_statistics": False} + elif self.engine == "fastparquet": + df_backend_kwargs = { + "stats": False, + "object_encoding": object_encoding, + "has_nulls": has_nulls, + } + else: + raise NotImplementedError(f"{self.engine} not supported") + df.to_parquet( + fn, + engine=self.engine, + storage_options=storage_options + or getattr(self.fs, "storage_options", None), + compression="zstd", + index=False, + **df_backend_kwargs, + ) + + partition.clear() + self._items.pop((field, record)) + + def flush(self, base_url=None, storage_options=None): + """Output any modified or deleted keys + + Parameters + ---------- + base_url: str + Location of the output + """ + + # write what we have so far and clear sub chunks + for thing in list(self._items): + if isinstance(thing, tuple): + field, record = thing + self.write( + field, + record, + base_url=base_url, + storage_options=storage_options, + ) + + # gather .zmetadata from self._items and write that too + for k in list(self._items): + if k != ".zmetadata" and ".z" in k: + self.zmetadata[k] = json.loads(self._items.pop(k)) + met = {"metadata": self.zmetadata, "record_size": self.record_size} + self._items.clear() + self._items[".zmetadata"] = json.dumps(met).encode() + self.fs.pipe( + "/".join([base_url or self.out_root, ".zmetadata"]), + self._items[".zmetadata"], + ) + + # TODO: only clear those that we wrote to? + self.open_refs.cache_clear() + + def __len__(self): + # Caveat: This counts expected references, not actual - but is fast + count = 0 + for field in self.listdir(): + if field.startswith("."): + count += 1 + else: + count += math.prod(self._get_chunk_sizes(field)) + count += len(self.zmetadata) # all metadata keys + # any other files not in reference partitions + count += sum(1 for _ in self._items if not isinstance(_, tuple)) + return count + + def __iter__(self): + # Caveat: returns only existing keys, so the number of these does not + # match len(self) + metas = set(self.zmetadata) + metas.update(self._items) + for bit in metas: + if isinstance(bit, str): + yield bit + for field in self.listdir(): + for k in self._keys_in_field(field): + if k in self: + yield k + + def __contains__(self, item): + try: + self._load_one_key(item) + return True + except KeyError: + return False + + def _keys_in_field(self, field): + """List key names in given field + + Produces strings like "field/x.y" appropriate from the chunking of the array + """ + chunk_sizes = self._get_chunk_sizes(field) + if len(chunk_sizes) == 0: + yield field + "/0" + return + inds = itertools.product(*(range(i) for i in chunk_sizes)) + for ind in inds: + yield field + "/" + ".".join([str(c) for c in ind]) + + +class ReferenceFileSystem(AsyncFileSystem): + """View byte ranges of some other file as a file system + Initial version: single file system target, which must support + async, and must allow start and end args in _cat_file. Later versions + may allow multiple arbitrary URLs for the targets. + This FileSystem is read-only. It is designed to be used with async + targets (for now). We do not get original file details from the target FS. + Configuration is by passing a dict of references at init, or a URL to + a JSON file containing the same; this dict + can also contain concrete data for some set of paths. + Reference dict format: + {path0: bytes_data, path1: (target_url, offset, size)} + https://github.com/fsspec/kerchunk/blob/main/README.md + """ + + protocol = "reference" + cachable = False + + def __init__( + self, + fo, + target=None, + ref_storage_args=None, + target_protocol=None, + target_options=None, + remote_protocol=None, + remote_options=None, + fs=None, + template_overrides=None, + simple_templates=True, + max_gap=64_000, + max_block=256_000_000, + cache_size=128, + **kwargs, + ): + """ + Parameters + ---------- + fo : dict or str + The set of references to use for this instance, with a structure as above. + If str referencing a JSON file, will use fsspec.open, in conjunction + with target_options and target_protocol to open and parse JSON at this + location. If a directory, then assume references are a set of parquet + files to be loaded lazily. + target : str + For any references having target_url as None, this is the default file + target to use + ref_storage_args : dict + If references is a str, use these kwargs for loading the JSON file. + Deprecated: use target_options instead. + target_protocol : str + Used for loading the reference file, if it is a path. If None, protocol + will be derived from the given path + target_options : dict + Extra FS options for loading the reference file ``fo``, if given as a path + remote_protocol : str + The protocol of the filesystem on which the references will be evaluated + (unless fs is provided). If not given, will be derived from the first + URL that has a protocol in the templates or in the references, in that + order. + remote_options : dict + kwargs to go with remote_protocol + fs : AbstractFileSystem | dict(str, (AbstractFileSystem | dict)) + Directly provide a file system(s): + - a single filesystem instance + - a dict of protocol:filesystem, where each value is either a filesystem + instance, or a dict of kwargs that can be used to create in + instance for the given protocol + + If this is given, remote_options and remote_protocol are ignored. + template_overrides : dict + Swap out any templates in the references file with these - useful for + testing. + simple_templates: bool + Whether templates can be processed with simple replace (True) or if + jinja is needed (False, much slower). All reference sets produced by + ``kerchunk`` are simple in this sense, but the spec allows for complex. + max_gap, max_block: int + For merging multiple concurrent requests to the same remote file. + Neighboring byte ranges will only be merged when their + inter-range gap is <= ``max_gap``. Default is 64KB. Set to 0 + to only merge when it requires no extra bytes. Pass a negative + number to disable merging, appropriate for local target files. + Neighboring byte ranges will only be merged when the size of + the aggregated range is <= ``max_block``. Default is 256MB. + cache_size : int + Maximum size of LRU cache, where cache_size*record_size denotes + the total number of references that can be loaded in memory at once. + Only used for lazily loaded references. + kwargs : passed to parent class + """ + super().__init__(**kwargs) + self.target = target + self.template_overrides = template_overrides + self.simple_templates = simple_templates + self.templates = {} + self.fss = {} + self._dircache = {} + self.max_gap = max_gap + self.max_block = max_block + if isinstance(fo, str): + dic = dict( + **(ref_storage_args or target_options or {}), protocol=target_protocol + ) + ref_fs, fo2 = fsspec.core.url_to_fs(fo, **dic) + if ref_fs.isfile(fo2): + # text JSON + with fsspec.open(fo, "rb", **dic) as f: + logger.info("Read reference from URL %s", fo) + text = json.load(f) + self._process_references(text, template_overrides) + else: + # Lazy parquet refs + logger.info("Open lazy reference dict from URL %s", fo) + self.references = LazyReferenceMapper( + fo2, + fs=ref_fs, + cache_size=cache_size, + ) + else: + # dictionaries + self._process_references(fo, template_overrides) + if isinstance(fs, dict): + self.fss = { + k: ( + fsspec.filesystem(k.split(":", 1)[0], **opts) + if isinstance(opts, dict) + else opts + ) + for k, opts in fs.items() + } + if None not in self.fss: + self.fss[None] = filesystem("file") + return + if fs is not None: + # single remote FS + remote_protocol = ( + fs.protocol[0] if isinstance(fs.protocol, tuple) else fs.protocol + ) + self.fss[remote_protocol] = fs + + if remote_protocol is None: + # get single protocol from any templates + for ref in self.templates.values(): + if callable(ref): + ref = ref() + protocol, _ = fsspec.core.split_protocol(ref) + if protocol and protocol not in self.fss: + fs = filesystem(protocol, **(remote_options or {})) + self.fss[protocol] = fs + if remote_protocol is None: + # get single protocol from references + # TODO: warning here, since this can be very expensive? + for ref in self.references.values(): + if callable(ref): + ref = ref() + if isinstance(ref, list) and ref[0]: + protocol, _ = fsspec.core.split_protocol(ref[0]) + if protocol not in self.fss: + fs = filesystem(protocol, **(remote_options or {})) + self.fss[protocol] = fs + # only use first remote URL + break + + if remote_protocol and remote_protocol not in self.fss: + fs = filesystem(remote_protocol, **(remote_options or {})) + self.fss[remote_protocol] = fs + + self.fss[None] = fs or filesystem("file") # default one + # Wrap any non-async filesystems to ensure async methods are available below + for k, f in self.fss.items(): + if not f.async_impl: + self.fss[k] = AsyncFileSystemWrapper(f, asynchronous=self.asynchronous) + elif self.asynchronous ^ f.asynchronous: + raise ValueError( + "Reference-FS's target filesystem must have same value " + "of asynchronous" + ) + + def _cat_common(self, path, start=None, end=None): + path = self._strip_protocol(path) + logger.debug(f"cat: {path}") + try: + part = self.references[path] + except KeyError as exc: + raise FileNotFoundError(path) from exc + if isinstance(part, str): + part = part.encode() + if hasattr(part, "to_bytes"): + part = part.to_bytes() + if isinstance(part, bytes): + logger.debug(f"Reference: {path}, type bytes") + if part.startswith(b"base64:"): + part = base64.b64decode(part[7:]) + return part, None, None + + if len(part) == 1: + logger.debug(f"Reference: {path}, whole file => {part}") + url = part[0] + start1, end1 = start, end + else: + url, start0, size = part + logger.debug(f"Reference: {path} => {url}, offset {start0}, size {size}") + end0 = start0 + size + + if start is not None: + if start >= 0: + start1 = start0 + start + else: + start1 = end0 + start + else: + start1 = start0 + if end is not None: + if end >= 0: + end1 = start0 + end + else: + end1 = end0 + end + else: + end1 = end0 + if url is None: + url = self.target + return url, start1, end1 + + async def _cat_file(self, path, start=None, end=None, **kwargs): + part_or_url, start0, end0 = self._cat_common(path, start=start, end=end) + if isinstance(part_or_url, bytes): + return part_or_url[start:end] + protocol, _ = split_protocol(part_or_url) + try: + return await self.fss[protocol]._cat_file( + part_or_url, start=start0, end=end0 + ) + except Exception as e: + raise ReferenceNotReachable(path, part_or_url) from e + + def cat_file(self, path, start=None, end=None, **kwargs): + part_or_url, start0, end0 = self._cat_common(path, start=start, end=end) + if isinstance(part_or_url, bytes): + return part_or_url[start:end] + protocol, _ = split_protocol(part_or_url) + try: + return self.fss[protocol].cat_file(part_or_url, start=start0, end=end0) + except Exception as e: + raise ReferenceNotReachable(path, part_or_url) from e + + def pipe_file(self, path, value, **_): + """Temporarily add binary data or reference as a file""" + self.references[path] = value + + async def _get_file(self, rpath, lpath, **kwargs): + if self.isdir(rpath): + return os.makedirs(lpath, exist_ok=True) + data = await self._cat_file(rpath) + with open(lpath, "wb") as f: + f.write(data) + + def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, **kwargs): + if self.isdir(rpath): + return os.makedirs(lpath, exist_ok=True) + data = self.cat_file(rpath, **kwargs) + callback.set_size(len(data)) + if isfilelike(lpath): + lpath.write(data) + else: + with open(lpath, "wb") as f: + f.write(data) + callback.absolute_update(len(data)) + + def get(self, rpath, lpath, recursive=False, **kwargs): + if recursive: + # trigger directory build + self.ls("") + rpath = self.expand_path(rpath, recursive=recursive) + fs = fsspec.filesystem("file", auto_mkdir=True) + targets = other_paths(rpath, lpath) + if recursive: + data = self.cat([r for r in rpath if not self.isdir(r)]) + else: + data = self.cat(rpath) + for remote, local in zip(rpath, targets): + if remote in data: + fs.pipe_file(local, data[remote]) + + def cat(self, path, recursive=False, on_error="raise", **kwargs): + if isinstance(path, str) and recursive: + raise NotImplementedError + if isinstance(path, list) and (recursive or any("*" in p for p in path)): + raise NotImplementedError + # TODO: if references is lazy, pre-fetch all paths in batch before access + proto_dict = _protocol_groups(path, self.references) + out = {} + for proto, paths in proto_dict.items(): + fs = self.fss[proto] + urls, starts, ends, valid_paths = [], [], [], [] + for p in paths: + # find references or label not-found. Early exit if any not + # found and on_error is "raise" + try: + u, s, e = self._cat_common(p) + if not isinstance(u, (bytes, str)): + # nan/None from parquet + continue + except FileNotFoundError as err: + if on_error == "raise": + raise + if on_error != "omit": + out[p] = err + else: + urls.append(u) + starts.append(s) + ends.append(e) + valid_paths.append(p) + + # process references into form for merging + urls2 = [] + starts2 = [] + ends2 = [] + paths2 = [] + whole_files = set() + for u, s, e, p in zip(urls, starts, ends, valid_paths): + if isinstance(u, bytes): + # data + out[p] = u + elif s is None: + # whole file - limits are None, None, but no further + # entries take for this file + whole_files.add(u) + urls2.append(u) + starts2.append(s) + ends2.append(e) + paths2.append(p) + for u, s, e, p in zip(urls, starts, ends, valid_paths): + # second run to account for files that are to be loaded whole + if s is not None and u not in whole_files: + urls2.append(u) + starts2.append(s) + ends2.append(e) + paths2.append(p) + + # merge and fetch consolidated ranges + new_paths, new_starts, new_ends = merge_offset_ranges( + list(urls2), + list(starts2), + list(ends2), + sort=True, + max_gap=self.max_gap, + max_block=self.max_block, + ) + bytes_out = fs.cat_ranges(new_paths, new_starts, new_ends) + + # unbundle from merged bytes - simple approach + for u, s, e, p in zip(urls, starts, ends, valid_paths): + if p in out: + continue # was bytes, already handled + for np, ns, ne, b in zip(new_paths, new_starts, new_ends, bytes_out): + if np == u and (ns is None or ne is None): + if isinstance(b, Exception): + out[p] = b + else: + out[p] = b[s:e] + elif np == u and s >= ns and e <= ne: + if isinstance(b, Exception): + out[p] = b + else: + out[p] = b[s - ns : (e - ne) or None] + + for k, v in out.copy().items(): + # these were valid references, but fetch failed, so transform exc + if isinstance(v, Exception) and k in self.references: + ex = out[k] + new_ex = ReferenceNotReachable(k, self.references[k]) + new_ex.__cause__ = ex + if on_error == "raise": + raise new_ex + elif on_error != "omit": + out[k] = new_ex + + if len(out) == 1 and isinstance(path, str) and "*" not in path: + return _first(out) + return out + + def _process_references(self, references, template_overrides=None): + vers = references.get("version", None) + if vers is None: + self._process_references0(references) + elif vers == 1: + self._process_references1(references, template_overrides=template_overrides) + else: + raise ValueError(f"Unknown reference spec version: {vers}") + # TODO: we make dircache by iterating over all entries, but for Spec >= 1, + # can replace with programmatic. Is it even needed for mapper interface? + + def _process_references0(self, references): + """Make reference dict for Spec Version 0""" + if isinstance(references, dict): + # do not do this for lazy/parquet backend, which will not make dicts, + # but must remain writable in the original object + references = { + key: json.dumps(val) if isinstance(val, dict) else val + for key, val in references.items() + } + self.references = references + + def _process_references1(self, references, template_overrides=None): + if not self.simple_templates or self.templates: + import jinja2 + self.references = {} + self._process_templates(references.get("templates", {})) + + @lru_cache(1000) + def _render_jinja(u): + return jinja2.Template(u).render(**self.templates) + + for k, v in references.get("refs", {}).items(): + if isinstance(v, str): + if v.startswith("base64:"): + self.references[k] = base64.b64decode(v[7:]) + self.references[k] = v + elif isinstance(v, dict): + self.references[k] = json.dumps(v) + elif self.templates: + u = v[0] + if "{{" in u: + if self.simple_templates: + u = ( + u.replace("{{", "{") + .replace("}}", "}") + .format(**self.templates) + ) + else: + u = _render_jinja(u) + self.references[k] = [u] if len(v) == 1 else [u, v[1], v[2]] + else: + self.references[k] = v + self.references.update(self._process_gen(references.get("gen", []))) + + def _process_templates(self, tmp): + self.templates = {} + if self.template_overrides is not None: + tmp.update(self.template_overrides) + for k, v in tmp.items(): + if "{{" in v: + import jinja2 + + self.templates[k] = lambda temp=v, **kwargs: jinja2.Template( + temp + ).render(**kwargs) + else: + self.templates[k] = v + + def _process_gen(self, gens): + out = {} + for gen in gens: + dimension = { + k: ( + v + if isinstance(v, list) + else range(v.get("start", 0), v["stop"], v.get("step", 1)) + ) + for k, v in gen["dimensions"].items() + } + products = ( + dict(zip(dimension.keys(), values)) + for values in itertools.product(*dimension.values()) + ) + for pr in products: + import jinja2 + + key = jinja2.Template(gen["key"]).render(**pr, **self.templates) + url = jinja2.Template(gen["url"]).render(**pr, **self.templates) + if ("offset" in gen) and ("length" in gen): + offset = int( + jinja2.Template(gen["offset"]).render(**pr, **self.templates) + ) + length = int( + jinja2.Template(gen["length"]).render(**pr, **self.templates) + ) + out[key] = [url, offset, length] + elif ("offset" in gen) ^ ("length" in gen): + raise ValueError( + "Both 'offset' and 'length' are required for a " + "reference generator entry if either is provided." + ) + else: + out[key] = [url] + return out + + def _dircache_from_items(self): + self.dircache = {"": []} + it = self.references.items() + for path, part in it: + if isinstance(part, (bytes, str)) or hasattr(part, "to_bytes"): + size = len(part) + elif len(part) == 1: + size = None + else: + _, _, size = part + par = path.rsplit("/", 1)[0] if "/" in path else "" + par0 = par + subdirs = [par0] + while par0 and par0 not in self.dircache: + # collect parent directories + par0 = self._parent(par0) + subdirs.append(par0) + + subdirs.reverse() + for parent, child in zip(subdirs, subdirs[1:]): + # register newly discovered directories + assert child not in self.dircache + assert parent in self.dircache + self.dircache[parent].append( + {"name": child, "type": "directory", "size": 0} + ) + self.dircache[child] = [] + + self.dircache[par].append({"name": path, "type": "file", "size": size}) + + def _open(self, path, mode="rb", block_size=None, cache_options=None, **kwargs): + part_or_url, start0, end0 = self._cat_common(path) + # This logic is kept outside `ReferenceFile` to avoid unnecessary redirection. + # That does mean `_cat_common` gets called twice if it eventually reaches `ReferenceFile`. + if isinstance(part_or_url, bytes): + return io.BytesIO(part_or_url[start0:end0]) + + protocol, _ = split_protocol(part_or_url) + if start0 is None and end0 is None: + return self.fss[protocol]._open( + part_or_url, + mode, + block_size=block_size, + cache_options=cache_options, + **kwargs, + ) + + return ReferenceFile( + self, + path, + mode, + block_size=block_size, + cache_options=cache_options, + **kwargs, + ) + + def ls(self, path, detail=True, **kwargs): + logger.debug("list %s", path) + path = self._strip_protocol(path) + if isinstance(self.references, LazyReferenceMapper): + try: + return self.references.ls(path, detail) + except KeyError: + pass + raise FileNotFoundError(f"'{path}' is not a known key") + if not self.dircache: + self._dircache_from_items() + out = self._ls_from_cache(path) + if out is None: + raise FileNotFoundError(path) + if detail: + return out + return [o["name"] for o in out] + + def exists(self, path, **kwargs): # overwrite auto-sync version + return self.isdir(path) or self.isfile(path) + + def isdir(self, path): # overwrite auto-sync version + if self.dircache: + return path in self.dircache + elif isinstance(self.references, LazyReferenceMapper): + return path in self.references.listdir() + else: + # this may be faster than building dircache for single calls, but + # by looping will be slow for many calls; could cache it? + return any(_.startswith(f"{path}/") for _ in self.references) + + def isfile(self, path): # overwrite auto-sync version + return path in self.references + + async def _ls(self, path, detail=True, **kwargs): # calls fast sync code + return self.ls(path, detail, **kwargs) + + def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs): + if withdirs: + return super().find( + path, maxdepth=maxdepth, withdirs=withdirs, detail=detail, **kwargs + ) + if path: + path = self._strip_protocol(path) + r = sorted(k for k in self.references if k.startswith(path)) + else: + r = sorted(self.references) + if detail: + if not self.dircache: + self._dircache_from_items() + return {k: self._ls_from_cache(k)[0] for k in r} + else: + return r + + def info(self, path, **kwargs): + out = self.references.get(path) + if out is not None: + if isinstance(out, (str, bytes)): + # decode base64 here + return {"name": path, "type": "file", "size": len(out)} + elif len(out) > 1: + return {"name": path, "type": "file", "size": out[2]} + else: + out0 = [{"name": path, "type": "file", "size": None}] + else: + out = self.ls(path, True) + out0 = [o for o in out if o["name"] == path] + if not out0: + return {"name": path, "type": "directory", "size": 0} + if out0[0]["size"] is None: + # if this is a whole remote file, update size using remote FS + prot, _ = split_protocol(self.references[path][0]) + out0[0]["size"] = self.fss[prot].size(self.references[path][0]) + return out0[0] + + async def _info(self, path, **kwargs): # calls fast sync code + return self.info(path) + + async def _rm_file(self, path, **kwargs): + self.references.pop( + path, None + ) # ignores FileNotFound, just as well for directories + self.dircache.clear() # this is a bit heavy handed + + async def _pipe_file(self, path, data, mode="overwrite", **kwargs): + if mode == "create" and self.exists(path): + raise FileExistsError + # can be str or bytes + self.references[path] = data + self.dircache.clear() # this is a bit heavy handed + + async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs): + # puts binary + if mode == "create" and self.exists(rpath): + raise FileExistsError + with open(lpath, "rb") as f: + self.references[rpath] = f.read() + self.dircache.clear() # this is a bit heavy handed + + def save_json(self, url, **storage_options): + """Write modified references into new location""" + out = {} + for k, v in self.references.items(): + if isinstance(v, bytes): + try: + out[k] = v.decode("ascii") + except UnicodeDecodeError: + out[k] = (b"base64:" + base64.b64encode(v)).decode() + else: + out[k] = v + with fsspec.open(url, "wb", **storage_options) as f: + f.write(json.dumps({"version": 1, "refs": out}).encode()) + + +class ReferenceFile(AbstractBufferedFile): + def __init__( + self, + fs, + path, + mode="rb", + block_size="default", + autocommit=True, + cache_type="readahead", + cache_options=None, + size=None, + **kwargs, + ): + super().__init__( + fs, + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + size=size, + cache_type=cache_type, + cache_options=cache_options, + **kwargs, + ) + part_or_url, self.start, self.end = self.fs._cat_common(self.path) + protocol, _ = split_protocol(part_or_url) + self.src_fs = self.fs.fss[protocol] + self.src_path = part_or_url + self._f = None + + @property + def f(self): + if self._f is None or self._f.closed: + self._f = self.src_fs._open( + self.src_path, + mode=self.mode, + block_size=self.blocksize, + autocommit=self.autocommit, + cache_type="none", + **self.kwargs, + ) + return self._f + + def close(self): + if self._f is not None: + self._f.close() + return super().close() + + def _fetch_range(self, start, end): + start = start + self.start + end = min(end + self.start, self.end) + self.f.seek(start) + return self.f.read(end - start) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/sftp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/sftp.py new file mode 100644 index 0000000000000000000000000000000000000000..77f7b370cd246f9a9bfd34141afc3edd728d13c3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/sftp.py @@ -0,0 +1,180 @@ +import datetime +import logging +import os +import types +import uuid +from stat import S_ISDIR, S_ISLNK + +import paramiko + +from .. import AbstractFileSystem +from ..utils import infer_storage_options + +logger = logging.getLogger("fsspec.sftp") + + +class SFTPFileSystem(AbstractFileSystem): + """Files over SFTP/SSH + + Peer-to-peer filesystem over SSH using paramiko. + + Note: if using this with the ``open`` or ``open_files``, with full URLs, + there is no way to tell if a path is relative, so all paths are assumed + to be absolute. + """ + + protocol = "sftp", "ssh" + + def __init__(self, host, **ssh_kwargs): + """ + + Parameters + ---------- + host: str + Hostname or IP as a string + temppath: str + Location on the server to put files, when within a transaction + ssh_kwargs: dict + Parameters passed on to connection. See details in + https://docs.paramiko.org/en/3.3/api/client.html#paramiko.client.SSHClient.connect + May include port, username, password... + """ + if self._cached: + return + super().__init__(**ssh_kwargs) + self.temppath = ssh_kwargs.pop("temppath", "/tmp") # remote temp directory + self.host = host + self.ssh_kwargs = ssh_kwargs + self._connect() + + def _connect(self): + logger.debug("Connecting to SFTP server %s", self.host) + self.client = paramiko.SSHClient() + self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + self.client.connect(self.host, **self.ssh_kwargs) + self.ftp = self.client.open_sftp() + + @classmethod + def _strip_protocol(cls, path): + return infer_storage_options(path)["path"] + + @staticmethod + def _get_kwargs_from_urls(urlpath): + out = infer_storage_options(urlpath) + out.pop("path", None) + out.pop("protocol", None) + return out + + def mkdir(self, path, create_parents=True, mode=511): + logger.debug("Creating folder %s", path) + if self.exists(path): + raise FileExistsError(f"File exists: {path}") + + if create_parents: + self.makedirs(path) + else: + self.ftp.mkdir(path, mode) + + def makedirs(self, path, exist_ok=False, mode=511): + if self.exists(path) and not exist_ok: + raise FileExistsError(f"File exists: {path}") + + parts = path.split("/") + new_path = "/" if path[:1] == "/" else "" + + for part in parts: + if part: + new_path = f"{new_path}/{part}" if new_path else part + if not self.exists(new_path): + self.ftp.mkdir(new_path, mode) + + def rmdir(self, path): + logger.debug("Removing folder %s", path) + self.ftp.rmdir(path) + + def info(self, path): + stat = self._decode_stat(self.ftp.stat(path)) + stat["name"] = path + return stat + + @staticmethod + def _decode_stat(stat, parent_path=None): + if S_ISDIR(stat.st_mode): + t = "directory" + elif S_ISLNK(stat.st_mode): + t = "link" + else: + t = "file" + out = { + "name": "", + "size": stat.st_size, + "type": t, + "uid": stat.st_uid, + "gid": stat.st_gid, + "time": datetime.datetime.fromtimestamp( + stat.st_atime, tz=datetime.timezone.utc + ), + "mtime": datetime.datetime.fromtimestamp( + stat.st_mtime, tz=datetime.timezone.utc + ), + } + if parent_path: + out["name"] = "/".join([parent_path.rstrip("/"), stat.filename]) + return out + + def ls(self, path, detail=False): + logger.debug("Listing folder %s", path) + stats = [self._decode_stat(stat, path) for stat in self.ftp.listdir_iter(path)] + if detail: + return stats + else: + paths = [stat["name"] for stat in stats] + return sorted(paths) + + def put(self, lpath, rpath, callback=None, **kwargs): + logger.debug("Put file %s into %s", lpath, rpath) + self.ftp.put(lpath, rpath) + + def get_file(self, rpath, lpath, **kwargs): + if self.isdir(rpath): + os.makedirs(lpath, exist_ok=True) + else: + self.ftp.get(self._strip_protocol(rpath), lpath) + + def _open(self, path, mode="rb", block_size=None, **kwargs): + """ + block_size: int or None + If 0, no buffering, if 1, line buffering, if >1, buffer that many + bytes, if None use default from paramiko. + """ + logger.debug("Opening file %s", path) + if kwargs.get("autocommit", True) is False: + # writes to temporary file, move on commit + path2 = "/".join([self.temppath, str(uuid.uuid4())]) + f = self.ftp.open(path2, mode, bufsize=block_size if block_size else -1) + f.temppath = path2 + f.targetpath = path + f.fs = self + f.commit = types.MethodType(commit_a_file, f) + f.discard = types.MethodType(discard_a_file, f) + else: + f = self.ftp.open(path, mode, bufsize=block_size if block_size else -1) + return f + + def _rm(self, path): + if self.isdir(path): + self.ftp.rmdir(path) + else: + self.ftp.remove(path) + + def mv(self, old, new): + logger.debug("Renaming %s into %s", old, new) + self.ftp.posix_rename(old, new) + + +def commit_a_file(self): + self.fs.mv(self.temppath, self.targetpath) + + +def discard_a_file(self): + self.fs._rm(self.temppath) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/smb.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/smb.py new file mode 100644 index 0000000000000000000000000000000000000000..db6b3f5c3702de90cf121ccca49f3ca2b580df9f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/smb.py @@ -0,0 +1,416 @@ +""" +This module contains SMBFileSystem class responsible for handling access to +Windows Samba network shares by using package smbprotocol +""" + +import datetime +import re +import uuid +from stat import S_ISDIR, S_ISLNK + +import smbclient +import smbprotocol.exceptions + +from .. import AbstractFileSystem +from ..utils import infer_storage_options + +# ! pylint: disable=bad-continuation + + +class SMBFileSystem(AbstractFileSystem): + """Allow reading and writing to Windows and Samba network shares. + + When using `fsspec.open()` for getting a file-like object the URI + should be specified as this format: + ``smb://workgroup;user:password@server:port/share/folder/file.csv``. + + Example:: + + >>> import fsspec + >>> with fsspec.open( + ... 'smb://myuser:mypassword@myserver.com/' 'share/folder/file.csv' + ... ) as smbfile: + ... df = pd.read_csv(smbfile, sep='|', header=None) + + Note that you need to pass in a valid hostname or IP address for the host + component of the URL. Do not use the Windows/NetBIOS machine name for the + host component. + + The first component of the path in the URL points to the name of the shared + folder. Subsequent path components will point to the directory/folder/file. + + The URL components ``workgroup`` , ``user``, ``password`` and ``port`` may be + optional. + + .. note:: + + For working this source require `smbprotocol`_ to be installed, e.g.:: + + $ pip install smbprotocol + # or + # pip install smbprotocol[kerberos] + + .. _smbprotocol: https://github.com/jborean93/smbprotocol#requirements + + Note: if using this with the ``open`` or ``open_files``, with full URLs, + there is no way to tell if a path is relative, so all paths are assumed + to be absolute. + """ + + protocol = "smb" + + # pylint: disable=too-many-arguments + def __init__( + self, + host, + port=None, + username=None, + password=None, + timeout=60, + encrypt=None, + share_access=None, + register_session_retries=4, + register_session_retry_wait=1, + register_session_retry_factor=10, + auto_mkdir=False, + **kwargs, + ): + """ + You can use _get_kwargs_from_urls to get some kwargs from + a reasonable SMB url. + + Authentication will be anonymous or integrated if username/password are not + given. + + Parameters + ---------- + host: str + The remote server name/ip to connect to + port: int or None + Port to connect with. Usually 445, sometimes 139. + username: str or None + Username to connect with. Required if Kerberos auth is not being used. + password: str or None + User's password on the server, if using username + timeout: int + Connection timeout in seconds + encrypt: bool + Whether to force encryption or not, once this has been set to True + the session cannot be changed back to False. + share_access: str or None + Specifies the default access applied to file open operations + performed with this file system object. + This affects whether other processes can concurrently open a handle + to the same file. + + - None (the default): exclusively locks the file until closed. + - 'r': Allow other handles to be opened with read access. + - 'w': Allow other handles to be opened with write access. + - 'd': Allow other handles to be opened with delete access. + register_session_retries: int + Number of retries to register a session with the server. Retries are not performed + for authentication errors, as they are considered as invalid credentials and not network + issues. If set to negative value, no register attempts will be performed. + register_session_retry_wait: int + Time in seconds to wait between each retry. Number must be non-negative. + register_session_retry_factor: int + Base factor for the wait time between each retry. The wait time + is calculated using exponential function. For factor=1 all wait times + will be equal to `register_session_retry_wait`. For any number of retries, + the last wait time will be equal to `register_session_retry_wait` and for retries>1 + the first wait time will be equal to `register_session_retry_wait / factor`. + Number must be equal to or greater than 1. Optimal factor is 10. + auto_mkdir: bool + Whether, when opening a file, the directory containing it should + be created (if it doesn't already exist). This is assumed by pyarrow + and zarr-python code. + """ + super().__init__(**kwargs) + self.host = host + self.port = port + self.username = username + self.password = password + self.timeout = timeout + self.encrypt = encrypt + self.temppath = kwargs.pop("temppath", "") + self.share_access = share_access + self.register_session_retries = register_session_retries + if register_session_retry_wait < 0: + raise ValueError( + "register_session_retry_wait must be a non-negative integer" + ) + self.register_session_retry_wait = register_session_retry_wait + if register_session_retry_factor < 1: + raise ValueError( + "register_session_retry_factor must be a positive " + "integer equal to or greater than 1" + ) + self.register_session_retry_factor = register_session_retry_factor + self.auto_mkdir = auto_mkdir + self._connect() + + @property + def _port(self): + return 445 if self.port is None else self.port + + def _connect(self): + import time + + if self.register_session_retries <= -1: + return + + retried_errors = [] + + wait_time = self.register_session_retry_wait + n_waits = ( + self.register_session_retries - 1 + ) # -1 = No wait time after the last retry + factor = self.register_session_retry_factor + + # Generate wait times for each retry attempt. + # Wait times are calculated using exponential function. For factor=1 all wait times + # will be equal to `wait`. For any number of retries the last wait time will be + # equal to `wait` and for retries>2 the first wait time will be equal to `wait / factor`. + wait_times = iter( + factor ** (n / n_waits - 1) * wait_time for n in range(0, n_waits + 1) + ) + + for attempt in range(self.register_session_retries + 1): + try: + smbclient.register_session( + self.host, + username=self.username, + password=self.password, + port=self._port, + encrypt=self.encrypt, + connection_timeout=self.timeout, + ) + return + except ( + smbprotocol.exceptions.SMBAuthenticationError, + smbprotocol.exceptions.LogonFailure, + ): + # These exceptions should not be repeated, as they clearly indicate + # that the credentials are invalid and not a network issue. + raise + except ValueError as exc: + if re.findall(r"\[Errno -\d+]", str(exc)): + # This exception is raised by the smbprotocol.transport:Tcp.connect + # and originates from socket.gaierror (OSError). These exceptions might + # be raised due to network instability. We will retry to connect. + retried_errors.append(exc) + else: + # All another ValueError exceptions should be raised, as they are not + # related to network issues. + raise + except Exception as exc: + # Save the exception and retry to connect. This except might be dropped + # in the future, once all exceptions suited for retry are identified. + retried_errors.append(exc) + + if attempt < self.register_session_retries: + time.sleep(next(wait_times)) + + # Raise last exception to inform user about the connection issues. + # Note: Should we use ExceptionGroup to raise all exceptions? + raise retried_errors[-1] + + @classmethod + def _strip_protocol(cls, path): + return infer_storage_options(path)["path"] + + @staticmethod + def _get_kwargs_from_urls(path): + # smb://workgroup;user:password@host:port/share/folder/file.csv + out = infer_storage_options(path) + out.pop("path", None) + out.pop("protocol", None) + return out + + def mkdir(self, path, create_parents=True, **kwargs): + wpath = _as_unc_path(self.host, path) + if create_parents: + smbclient.makedirs(wpath, exist_ok=False, port=self._port, **kwargs) + else: + smbclient.mkdir(wpath, port=self._port, **kwargs) + + def makedirs(self, path, exist_ok=False): + if _share_has_path(path): + wpath = _as_unc_path(self.host, path) + smbclient.makedirs(wpath, exist_ok=exist_ok, port=self._port) + + def rmdir(self, path): + if _share_has_path(path): + wpath = _as_unc_path(self.host, path) + smbclient.rmdir(wpath, port=self._port) + + def info(self, path, **kwargs): + wpath = _as_unc_path(self.host, path) + stats = smbclient.stat(wpath, port=self._port, **kwargs) + if S_ISDIR(stats.st_mode): + stype = "directory" + elif S_ISLNK(stats.st_mode): + stype = "link" + else: + stype = "file" + res = { + "name": path + "/" if stype == "directory" else path, + "size": stats.st_size, + "type": stype, + "uid": stats.st_uid, + "gid": stats.st_gid, + "time": stats.st_atime, + "mtime": stats.st_mtime, + } + return res + + def created(self, path): + """Return the created timestamp of a file as a datetime.datetime""" + wpath = _as_unc_path(self.host, path) + stats = smbclient.stat(wpath, port=self._port) + return datetime.datetime.fromtimestamp(stats.st_ctime, tz=datetime.timezone.utc) + + def modified(self, path): + """Return the modified timestamp of a file as a datetime.datetime""" + wpath = _as_unc_path(self.host, path) + stats = smbclient.stat(wpath, port=self._port) + return datetime.datetime.fromtimestamp(stats.st_mtime, tz=datetime.timezone.utc) + + def ls(self, path, detail=True, **kwargs): + unc = _as_unc_path(self.host, path) + listed = smbclient.listdir(unc, port=self._port, **kwargs) + dirs = ["/".join([path.rstrip("/"), p]) for p in listed] + if detail: + dirs = [self.info(d) for d in dirs] + return dirs + + # pylint: disable=too-many-arguments + def _open( + self, + path, + mode="rb", + block_size=-1, + autocommit=True, + cache_options=None, + **kwargs, + ): + """ + block_size: int or None + If 0, no buffering, 1, line buffering, >1, buffer that many bytes + + Notes + ----- + By specifying 'share_access' in 'kwargs' it is possible to override the + default shared access setting applied in the constructor of this object. + """ + if self.auto_mkdir and "w" in mode: + self.makedirs(self._parent(path), exist_ok=True) + bls = block_size if block_size is not None and block_size >= 0 else -1 + wpath = _as_unc_path(self.host, path) + share_access = kwargs.pop("share_access", self.share_access) + if "w" in mode and autocommit is False: + temp = _as_temp_path(self.host, path, self.temppath) + return SMBFileOpener( + wpath, temp, mode, port=self._port, block_size=bls, **kwargs + ) + return smbclient.open_file( + wpath, + mode, + buffering=bls, + share_access=share_access, + port=self._port, + **kwargs, + ) + + def copy(self, path1, path2, **kwargs): + """Copy within two locations in the same filesystem""" + wpath1 = _as_unc_path(self.host, path1) + wpath2 = _as_unc_path(self.host, path2) + if self.auto_mkdir: + self.makedirs(self._parent(path2), exist_ok=True) + smbclient.copyfile(wpath1, wpath2, port=self._port, **kwargs) + + def _rm(self, path): + if _share_has_path(path): + wpath = _as_unc_path(self.host, path) + stats = smbclient.stat(wpath, port=self._port) + if S_ISDIR(stats.st_mode): + smbclient.rmdir(wpath, port=self._port) + else: + smbclient.remove(wpath, port=self._port) + + def mv(self, path1, path2, recursive=None, maxdepth=None, **kwargs): + wpath1 = _as_unc_path(self.host, path1) + wpath2 = _as_unc_path(self.host, path2) + smbclient.rename(wpath1, wpath2, port=self._port, **kwargs) + + +def _as_unc_path(host, path): + rpath = path.replace("/", "\\") + unc = f"\\\\{host}{rpath}" + return unc + + +def _as_temp_path(host, path, temppath): + share = path.split("/")[1] + temp_file = f"/{share}{temppath}/{uuid.uuid4()}" + unc = _as_unc_path(host, temp_file) + return unc + + +def _share_has_path(path): + parts = path.count("/") + if path.endswith("/"): + return parts > 2 + return parts > 1 + + +class SMBFileOpener: + """writes to remote temporary file, move on commit""" + + def __init__(self, path, temp, mode, port=445, block_size=-1, **kwargs): + self.path = path + self.temp = temp + self.mode = mode + self.block_size = block_size + self.kwargs = kwargs + self.smbfile = None + self._incontext = False + self.port = port + self._open() + + def _open(self): + if self.smbfile is None or self.smbfile.closed: + self.smbfile = smbclient.open_file( + self.temp, + self.mode, + port=self.port, + buffering=self.block_size, + **self.kwargs, + ) + + def commit(self): + """Move temp file to definitive on success.""" + # TODO: use transaction support in SMB protocol + smbclient.replace(self.temp, self.path, port=self.port) + + def discard(self): + """Remove the temp file on failure.""" + smbclient.remove(self.temp, port=self.port) + + def __fspath__(self): + return self.path + + def __iter__(self): + return self.smbfile.__iter__() + + def __getattr__(self, item): + return getattr(self.smbfile, item) + + def __enter__(self): + self._incontext = True + return self.smbfile.__enter__() + + def __exit__(self, exc_type, exc_value, traceback): + self._incontext = False + self.smbfile.__exit__(exc_type, exc_value, traceback) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/tar.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/tar.py new file mode 100644 index 0000000000000000000000000000000000000000..412e5ba4d2cdea7db090dc96412e697909a38d78 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/tar.py @@ -0,0 +1,124 @@ +import logging +import tarfile + +import fsspec +from fsspec.archive import AbstractArchiveFileSystem +from fsspec.compression import compr +from fsspec.utils import infer_compression + +typemap = {b"0": "file", b"5": "directory"} + +logger = logging.getLogger("tar") + + +class TarFileSystem(AbstractArchiveFileSystem): + """Compressed Tar archives as a file-system (read-only) + + Supports the following formats: + tar.gz, tar.bz2, tar.xz + """ + + root_marker = "" + protocol = "tar" + cachable = False + + def __init__( + self, + fo="", + index_store=None, + target_options=None, + target_protocol=None, + compression=None, + **kwargs, + ): + super().__init__(**kwargs) + target_options = target_options or {} + + if isinstance(fo, str): + self.of = fsspec.open(fo, protocol=target_protocol, **target_options) + fo = self.of.open() # keep the reference + + # Try to infer compression. + if compression is None: + name = None + + # Try different ways to get hold of the filename. `fo` might either + # be a `fsspec.LocalFileOpener`, an `io.BufferedReader` or an + # `fsspec.AbstractFileSystem` instance. + try: + # Amended io.BufferedReader or similar. + # This uses a "protocol extension" where original filenames are + # propagated to archive-like filesystems in order to let them + # infer the right compression appropriately. + if hasattr(fo, "original"): + name = fo.original + + # fsspec.LocalFileOpener + elif hasattr(fo, "path"): + name = fo.path + + # io.BufferedReader + elif hasattr(fo, "name"): + name = fo.name + + # fsspec.AbstractFileSystem + elif hasattr(fo, "info"): + name = fo.info()["name"] + + except Exception as ex: + logger.warning( + f"Unable to determine file name, not inferring compression: {ex}" + ) + + if name is not None: + compression = infer_compression(name) + logger.info(f"Inferred compression {compression} from file name {name}") + + if compression is not None: + # TODO: tarfile already implements compression with modes like "'r:gz'", + # but then would seek to offset in the file work? + fo = compr[compression](fo) + + self._fo_ref = fo + self.fo = fo # the whole instance is a context + self.tar = tarfile.TarFile(fileobj=self.fo) + self.dir_cache = None + + self.index_store = index_store + self.index = None + self._index() + + def _index(self): + # TODO: load and set saved index, if exists + out = {} + for ti in self.tar: + info = ti.get_info() + info["type"] = typemap.get(info["type"], "file") + name = ti.get_info()["name"].rstrip("/") + out[name] = (info, ti.offset_data) + + self.index = out + # TODO: save index to self.index_store here, if set + + def _get_dirs(self): + if self.dir_cache is not None: + return + + # This enables ls to get directories as children as well as files + self.dir_cache = { + dirname: {"name": dirname, "size": 0, "type": "directory"} + for dirname in self._all_dirnames(self.tar.getnames()) + } + for member in self.tar.getmembers(): + info = member.get_info() + info["name"] = info["name"].rstrip("/") + info["type"] = typemap.get(info["type"], "file") + self.dir_cache[info["name"]] = info + + def _open(self, path, mode="rb", **kwargs): + if mode != "rb": + raise ValueError("Read-only filesystem implementation") + details, offset = self.index[path] + if details["type"] != "file": + raise ValueError("Can only handle regular files") + return self.tar.extractfile(path) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/webhdfs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/webhdfs.py new file mode 100644 index 0000000000000000000000000000000000000000..c6e0d8446f875ec9578cccf055aeb47cd1c2e996 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/webhdfs.py @@ -0,0 +1,485 @@ +# https://hadoop.apache.org/docs/r1.0.4/webhdfs.html + +import logging +import os +import secrets +import shutil +import tempfile +import uuid +from contextlib import suppress +from urllib.parse import quote + +import requests + +from ..spec import AbstractBufferedFile, AbstractFileSystem +from ..utils import infer_storage_options, tokenize + +logger = logging.getLogger("webhdfs") + + +class WebHDFS(AbstractFileSystem): + """ + Interface to HDFS over HTTP using the WebHDFS API. Supports also HttpFS gateways. + + Four auth mechanisms are supported: + + insecure: no auth is done, and the user is assumed to be whoever they + say they are (parameter ``user``), or a predefined value such as + "dr.who" if not given + spnego: when kerberos authentication is enabled, auth is negotiated by + requests_kerberos https://github.com/requests/requests-kerberos . + This establishes a session based on existing kinit login and/or + specified principal/password; parameters are passed with ``kerb_kwargs`` + token: uses an existing Hadoop delegation token from another secured + service. Indeed, this client can also generate such tokens when + not insecure. Note that tokens expire, but can be renewed (by a + previously specified user) and may allow for proxying. + basic-auth: used when both parameter ``user`` and parameter ``password`` + are provided. + + """ + + tempdir = str(tempfile.gettempdir()) + protocol = "webhdfs", "webHDFS" + + def __init__( + self, + host, + port=50070, + kerberos=False, + token=None, + user=None, + password=None, + proxy_to=None, + kerb_kwargs=None, + data_proxy=None, + use_https=False, + session_cert=None, + session_verify=True, + **kwargs, + ): + """ + Parameters + ---------- + host: str + Name-node address + port: int + Port for webHDFS + kerberos: bool + Whether to authenticate with kerberos for this connection + token: str or None + If given, use this token on every call to authenticate. A user + and user-proxy may be encoded in the token and should not be also + given + user: str or None + If given, assert the user name to connect with + password: str or None + If given, assert the password to use for basic auth. If password + is provided, user must be provided also + proxy_to: str or None + If given, the user has the authority to proxy, and this value is + the user in who's name actions are taken + kerb_kwargs: dict + Any extra arguments for HTTPKerberosAuth, see + ``_ + data_proxy: dict, callable or None + If given, map data-node addresses. This can be necessary if the + HDFS cluster is behind a proxy, running on Docker or otherwise has + a mismatch between the host-names given by the name-node and the + address by which to refer to them from the client. If a dict, + maps host names ``host->data_proxy[host]``; if a callable, full + URLs are passed, and function must conform to + ``url->data_proxy(url)``. + use_https: bool + Whether to connect to the Name-node using HTTPS instead of HTTP + session_cert: str or Tuple[str, str] or None + Path to a certificate file, or tuple of (cert, key) files to use + for the requests.Session + session_verify: str, bool or None + Path to a certificate file to use for verifying the requests.Session. + kwargs + """ + if self._cached: + return + super().__init__(**kwargs) + self.url = f"{'https' if use_https else 'http'}://{host}:{port}/webhdfs/v1" + self.kerb = kerberos + self.kerb_kwargs = kerb_kwargs or {} + self.pars = {} + self.proxy = data_proxy or {} + if token is not None: + if user is not None or proxy_to is not None: + raise ValueError( + "If passing a delegation token, must not set " + "user or proxy_to, as these are encoded in the" + " token" + ) + self.pars["delegation"] = token + self.user = user + self.password = password + + if password is not None: + if user is None: + raise ValueError( + "If passing a password, the user must also be" + "set in order to set up the basic-auth" + ) + else: + if user is not None: + self.pars["user.name"] = user + + if proxy_to is not None: + self.pars["doas"] = proxy_to + if kerberos and user is not None: + raise ValueError( + "If using Kerberos auth, do not specify the " + "user, this is handled by kinit." + ) + + self.session_cert = session_cert + self.session_verify = session_verify + + self._connect() + + self._fsid = f"webhdfs_{tokenize(host, port)}" + + @property + def fsid(self): + return self._fsid + + def _connect(self): + self.session = requests.Session() + + if self.session_cert: + self.session.cert = self.session_cert + + self.session.verify = self.session_verify + + if self.kerb: + from requests_kerberos import HTTPKerberosAuth + + self.session.auth = HTTPKerberosAuth(**self.kerb_kwargs) + + if self.user is not None and self.password is not None: + from requests.auth import HTTPBasicAuth + + self.session.auth = HTTPBasicAuth(self.user, self.password) + + def _call(self, op, method="get", path=None, data=None, redirect=True, **kwargs): + path = self._strip_protocol(path) if path is not None else "" + url = self._apply_proxy(self.url + quote(path, safe="/=")) + args = kwargs.copy() + args.update(self.pars) + args["op"] = op.upper() + logger.debug("sending %s with %s", url, method) + out = self.session.request( + method=method.upper(), + url=url, + params=args, + data=data, + allow_redirects=redirect, + ) + if out.status_code in [400, 401, 403, 404, 500]: + try: + err = out.json() + msg = err["RemoteException"]["message"] + exp = err["RemoteException"]["exception"] + except (ValueError, KeyError): + pass + else: + if exp in ["IllegalArgumentException", "UnsupportedOperationException"]: + raise ValueError(msg) + elif exp in ["SecurityException", "AccessControlException"]: + raise PermissionError(msg) + elif exp in ["FileNotFoundException"]: + raise FileNotFoundError(msg) + else: + raise RuntimeError(msg) + out.raise_for_status() + return out + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + replication=None, + permissions=None, + **kwargs, + ): + """ + + Parameters + ---------- + path: str + File location + mode: str + 'rb', 'wb', etc. + block_size: int + Client buffer size for read-ahead or write buffer + autocommit: bool + If False, writes to temporary file that only gets put in final + location upon commit + replication: int + Number of copies of file on the cluster, write mode only + permissions: str or int + posix permissions, write mode only + kwargs + + Returns + ------- + WebHDFile instance + """ + block_size = block_size or self.blocksize + return WebHDFile( + self, + path, + mode=mode, + block_size=block_size, + tempdir=self.tempdir, + autocommit=autocommit, + replication=replication, + permissions=permissions, + ) + + @staticmethod + def _process_info(info): + info["type"] = info["type"].lower() + info["size"] = info["length"] + return info + + @classmethod + def _strip_protocol(cls, path): + return infer_storage_options(path)["path"] + + @staticmethod + def _get_kwargs_from_urls(urlpath): + out = infer_storage_options(urlpath) + out.pop("path", None) + out.pop("protocol", None) + if "username" in out: + out["user"] = out.pop("username") + return out + + def info(self, path): + out = self._call("GETFILESTATUS", path=path) + info = out.json()["FileStatus"] + info["name"] = path + return self._process_info(info) + + def ls(self, path, detail=False): + out = self._call("LISTSTATUS", path=path) + infos = out.json()["FileStatuses"]["FileStatus"] + for info in infos: + self._process_info(info) + info["name"] = path.rstrip("/") + "/" + info["pathSuffix"] + if detail: + return sorted(infos, key=lambda i: i["name"]) + else: + return sorted(info["name"] for info in infos) + + def content_summary(self, path): + """Total numbers of files, directories and bytes under path""" + out = self._call("GETCONTENTSUMMARY", path=path) + return out.json()["ContentSummary"] + + def ukey(self, path): + """Checksum info of file, giving method and result""" + out = self._call("GETFILECHECKSUM", path=path, redirect=False) + if "Location" in out.headers: + location = self._apply_proxy(out.headers["Location"]) + out2 = self.session.get(location) + out2.raise_for_status() + return out2.json()["FileChecksum"] + else: + out.raise_for_status() + return out.json()["FileChecksum"] + + def home_directory(self): + """Get user's home directory""" + out = self._call("GETHOMEDIRECTORY") + return out.json()["Path"] + + def get_delegation_token(self, renewer=None): + """Retrieve token which can give the same authority to other uses + + Parameters + ---------- + renewer: str or None + User who may use this token; if None, will be current user + """ + if renewer: + out = self._call("GETDELEGATIONTOKEN", renewer=renewer) + else: + out = self._call("GETDELEGATIONTOKEN") + t = out.json()["Token"] + if t is None: + raise ValueError("No token available for this user/security context") + return t["urlString"] + + def renew_delegation_token(self, token): + """Make token live longer. Returns new expiry time""" + out = self._call("RENEWDELEGATIONTOKEN", method="put", token=token) + return out.json()["long"] + + def cancel_delegation_token(self, token): + """Stop the token from being useful""" + self._call("CANCELDELEGATIONTOKEN", method="put", token=token) + + def chmod(self, path, mod): + """Set the permission at path + + Parameters + ---------- + path: str + location to set (file or directory) + mod: str or int + posix epresentation or permission, give as oct string, e.g, '777' + or 0o777 + """ + self._call("SETPERMISSION", method="put", path=path, permission=mod) + + def chown(self, path, owner=None, group=None): + """Change owning user and/or group""" + kwargs = {} + if owner is not None: + kwargs["owner"] = owner + if group is not None: + kwargs["group"] = group + self._call("SETOWNER", method="put", path=path, **kwargs) + + def set_replication(self, path, replication): + """ + Set file replication factor + + Parameters + ---------- + path: str + File location (not for directories) + replication: int + Number of copies of file on the cluster. Should be smaller than + number of data nodes; normally 3 on most systems. + """ + self._call("SETREPLICATION", path=path, method="put", replication=replication) + + def mkdir(self, path, **kwargs): + self._call("MKDIRS", method="put", path=path) + + def makedirs(self, path, exist_ok=False): + if exist_ok is False and self.exists(path): + raise FileExistsError(path) + self.mkdir(path) + + def mv(self, path1, path2, **kwargs): + self._call("RENAME", method="put", path=path1, destination=path2) + + def rm(self, path, recursive=False, **kwargs): + self._call( + "DELETE", + method="delete", + path=path, + recursive="true" if recursive else "false", + ) + + def rm_file(self, path, **kwargs): + self.rm(path) + + def cp_file(self, lpath, rpath, **kwargs): + with self.open(lpath) as lstream: + tmp_fname = "/".join([self._parent(rpath), f".tmp.{secrets.token_hex(16)}"]) + # Perform an atomic copy (stream to a temporary file and + # move it to the actual destination). + try: + with self.open(tmp_fname, "wb") as rstream: + shutil.copyfileobj(lstream, rstream) + self.mv(tmp_fname, rpath) + except BaseException: + with suppress(FileNotFoundError): + self.rm(tmp_fname) + raise + + def _apply_proxy(self, location): + if self.proxy and callable(self.proxy): + location = self.proxy(location) + elif self.proxy: + # as a dict + for k, v in self.proxy.items(): + location = location.replace(k, v, 1) + return location + + +class WebHDFile(AbstractBufferedFile): + """A file living in HDFS over webHDFS""" + + def __init__(self, fs, path, **kwargs): + super().__init__(fs, path, **kwargs) + kwargs = kwargs.copy() + if kwargs.get("permissions", None) is None: + kwargs.pop("permissions", None) + if kwargs.get("replication", None) is None: + kwargs.pop("replication", None) + self.permissions = kwargs.pop("permissions", 511) + tempdir = kwargs.pop("tempdir") + if kwargs.pop("autocommit", False) is False: + self.target = self.path + self.path = os.path.join(tempdir, str(uuid.uuid4())) + + def _upload_chunk(self, final=False): + """Write one part of a multi-block file upload + + Parameters + ========== + final: bool + This is the last block, so should complete file, if + self.autocommit is True. + """ + out = self.fs.session.post( + self.location, + data=self.buffer.getvalue(), + headers={"content-type": "application/octet-stream"}, + ) + out.raise_for_status() + return True + + def _initiate_upload(self): + """Create remote file/upload""" + kwargs = self.kwargs.copy() + if "a" in self.mode: + op, method = "APPEND", "POST" + else: + op, method = "CREATE", "PUT" + kwargs["overwrite"] = "true" + out = self.fs._call(op, method, self.path, redirect=False, **kwargs) + location = self.fs._apply_proxy(out.headers["Location"]) + if "w" in self.mode: + # create empty file to append to + out2 = self.fs.session.put( + location, headers={"content-type": "application/octet-stream"} + ) + out2.raise_for_status() + # after creating empty file, change location to append to + out2 = self.fs._call("APPEND", "POST", self.path, redirect=False, **kwargs) + self.location = self.fs._apply_proxy(out2.headers["Location"]) + + def _fetch_range(self, start, end): + start = max(start, 0) + end = min(self.size, end) + if start >= end or start >= self.size: + return b"" + out = self.fs._call( + "OPEN", path=self.path, offset=start, length=end - start, redirect=False + ) + out.raise_for_status() + if "Location" in out.headers: + location = out.headers["Location"] + out2 = self.fs.session.get(self.fs._apply_proxy(location)) + return out2.content + else: + return out.content + + def commit(self): + self.fs.mv(self.path, self.target) + + def discard(self): + self.fs.rm(self.path) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/zip.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/zip.py new file mode 100644 index 0000000000000000000000000000000000000000..6db3ae27806106a19a366886ab4b183f85c1cb1a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/implementations/zip.py @@ -0,0 +1,177 @@ +import os +import zipfile + +import fsspec +from fsspec.archive import AbstractArchiveFileSystem + + +class ZipFileSystem(AbstractArchiveFileSystem): + """Read/Write contents of ZIP archive as a file-system + + Keeps file object open while instance lives. + + This class is pickleable, but not necessarily thread-safe + """ + + root_marker = "" + protocol = "zip" + cachable = False + + def __init__( + self, + fo="", + mode="r", + target_protocol=None, + target_options=None, + compression=zipfile.ZIP_STORED, + allowZip64=True, + compresslevel=None, + **kwargs, + ): + """ + Parameters + ---------- + fo: str or file-like + Contains ZIP, and must exist. If a str, will fetch file using + :meth:`~fsspec.open_files`, which must return one file exactly. + mode: str + Accept: "r", "w", "a" + target_protocol: str (optional) + If ``fo`` is a string, this value can be used to override the + FS protocol inferred from a URL + target_options: dict (optional) + Kwargs passed when instantiating the target FS, if ``fo`` is + a string. + compression, allowZip64, compresslevel: passed to ZipFile + Only relevant when creating a ZIP + """ + super().__init__(self, **kwargs) + if mode not in set("rwa"): + raise ValueError(f"mode '{mode}' no understood") + self.mode = mode + if isinstance(fo, (str, os.PathLike)): + if mode == "a": + m = "r+b" + else: + m = mode + "b" + fo = fsspec.open( + fo, mode=m, protocol=target_protocol, **(target_options or {}) + ) + self.force_zip_64 = allowZip64 + self.of = fo + self.fo = fo.__enter__() # the whole instance is a context + self.zip = zipfile.ZipFile( + self.fo, + mode=mode, + compression=compression, + allowZip64=allowZip64, + compresslevel=compresslevel, + ) + self.dir_cache = None + + @classmethod + def _strip_protocol(cls, path): + # zip file paths are always relative to the archive root + return super()._strip_protocol(path).lstrip("/") + + def __del__(self): + if hasattr(self, "zip"): + self.close() + del self.zip + + def close(self): + """Commits any write changes to the file. Done on ``del`` too.""" + self.zip.close() + + def _get_dirs(self): + if self.dir_cache is None or self.mode in set("wa"): + # when writing, dir_cache is always in the ZipFile's attributes, + # not read from the file. + files = self.zip.infolist() + self.dir_cache = { + dirname.rstrip("/"): { + "name": dirname.rstrip("/"), + "size": 0, + "type": "directory", + } + for dirname in self._all_dirnames(self.zip.namelist()) + } + for z in files: + f = {s: getattr(z, s, None) for s in zipfile.ZipInfo.__slots__} + f.update( + { + "name": z.filename.rstrip("/"), + "size": z.file_size, + "type": ("directory" if z.is_dir() else "file"), + } + ) + self.dir_cache[f["name"]] = f + + def pipe_file(self, path, value, **kwargs): + # override upstream, because we know the exact file size in this case + self.zip.writestr(path, value, **kwargs) + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + path = self._strip_protocol(path) + if "r" in mode and self.mode in set("wa"): + if self.exists(path): + raise OSError("ZipFS can only be open for reading or writing, not both") + raise FileNotFoundError(path) + if "r" in self.mode and "w" in mode: + raise OSError("ZipFS can only be open for reading or writing, not both") + out = self.zip.open(path, mode.strip("b"), force_zip64=self.force_zip_64) + if "r" in mode: + info = self.info(path) + out.size = info["size"] + out.name = info["name"] + return out + + def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs): + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + # Remove the leading slash, as the zip file paths are always + # given without a leading slash + path = path.lstrip("/") + path_parts = list(filter(lambda s: bool(s), path.split("/"))) + + def _matching_starts(file_path): + file_parts = filter(lambda s: bool(s), file_path.split("/")) + return all(a == b for a, b in zip(path_parts, file_parts)) + + self._get_dirs() + + result = {} + # To match posix find, if an exact file name is given, we should + # return only that file + if path in self.dir_cache and self.dir_cache[path]["type"] == "file": + result[path] = self.dir_cache[path] + return result if detail else [path] + + for file_path, file_info in self.dir_cache.items(): + if not (path == "" or _matching_starts(file_path)): + continue + + if file_info["type"] == "directory": + if withdirs: + if file_path not in result: + result[file_path.strip("/")] = file_info + continue + + if file_path not in result: + result[file_path] = file_info if detail else None + + if maxdepth: + path_depth = path.count("/") + result = { + k: v for k, v in result.items() if k.count("/") - path_depth < maxdepth + } + return result if detail else sorted(result) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/json.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/json.py new file mode 100644 index 0000000000000000000000000000000000000000..3bd2485ef1cc581d608f8627cb4133c198e35293 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/json.py @@ -0,0 +1,117 @@ +import json +from collections.abc import Mapping, Sequence +from contextlib import suppress +from pathlib import PurePath +from typing import ( + Any, + Callable, + ClassVar, + Optional, +) + +from .registry import _import_class, get_filesystem_class +from .spec import AbstractFileSystem + + +class FilesystemJSONEncoder(json.JSONEncoder): + include_password: ClassVar[bool] = True + + def default(self, o: Any) -> Any: + if isinstance(o, AbstractFileSystem): + return o.to_dict(include_password=self.include_password) + if isinstance(o, PurePath): + cls = type(o) + return {"cls": f"{cls.__module__}.{cls.__name__}", "str": str(o)} + + return super().default(o) + + def make_serializable(self, obj: Any) -> Any: + """ + Recursively converts an object so that it can be JSON serialized via + :func:`json.dumps` and :func:`json.dump`, without actually calling + said functions. + """ + if isinstance(obj, (str, int, float, bool)): + return obj + if isinstance(obj, Mapping): + return {k: self.make_serializable(v) for k, v in obj.items()} + if isinstance(obj, Sequence): + return [self.make_serializable(v) for v in obj] + + return self.default(obj) + + +class FilesystemJSONDecoder(json.JSONDecoder): + def __init__( + self, + *, + object_hook: Optional[Callable[[dict[str, Any]], Any]] = None, + parse_float: Optional[Callable[[str], Any]] = None, + parse_int: Optional[Callable[[str], Any]] = None, + parse_constant: Optional[Callable[[str], Any]] = None, + strict: bool = True, + object_pairs_hook: Optional[Callable[[list[tuple[str, Any]]], Any]] = None, + ) -> None: + self.original_object_hook = object_hook + + super().__init__( + object_hook=self.custom_object_hook, + parse_float=parse_float, + parse_int=parse_int, + parse_constant=parse_constant, + strict=strict, + object_pairs_hook=object_pairs_hook, + ) + + @classmethod + def try_resolve_path_cls(cls, dct: dict[str, Any]): + with suppress(Exception): + fqp = dct["cls"] + + path_cls = _import_class(fqp) + + if issubclass(path_cls, PurePath): + return path_cls + + return None + + @classmethod + def try_resolve_fs_cls(cls, dct: dict[str, Any]): + with suppress(Exception): + if "cls" in dct: + try: + fs_cls = _import_class(dct["cls"]) + if issubclass(fs_cls, AbstractFileSystem): + return fs_cls + except Exception: + if "protocol" in dct: # Fallback if cls cannot be imported + return get_filesystem_class(dct["protocol"]) + + raise + + return None + + def custom_object_hook(self, dct: dict[str, Any]): + if "cls" in dct: + if (obj_cls := self.try_resolve_fs_cls(dct)) is not None: + return AbstractFileSystem.from_dict(dct) + if (obj_cls := self.try_resolve_path_cls(dct)) is not None: + return obj_cls(dct["str"]) + + if self.original_object_hook is not None: + return self.original_object_hook(dct) + + return dct + + def unmake_serializable(self, obj: Any) -> Any: + """ + Inverse function of :meth:`FilesystemJSONEncoder.make_serializable`. + """ + if isinstance(obj, dict): + obj = self.custom_object_hook(obj) + if isinstance(obj, dict): + return {k: self.unmake_serializable(v) for k, v in obj.items()} + if isinstance(obj, (list, tuple)): + return [self.unmake_serializable(v) for v in obj] + + return obj diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/mapping.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..752eef35273b13eded7297e2e801b58e436a25b1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/mapping.py @@ -0,0 +1,251 @@ +import array +import logging +import posixpath +import warnings +from collections.abc import MutableMapping +from functools import cached_property + +from fsspec.core import url_to_fs + +logger = logging.getLogger("fsspec.mapping") + + +class FSMap(MutableMapping): + """Wrap a FileSystem instance as a mutable wrapping. + + The keys of the mapping become files under the given root, and the + values (which must be bytes) the contents of those files. + + Parameters + ---------- + root: string + prefix for all the files + fs: FileSystem instance + check: bool (=True) + performs a touch at the location, to check for write access. + + Examples + -------- + >>> fs = FileSystem(**parameters) # doctest: +SKIP + >>> d = FSMap('my-data/path/', fs) # doctest: +SKIP + or, more likely + >>> d = fs.get_mapper('my-data/path/') + + >>> d['loc1'] = b'Hello World' # doctest: +SKIP + >>> list(d.keys()) # doctest: +SKIP + ['loc1'] + >>> d['loc1'] # doctest: +SKIP + b'Hello World' + """ + + def __init__(self, root, fs, check=False, create=False, missing_exceptions=None): + self.fs = fs + self.root = fs._strip_protocol(root) + self._root_key_to_str = fs._strip_protocol(posixpath.join(root, "x"))[:-1] + if missing_exceptions is None: + missing_exceptions = ( + FileNotFoundError, + IsADirectoryError, + NotADirectoryError, + ) + self.missing_exceptions = missing_exceptions + self.check = check + self.create = create + if create: + if not self.fs.exists(root): + self.fs.mkdir(root) + if check: + if not self.fs.exists(root): + raise ValueError( + f"Path {root} does not exist. Create " + f" with the ``create=True`` keyword" + ) + self.fs.touch(root + "/a") + self.fs.rm(root + "/a") + + @cached_property + def dirfs(self): + """dirfs instance that can be used with the same keys as the mapper""" + from .implementations.dirfs import DirFileSystem + + return DirFileSystem(path=self._root_key_to_str, fs=self.fs) + + def clear(self): + """Remove all keys below root - empties out mapping""" + logger.info("Clear mapping at %s", self.root) + try: + self.fs.rm(self.root, True) + self.fs.mkdir(self.root) + except: # noqa: E722 + pass + + def getitems(self, keys, on_error="raise"): + """Fetch multiple items from the store + + If the backend is async-able, this might proceed concurrently + + Parameters + ---------- + keys: list(str) + They keys to be fetched + on_error : "raise", "omit", "return" + If raise, an underlying exception will be raised (converted to KeyError + if the type is in self.missing_exceptions); if omit, keys with exception + will simply not be included in the output; if "return", all keys are + included in the output, but the value will be bytes or an exception + instance. + + Returns + ------- + dict(key, bytes|exception) + """ + keys2 = [self._key_to_str(k) for k in keys] + oe = on_error if on_error == "raise" else "return" + try: + out = self.fs.cat(keys2, on_error=oe) + if isinstance(out, bytes): + out = {keys2[0]: out} + except self.missing_exceptions as e: + raise KeyError from e + out = { + k: (KeyError() if isinstance(v, self.missing_exceptions) else v) + for k, v in out.items() + } + return { + key: out[k2] if on_error == "raise" else out.get(k2, KeyError(k2)) + for key, k2 in zip(keys, keys2) + if on_error == "return" or not isinstance(out[k2], BaseException) + } + + def setitems(self, values_dict): + """Set the values of multiple items in the store + + Parameters + ---------- + values_dict: dict(str, bytes) + """ + values = {self._key_to_str(k): maybe_convert(v) for k, v in values_dict.items()} + self.fs.pipe(values) + + def delitems(self, keys): + """Remove multiple keys from the store""" + self.fs.rm([self._key_to_str(k) for k in keys]) + + def _key_to_str(self, key): + """Generate full path for the key""" + if not isinstance(key, str): + # raise TypeError("key must be of type `str`, got `{type(key).__name__}`" + warnings.warn( + "from fsspec 2023.5 onward FSMap non-str keys will raise TypeError", + DeprecationWarning, + ) + if isinstance(key, list): + key = tuple(key) + key = str(key) + return f"{self._root_key_to_str}{key}".rstrip("/") + + def _str_to_key(self, s): + """Strip path of to leave key name""" + return s[len(self.root) :].lstrip("/") + + def __getitem__(self, key, default=None): + """Retrieve data""" + k = self._key_to_str(key) + try: + result = self.fs.cat(k) + except self.missing_exceptions as exc: + if default is not None: + return default + raise KeyError(key) from exc + return result + + def pop(self, key, default=None): + """Pop data""" + result = self.__getitem__(key, default) + try: + del self[key] + except KeyError: + pass + return result + + def __setitem__(self, key, value): + """Store value in key""" + key = self._key_to_str(key) + self.fs.mkdirs(self.fs._parent(key), exist_ok=True) + self.fs.pipe_file(key, maybe_convert(value)) + + def __iter__(self): + return (self._str_to_key(x) for x in self.fs.find(self.root)) + + def __len__(self): + return len(self.fs.find(self.root)) + + def __delitem__(self, key): + """Remove key""" + try: + self.fs.rm(self._key_to_str(key)) + except Exception as exc: + raise KeyError from exc + + def __contains__(self, key): + """Does key exist in mapping?""" + path = self._key_to_str(key) + return self.fs.isfile(path) + + def __reduce__(self): + return FSMap, (self.root, self.fs, False, False, self.missing_exceptions) + + +def maybe_convert(value): + if isinstance(value, array.array) or hasattr(value, "__array__"): + # bytes-like things + if hasattr(value, "dtype") and value.dtype.kind in "Mm": + # The buffer interface doesn't support datetime64/timdelta64 numpy + # arrays + value = value.view("int64") + value = bytes(memoryview(value)) + return value + + +def get_mapper( + url="", + check=False, + create=False, + missing_exceptions=None, + alternate_root=None, + **kwargs, +): + """Create key-value interface for given URL and options + + The URL will be of the form "protocol://location" and point to the root + of the mapper required. All keys will be file-names below this location, + and their values the contents of each key. + + Also accepts compound URLs like zip::s3://bucket/file.zip , see ``fsspec.open``. + + Parameters + ---------- + url: str + Root URL of mapping + check: bool + Whether to attempt to read from the location before instantiation, to + check that the mapping does exist + create: bool + Whether to make the directory corresponding to the root before + instantiating + missing_exceptions: None or tuple + If given, these exception types will be regarded as missing keys and + return KeyError when trying to read data. By default, you get + (FileNotFoundError, IsADirectoryError, NotADirectoryError) + alternate_root: None or str + In cases of complex URLs, the parser may fail to pick the correct part + for the mapper root, so this arg can override + + Returns + ------- + ``FSMap`` instance, the dict-like key-value store. + """ + # Removing protocol here - could defer to each open() on the backend + fs, urlpath = url_to_fs(url, **kwargs) + root = alternate_root if alternate_root is not None else urlpath + return FSMap(root, fs, check, create, missing_exceptions=missing_exceptions) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/parquet.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/parquet.py new file mode 100644 index 0000000000000000000000000000000000000000..faedb7b9e0aa90b6fb7cba33e794c4b4fb35eb77 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/parquet.py @@ -0,0 +1,541 @@ +import io +import json +import warnings + +from .core import url_to_fs +from .utils import merge_offset_ranges + +# Parquet-Specific Utilities for fsspec +# +# Most of the functions defined in this module are NOT +# intended for public consumption. The only exception +# to this is `open_parquet_file`, which should be used +# place of `fs.open()` to open parquet-formatted files +# on remote file systems. + + +def open_parquet_file( + path, + mode="rb", + fs=None, + metadata=None, + columns=None, + row_groups=None, + storage_options=None, + strict=False, + engine="auto", + max_gap=64_000, + max_block=256_000_000, + footer_sample_size=1_000_000, + **kwargs, +): + """ + Return a file-like object for a single Parquet file. + + The specified parquet `engine` will be used to parse the + footer metadata, and determine the required byte ranges + from the file. The target path will then be opened with + the "parts" (`KnownPartsOfAFile`) caching strategy. + + Note that this method is intended for usage with remote + file systems, and is unlikely to improve parquet-read + performance on local file systems. + + Parameters + ---------- + path: str + Target file path. + mode: str, optional + Mode option to be passed through to `fs.open`. Default is "rb". + metadata: Any, optional + Parquet metadata object. Object type must be supported + by the backend parquet engine. For now, only the "fastparquet" + engine supports an explicit `ParquetFile` metadata object. + If a metadata object is supplied, the remote footer metadata + will not need to be transferred into local memory. + fs: AbstractFileSystem, optional + Filesystem object to use for opening the file. If nothing is + specified, an `AbstractFileSystem` object will be inferred. + engine : str, default "auto" + Parquet engine to use for metadata parsing. Allowed options + include "fastparquet", "pyarrow", and "auto". The specified + engine must be installed in the current environment. If + "auto" is specified, and both engines are installed, + "fastparquet" will take precedence over "pyarrow". + columns: list, optional + List of all column names that may be read from the file. + row_groups : list, optional + List of all row-groups that may be read from the file. This + may be a list of row-group indices (integers), or it may be + a list of `RowGroup` metadata objects (if the "fastparquet" + engine is used). + storage_options : dict, optional + Used to generate an `AbstractFileSystem` object if `fs` was + not specified. + strict : bool, optional + Whether the resulting `KnownPartsOfAFile` cache should + fetch reads that go beyond a known byte-range boundary. + If `False` (the default), any read that ends outside a + known part will be zero padded. Note that using + `strict=True` may be useful for debugging. + max_gap : int, optional + Neighboring byte ranges will only be merged when their + inter-range gap is <= `max_gap`. Default is 64KB. + max_block : int, optional + Neighboring byte ranges will only be merged when the size of + the aggregated range is <= `max_block`. Default is 256MB. + footer_sample_size : int, optional + Number of bytes to read from the end of the path to look + for the footer metadata. If the sampled bytes do not contain + the footer, a second read request will be required, and + performance will suffer. Default is 1MB. + **kwargs : + Optional key-word arguments to pass to `fs.open` + """ + + # Make sure we have an `AbstractFileSystem` object + # to work with + if fs is None: + fs = url_to_fs(path, **(storage_options or {}))[0] + + # For now, `columns == []` not supported. Just use + # default `open` command with `path` input + if columns is not None and len(columns) == 0: + return fs.open(path, mode=mode) + + # Set the engine + engine = _set_engine(engine) + + # Fetch the known byte ranges needed to read + # `columns` and/or `row_groups` + data = _get_parquet_byte_ranges( + [path], + fs, + metadata=metadata, + columns=columns, + row_groups=row_groups, + engine=engine, + max_gap=max_gap, + max_block=max_block, + footer_sample_size=footer_sample_size, + ) + + # Extract file name from `data` + fn = next(iter(data)) if data else path + + # Call self.open with "parts" caching + options = kwargs.pop("cache_options", {}).copy() + return fs.open( + fn, + mode=mode, + cache_type="parts", + cache_options={ + **options, + "data": data.get(fn, {}), + "strict": strict, + }, + **kwargs, + ) + + +def _get_parquet_byte_ranges( + paths, + fs, + metadata=None, + columns=None, + row_groups=None, + max_gap=64_000, + max_block=256_000_000, + footer_sample_size=1_000_000, + engine="auto", +): + """Get a dictionary of the known byte ranges needed + to read a specific column/row-group selection from a + Parquet dataset. Each value in the output dictionary + is intended for use as the `data` argument for the + `KnownPartsOfAFile` caching strategy of a single path. + """ + + # Set engine if necessary + if isinstance(engine, str): + engine = _set_engine(engine) + + # Pass to specialized function if metadata is defined + if metadata is not None: + # Use the provided parquet metadata object + # to avoid transferring/parsing footer metadata + return _get_parquet_byte_ranges_from_metadata( + metadata, + fs, + engine, + columns=columns, + row_groups=row_groups, + max_gap=max_gap, + max_block=max_block, + ) + + # Get file sizes asynchronously + file_sizes = fs.sizes(paths) + + # Populate global paths, starts, & ends + result = {} + data_paths = [] + data_starts = [] + data_ends = [] + add_header_magic = True + if columns is None and row_groups is None: + # We are NOT selecting specific columns or row-groups. + # + # We can avoid sampling the footers, and just transfer + # all file data with cat_ranges + for i, path in enumerate(paths): + result[path] = {} + for b in range(0, file_sizes[i], max_block): + data_paths.append(path) + data_starts.append(b) + data_ends.append(min(b + max_block, file_sizes[i])) + add_header_magic = False # "Magic" should already be included + else: + # We ARE selecting specific columns or row-groups. + # + # Gather file footers. + # We just take the last `footer_sample_size` bytes of each + # file (or the entire file if it is smaller than that) + footer_starts = [] + footer_ends = [] + for i, path in enumerate(paths): + footer_ends.append(file_sizes[i]) + sample_size = max(0, file_sizes[i] - footer_sample_size) + footer_starts.append(sample_size) + footer_samples = fs.cat_ranges(paths, footer_starts, footer_ends) + + # Check our footer samples and re-sample if necessary. + missing_footer_starts = footer_starts.copy() + large_footer = 0 + for i, path in enumerate(paths): + footer_size = int.from_bytes(footer_samples[i][-8:-4], "little") + real_footer_start = file_sizes[i] - (footer_size + 8) + if real_footer_start < footer_starts[i]: + missing_footer_starts[i] = real_footer_start + large_footer = max(large_footer, (footer_size + 8)) + if large_footer: + warnings.warn( + f"Not enough data was used to sample the parquet footer. " + f"Try setting footer_sample_size >= {large_footer}." + ) + for i, block in enumerate( + fs.cat_ranges( + paths, + missing_footer_starts, + footer_starts, + ) + ): + footer_samples[i] = block + footer_samples[i] + footer_starts[i] = missing_footer_starts[i] + + # Calculate required byte ranges for each path + for i, path in enumerate(paths): + # Deal with small-file case. + # Just include all remaining bytes of the file + # in a single range. + if file_sizes[i] < max_block: + if footer_starts[i] > 0: + # Only need to transfer the data if the + # footer sample isn't already the whole file + data_paths.append(path) + data_starts.append(0) + data_ends.append(footer_starts[i]) + continue + + # Use "engine" to collect data byte ranges + path_data_starts, path_data_ends = engine._parquet_byte_ranges( + columns, + row_groups=row_groups, + footer=footer_samples[i], + footer_start=footer_starts[i], + ) + + data_paths += [path] * len(path_data_starts) + data_starts += path_data_starts + data_ends += path_data_ends + + # Merge adjacent offset ranges + data_paths, data_starts, data_ends = merge_offset_ranges( + data_paths, + data_starts, + data_ends, + max_gap=max_gap, + max_block=max_block, + sort=False, # Should already be sorted + ) + + # Start by populating `result` with footer samples + for i, path in enumerate(paths): + result[path] = {(footer_starts[i], footer_ends[i]): footer_samples[i]} + + # Transfer the data byte-ranges into local memory + _transfer_ranges(fs, result, data_paths, data_starts, data_ends) + + # Add b"PAR1" to header if necessary + if add_header_magic: + _add_header_magic(result) + + return result + + +def _get_parquet_byte_ranges_from_metadata( + metadata, + fs, + engine, + columns=None, + row_groups=None, + max_gap=64_000, + max_block=256_000_000, +): + """Simplified version of `_get_parquet_byte_ranges` for + the case that an engine-specific `metadata` object is + provided, and the remote footer metadata does not need to + be transferred before calculating the required byte ranges. + """ + + # Use "engine" to collect data byte ranges + data_paths, data_starts, data_ends = engine._parquet_byte_ranges( + columns, + row_groups=row_groups, + metadata=metadata, + ) + + # Merge adjacent offset ranges + data_paths, data_starts, data_ends = merge_offset_ranges( + data_paths, + data_starts, + data_ends, + max_gap=max_gap, + max_block=max_block, + sort=False, # Should be sorted + ) + + # Transfer the data byte-ranges into local memory + result = {fn: {} for fn in list(set(data_paths))} + _transfer_ranges(fs, result, data_paths, data_starts, data_ends) + + # Add b"PAR1" to header + _add_header_magic(result) + + return result + + +def _transfer_ranges(fs, blocks, paths, starts, ends): + # Use cat_ranges to gather the data byte_ranges + ranges = (paths, starts, ends) + for path, start, stop, data in zip(*ranges, fs.cat_ranges(*ranges)): + blocks[path][(start, stop)] = data + + +def _add_header_magic(data): + # Add b"PAR1" to file headers + for path in list(data.keys()): + add_magic = True + for k in data[path]: + if k[0] == 0 and k[1] >= 4: + add_magic = False + break + if add_magic: + data[path][(0, 4)] = b"PAR1" + + +def _set_engine(engine_str): + # Define a list of parquet engines to try + if engine_str == "auto": + try_engines = ("fastparquet", "pyarrow") + elif not isinstance(engine_str, str): + raise ValueError( + "Failed to set parquet engine! " + "Please pass 'fastparquet', 'pyarrow', or 'auto'" + ) + elif engine_str not in ("fastparquet", "pyarrow"): + raise ValueError(f"{engine_str} engine not supported by `fsspec.parquet`") + else: + try_engines = [engine_str] + + # Try importing the engines in `try_engines`, + # and choose the first one that succeeds + for engine in try_engines: + try: + if engine == "fastparquet": + return FastparquetEngine() + elif engine == "pyarrow": + return PyarrowEngine() + except ImportError: + pass + + # Raise an error if a supported parquet engine + # was not found + raise ImportError( + f"The following parquet engines are not installed " + f"in your python environment: {try_engines}." + f"Please install 'fastparquert' or 'pyarrow' to " + f"utilize the `fsspec.parquet` module." + ) + + +class FastparquetEngine: + # The purpose of the FastparquetEngine class is + # to check if fastparquet can be imported (on initialization) + # and to define a `_parquet_byte_ranges` method. In the + # future, this class may also be used to define other + # methods/logic that are specific to fastparquet. + + def __init__(self): + import fastparquet as fp + + self.fp = fp + + def _row_group_filename(self, row_group, pf): + return pf.row_group_filename(row_group) + + def _parquet_byte_ranges( + self, + columns, + row_groups=None, + metadata=None, + footer=None, + footer_start=None, + ): + # Initialize offset ranges and define ParqetFile metadata + pf = metadata + data_paths, data_starts, data_ends = [], [], [] + if pf is None: + pf = self.fp.ParquetFile(io.BytesIO(footer)) + + # Convert columns to a set and add any index columns + # specified in the pandas metadata (just in case) + column_set = None if columns is None else set(columns) + if column_set is not None and hasattr(pf, "pandas_metadata"): + md_index = [ + ind + for ind in pf.pandas_metadata.get("index_columns", []) + # Ignore RangeIndex information + if not isinstance(ind, dict) + ] + column_set |= set(md_index) + + # Check if row_groups is a list of integers + # or a list of row-group metadata + if row_groups and not isinstance(row_groups[0], int): + # Input row_groups contains row-group metadata + row_group_indices = None + else: + # Input row_groups contains row-group indices + row_group_indices = row_groups + row_groups = pf.row_groups + + # Loop through column chunks to add required byte ranges + for r, row_group in enumerate(row_groups): + # Skip this row-group if we are targeting + # specific row-groups + if row_group_indices is None or r in row_group_indices: + # Find the target parquet-file path for `row_group` + fn = self._row_group_filename(row_group, pf) + + for column in row_group.columns: + name = column.meta_data.path_in_schema[0] + # Skip this column if we are targeting a + # specific columns + if column_set is None or name in column_set: + file_offset0 = column.meta_data.dictionary_page_offset + if file_offset0 is None: + file_offset0 = column.meta_data.data_page_offset + num_bytes = column.meta_data.total_compressed_size + if footer_start is None or file_offset0 < footer_start: + data_paths.append(fn) + data_starts.append(file_offset0) + data_ends.append( + min( + file_offset0 + num_bytes, + footer_start or (file_offset0 + num_bytes), + ) + ) + + if metadata: + # The metadata in this call may map to multiple + # file paths. Need to include `data_paths` + return data_paths, data_starts, data_ends + return data_starts, data_ends + + +class PyarrowEngine: + # The purpose of the PyarrowEngine class is + # to check if pyarrow can be imported (on initialization) + # and to define a `_parquet_byte_ranges` method. In the + # future, this class may also be used to define other + # methods/logic that are specific to pyarrow. + + def __init__(self): + import pyarrow.parquet as pq + + self.pq = pq + + def _row_group_filename(self, row_group, metadata): + raise NotImplementedError + + def _parquet_byte_ranges( + self, + columns, + row_groups=None, + metadata=None, + footer=None, + footer_start=None, + ): + if metadata is not None: + raise ValueError("metadata input not supported for PyarrowEngine") + + data_starts, data_ends = [], [] + md = self.pq.ParquetFile(io.BytesIO(footer)).metadata + + # Convert columns to a set and add any index columns + # specified in the pandas metadata (just in case) + column_set = None if columns is None else set(columns) + if column_set is not None: + schema = md.schema.to_arrow_schema() + has_pandas_metadata = ( + schema.metadata is not None and b"pandas" in schema.metadata + ) + if has_pandas_metadata: + md_index = [ + ind + for ind in json.loads( + schema.metadata[b"pandas"].decode("utf8") + ).get("index_columns", []) + # Ignore RangeIndex information + if not isinstance(ind, dict) + ] + column_set |= set(md_index) + + # Loop through column chunks to add required byte ranges + for r in range(md.num_row_groups): + # Skip this row-group if we are targeting + # specific row-groups + if row_groups is None or r in row_groups: + row_group = md.row_group(r) + for c in range(row_group.num_columns): + column = row_group.column(c) + name = column.path_in_schema + # Skip this column if we are targeting a + # specific columns + split_name = name.split(".")[0] + if ( + column_set is None + or name in column_set + or split_name in column_set + ): + file_offset0 = column.dictionary_page_offset + if file_offset0 is None: + file_offset0 = column.data_page_offset + num_bytes = column.total_compressed_size + if file_offset0 < footer_start: + data_starts.append(file_offset0) + data_ends.append( + min(file_offset0 + num_bytes, footer_start) + ) + return data_starts, data_ends diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/registry.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..96ffad7f4a889662c8fb4a006e1c497652992430 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/registry.py @@ -0,0 +1,330 @@ +from __future__ import annotations + +import importlib +import types +import warnings + +__all__ = ["registry", "get_filesystem_class", "default"] + +# internal, mutable +_registry: dict[str, type] = {} + +# external, immutable +registry = types.MappingProxyType(_registry) +default = "file" + + +def register_implementation(name, cls, clobber=False, errtxt=None): + """Add implementation class to the registry + + Parameters + ---------- + name: str + Protocol name to associate with the class + cls: class or str + if a class: fsspec-compliant implementation class (normally inherits from + ``fsspec.AbstractFileSystem``, gets added straight to the registry. If a + str, the full path to an implementation class like package.module.class, + which gets added to known_implementations, + so the import is deferred until the filesystem is actually used. + clobber: bool (optional) + Whether to overwrite a protocol with the same name; if False, will raise + instead. + errtxt: str (optional) + If given, then a failure to import the given class will result in this + text being given. + """ + if isinstance(cls, str): + if name in known_implementations and clobber is False: + if cls != known_implementations[name]["class"]: + raise ValueError( + f"Name ({name}) already in the known_implementations and clobber " + f"is False" + ) + else: + known_implementations[name] = { + "class": cls, + "err": errtxt or f"{cls} import failed for protocol {name}", + } + + else: + if name in registry and clobber is False: + if _registry[name] is not cls: + raise ValueError( + f"Name ({name}) already in the registry and clobber is False" + ) + else: + _registry[name] = cls + + +# protocols mapped to the class which implements them. This dict can be +# updated with register_implementation +known_implementations = { + "abfs": { + "class": "adlfs.AzureBlobFileSystem", + "err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage", + }, + "adl": { + "class": "adlfs.AzureDatalakeFileSystem", + "err": "Install adlfs to access Azure Datalake Gen1", + }, + "arrow_hdfs": { + "class": "fsspec.implementations.arrow.HadoopFileSystem", + "err": "pyarrow and local java libraries required for HDFS", + }, + "asynclocal": { + "class": "morefs.asyn_local.AsyncLocalFileSystem", + "err": "Install 'morefs[asynclocalfs]' to use AsyncLocalFileSystem", + }, + "asyncwrapper": { + "class": "fsspec.implementations.asyn_wrapper.AsyncFileSystemWrapper", + }, + "az": { + "class": "adlfs.AzureBlobFileSystem", + "err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage", + }, + "blockcache": {"class": "fsspec.implementations.cached.CachingFileSystem"}, + "box": { + "class": "boxfs.BoxFileSystem", + "err": "Please install boxfs to access BoxFileSystem", + }, + "cached": {"class": "fsspec.implementations.cached.CachingFileSystem"}, + "dask": { + "class": "fsspec.implementations.dask.DaskWorkerFileSystem", + "err": "Install dask distributed to access worker file system", + }, + "data": {"class": "fsspec.implementations.data.DataFileSystem"}, + "dbfs": { + "class": "fsspec.implementations.dbfs.DatabricksFileSystem", + "err": "Install the requests package to use the DatabricksFileSystem", + }, + "dir": {"class": "fsspec.implementations.dirfs.DirFileSystem"}, + "dropbox": { + "class": "dropboxdrivefs.DropboxDriveFileSystem", + "err": ( + 'DropboxFileSystem requires "dropboxdrivefs","requests" and "' + '"dropbox" to be installed' + ), + }, + "dvc": { + "class": "dvc.api.DVCFileSystem", + "err": "Install dvc to access DVCFileSystem", + }, + "file": {"class": "fsspec.implementations.local.LocalFileSystem"}, + "filecache": {"class": "fsspec.implementations.cached.WholeFileCacheFileSystem"}, + "ftp": {"class": "fsspec.implementations.ftp.FTPFileSystem"}, + "gcs": { + "class": "gcsfs.GCSFileSystem", + "err": "Please install gcsfs to access Google Storage", + }, + "gdrive": { + "class": "gdrive_fsspec.GoogleDriveFileSystem", + "err": "Please install gdrive_fs for access to Google Drive", + }, + "generic": {"class": "fsspec.generic.GenericFileSystem"}, + "gist": { + "class": "fsspec.implementations.gist.GistFileSystem", + "err": "Install the requests package to use the gist FS", + }, + "git": { + "class": "fsspec.implementations.git.GitFileSystem", + "err": "Install pygit2 to browse local git repos", + }, + "github": { + "class": "fsspec.implementations.github.GithubFileSystem", + "err": "Install the requests package to use the github FS", + }, + "gs": { + "class": "gcsfs.GCSFileSystem", + "err": "Please install gcsfs to access Google Storage", + }, + "hdfs": { + "class": "fsspec.implementations.arrow.HadoopFileSystem", + "err": "pyarrow and local java libraries required for HDFS", + }, + "hf": { + "class": "huggingface_hub.HfFileSystem", + "err": "Install huggingface_hub to access HfFileSystem", + }, + "http": { + "class": "fsspec.implementations.http.HTTPFileSystem", + "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed', + }, + "https": { + "class": "fsspec.implementations.http.HTTPFileSystem", + "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed', + }, + "jlab": { + "class": "fsspec.implementations.jupyter.JupyterFileSystem", + "err": "Jupyter FS requires requests to be installed", + }, + "jupyter": { + "class": "fsspec.implementations.jupyter.JupyterFileSystem", + "err": "Jupyter FS requires requests to be installed", + }, + "lakefs": { + "class": "lakefs_spec.LakeFSFileSystem", + "err": "Please install lakefs-spec to access LakeFSFileSystem", + }, + "libarchive": { + "class": "fsspec.implementations.libarchive.LibArchiveFileSystem", + "err": "LibArchive requires to be installed", + }, + "local": {"class": "fsspec.implementations.local.LocalFileSystem"}, + "memory": {"class": "fsspec.implementations.memory.MemoryFileSystem"}, + "oci": { + "class": "ocifs.OCIFileSystem", + "err": "Install ocifs to access OCI Object Storage", + }, + "ocilake": { + "class": "ocifs.OCIFileSystem", + "err": "Install ocifs to access OCI Data Lake", + }, + "oss": { + "class": "ossfs.OSSFileSystem", + "err": "Install ossfs to access Alibaba Object Storage System", + }, + "pyscript": { + "class": "pyscript_fsspec_client.client.PyscriptFileSystem", + "err": "Install requests (cpython) or run in pyscript", + }, + "reference": {"class": "fsspec.implementations.reference.ReferenceFileSystem"}, + "root": { + "class": "fsspec_xrootd.XRootDFileSystem", + "err": ( + "Install fsspec-xrootd to access xrootd storage system. " + "Note: 'root' is the protocol name for xrootd storage systems, " + "not referring to root directories" + ), + }, + "s3": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"}, + "s3a": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"}, + "sftp": { + "class": "fsspec.implementations.sftp.SFTPFileSystem", + "err": 'SFTPFileSystem requires "paramiko" to be installed', + }, + "simplecache": {"class": "fsspec.implementations.cached.SimpleCacheFileSystem"}, + "smb": { + "class": "fsspec.implementations.smb.SMBFileSystem", + "err": 'SMB requires "smbprotocol" or "smbprotocol[kerberos]" installed', + }, + "ssh": { + "class": "fsspec.implementations.sftp.SFTPFileSystem", + "err": 'SFTPFileSystem requires "paramiko" to be installed', + }, + "tar": {"class": "fsspec.implementations.tar.TarFileSystem"}, + "tos": { + "class": "tosfs.TosFileSystem", + "err": "Install tosfs to access ByteDance volcano engine Tinder Object Storage", + }, + "tosfs": { + "class": "tosfs.TosFileSystem", + "err": "Install tosfs to access ByteDance volcano engine Tinder Object Storage", + }, + "wandb": {"class": "wandbfs.WandbFS", "err": "Install wandbfs to access wandb"}, + "webdav": { + "class": "webdav4.fsspec.WebdavFileSystem", + "err": "Install webdav4 to access WebDAV", + }, + "webhdfs": { + "class": "fsspec.implementations.webhdfs.WebHDFS", + "err": 'webHDFS access requires "requests" to be installed', + }, + "zip": {"class": "fsspec.implementations.zip.ZipFileSystem"}, +} + +assert list(known_implementations) == sorted(known_implementations), ( + "Not in alphabetical order" +) + + +def get_filesystem_class(protocol): + """Fetch named protocol implementation from the registry + + The dict ``known_implementations`` maps protocol names to the locations + of classes implementing the corresponding file-system. When used for the + first time, appropriate imports will happen and the class will be placed in + the registry. All subsequent calls will fetch directly from the registry. + + Some protocol implementations require additional dependencies, and so the + import may fail. In this case, the string in the "err" field of the + ``known_implementations`` will be given as the error message. + """ + if not protocol: + protocol = default + + if protocol not in registry: + if protocol not in known_implementations: + raise ValueError(f"Protocol not known: {protocol}") + bit = known_implementations[protocol] + try: + register_implementation(protocol, _import_class(bit["class"])) + except ImportError as e: + raise ImportError(bit.get("err")) from e + cls = registry[protocol] + if getattr(cls, "protocol", None) in ("abstract", None): + cls.protocol = protocol + + return cls + + +s3_msg = """Your installed version of s3fs is very old and known to cause +severe performance issues, see also https://github.com/dask/dask/issues/10276 + +To fix, you should specify a lower version bound on s3fs, or +update the current installation. +""" + + +def _import_class(fqp: str): + """Take a fully-qualified path and return the imported class or identifier. + + ``fqp`` is of the form "package.module.klass" or + "package.module:subobject.klass". + + Warnings + -------- + This can import arbitrary modules. Make sure you haven't installed any modules + that may execute malicious code at import time. + """ + if ":" in fqp: + mod, name = fqp.rsplit(":", 1) + else: + mod, name = fqp.rsplit(".", 1) + + is_s3 = mod == "s3fs" + mod = importlib.import_module(mod) + if is_s3 and mod.__version__.split(".") < ["0", "5"]: + warnings.warn(s3_msg) + for part in name.split("."): + mod = getattr(mod, part) + + if not isinstance(mod, type): + raise TypeError(f"{fqp} is not a class") + + return mod + + +def filesystem(protocol, **storage_options): + """Instantiate filesystems for given protocol and arguments + + ``storage_options`` are specific to the protocol being chosen, and are + passed directly to the class. + """ + if protocol == "arrow_hdfs": + warnings.warn( + "The 'arrow_hdfs' protocol has been deprecated and will be " + "removed in the future. Specify it as 'hdfs'.", + DeprecationWarning, + ) + + cls = get_filesystem_class(protocol) + return cls(**storage_options) + + +def available_protocols(): + """Return a list of the implemented protocols. + + Note that any given protocol may require extra packages to be importable. + """ + return list(known_implementations) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/spec.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/spec.py new file mode 100644 index 0000000000000000000000000000000000000000..5f6f9a10441c12ef8db4870c4e5dc72262037c6e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/spec.py @@ -0,0 +1,2270 @@ +from __future__ import annotations + +import io +import json +import logging +import os +import threading +import warnings +import weakref +from errno import ESPIPE +from glob import has_magic +from hashlib import sha256 +from typing import Any, ClassVar + +from .callbacks import DEFAULT_CALLBACK +from .config import apply_config, conf +from .dircache import DirCache +from .transaction import Transaction +from .utils import ( + _unstrip_protocol, + glob_translate, + isfilelike, + other_paths, + read_block, + stringify_path, + tokenize, +) + +logger = logging.getLogger("fsspec") + + +def make_instance(cls, args, kwargs): + return cls(*args, **kwargs) + + +class _Cached(type): + """ + Metaclass for caching file system instances. + + Notes + ----- + Instances are cached according to + + * The values of the class attributes listed in `_extra_tokenize_attributes` + * The arguments passed to ``__init__``. + + This creates an additional reference to the filesystem, which prevents the + filesystem from being garbage collected when all *user* references go away. + A call to the :meth:`AbstractFileSystem.clear_instance_cache` must *also* + be made for a filesystem instance to be garbage collected. + """ + + def __init__(cls, *args, **kwargs): + super().__init__(*args, **kwargs) + # Note: we intentionally create a reference here, to avoid garbage + # collecting instances when all other references are gone. To really + # delete a FileSystem, the cache must be cleared. + if conf.get("weakref_instance_cache"): # pragma: no cover + # debug option for analysing fork/spawn conditions + cls._cache = weakref.WeakValueDictionary() + else: + cls._cache = {} + cls._pid = os.getpid() + + def __call__(cls, *args, **kwargs): + kwargs = apply_config(cls, kwargs) + extra_tokens = tuple( + getattr(cls, attr, None) for attr in cls._extra_tokenize_attributes + ) + token = tokenize( + cls, cls._pid, threading.get_ident(), *args, *extra_tokens, **kwargs + ) + skip = kwargs.pop("skip_instance_cache", False) + if os.getpid() != cls._pid: + cls._cache.clear() + cls._pid = os.getpid() + if not skip and cls.cachable and token in cls._cache: + cls._latest = token + return cls._cache[token] + else: + obj = super().__call__(*args, **kwargs) + # Setting _fs_token here causes some static linters to complain. + obj._fs_token_ = token + obj.storage_args = args + obj.storage_options = kwargs + if obj.async_impl and obj.mirror_sync_methods: + from .asyn import mirror_sync_methods + + mirror_sync_methods(obj) + + if cls.cachable and not skip: + cls._latest = token + cls._cache[token] = obj + return obj + + +class AbstractFileSystem(metaclass=_Cached): + """ + An abstract super-class for pythonic file-systems + + Implementations are expected to be compatible with or, better, subclass + from here. + """ + + cachable = True # this class can be cached, instances reused + _cached = False + blocksize = 2**22 + sep = "/" + protocol: ClassVar[str | tuple[str, ...]] = "abstract" + _latest = None + async_impl = False + mirror_sync_methods = False + root_marker = "" # For some FSs, may require leading '/' or other character + transaction_type = Transaction + + #: Extra *class attributes* that should be considered when hashing. + _extra_tokenize_attributes = () + + # Set by _Cached metaclass + storage_args: tuple[Any, ...] + storage_options: dict[str, Any] + + def __init__(self, *args, **storage_options): + """Create and configure file-system instance + + Instances may be cachable, so if similar enough arguments are seen + a new instance is not required. The token attribute exists to allow + implementations to cache instances if they wish. + + A reasonable default should be provided if there are no arguments. + + Subclasses should call this method. + + Parameters + ---------- + use_listings_cache, listings_expiry_time, max_paths: + passed to ``DirCache``, if the implementation supports + directory listing caching. Pass use_listings_cache=False + to disable such caching. + skip_instance_cache: bool + If this is a cachable implementation, pass True here to force + creating a new instance even if a matching instance exists, and prevent + storing this instance. + asynchronous: bool + loop: asyncio-compatible IOLoop or None + """ + if self._cached: + # reusing instance, don't change + return + self._cached = True + self._intrans = False + self._transaction = None + self._invalidated_caches_in_transaction = [] + self.dircache = DirCache(**storage_options) + + if storage_options.pop("add_docs", None): + warnings.warn("add_docs is no longer supported.", FutureWarning) + + if storage_options.pop("add_aliases", None): + warnings.warn("add_aliases has been removed.", FutureWarning) + # This is set in _Cached + self._fs_token_ = None + + @property + def fsid(self): + """Persistent filesystem id that can be used to compare filesystems + across sessions. + """ + raise NotImplementedError + + @property + def _fs_token(self): + return self._fs_token_ + + def __dask_tokenize__(self): + return self._fs_token + + def __hash__(self): + return int(self._fs_token, 16) + + def __eq__(self, other): + return isinstance(other, type(self)) and self._fs_token == other._fs_token + + def __reduce__(self): + return make_instance, (type(self), self.storage_args, self.storage_options) + + @classmethod + def _strip_protocol(cls, path): + """Turn path from fully-qualified to file-system-specific + + May require FS-specific handling, e.g., for relative paths or links. + """ + if isinstance(path, list): + return [cls._strip_protocol(p) for p in path] + path = stringify_path(path) + protos = (cls.protocol,) if isinstance(cls.protocol, str) else cls.protocol + for protocol in protos: + if path.startswith(protocol + "://"): + path = path[len(protocol) + 3 :] + elif path.startswith(protocol + "::"): + path = path[len(protocol) + 2 :] + path = path.rstrip("/") + # use of root_marker to make minimum required path, e.g., "/" + return path or cls.root_marker + + def unstrip_protocol(self, name: str) -> str: + """Format FS-specific path to generic, including protocol""" + protos = (self.protocol,) if isinstance(self.protocol, str) else self.protocol + for protocol in protos: + if name.startswith(f"{protocol}://"): + return name + return f"{protos[0]}://{name}" + + @staticmethod + def _get_kwargs_from_urls(path): + """If kwargs can be encoded in the paths, extract them here + + This should happen before instantiation of the class; incoming paths + then should be amended to strip the options in methods. + + Examples may look like an sftp path "sftp://user@host:/my/path", where + the user and host should become kwargs and later get stripped. + """ + # by default, nothing happens + return {} + + @classmethod + def current(cls): + """Return the most recently instantiated FileSystem + + If no instance has been created, then create one with defaults + """ + if cls._latest in cls._cache: + return cls._cache[cls._latest] + return cls() + + @property + def transaction(self): + """A context within which files are committed together upon exit + + Requires the file class to implement `.commit()` and `.discard()` + for the normal and exception cases. + """ + if self._transaction is None: + self._transaction = self.transaction_type(self) + return self._transaction + + def start_transaction(self): + """Begin write transaction for deferring files, non-context version""" + self._intrans = True + self._transaction = self.transaction_type(self) + return self.transaction + + def end_transaction(self): + """Finish write transaction, non-context version""" + self.transaction.complete() + self._transaction = None + # The invalid cache must be cleared after the transaction is completed. + for path in self._invalidated_caches_in_transaction: + self.invalidate_cache(path) + self._invalidated_caches_in_transaction.clear() + + def invalidate_cache(self, path=None): + """ + Discard any cached directory information + + Parameters + ---------- + path: string or None + If None, clear all listings cached else listings at or under given + path. + """ + # Not necessary to implement invalidation mechanism, may have no cache. + # But if have, you should call this method of parent class from your + # subclass to ensure expiring caches after transacations correctly. + # See the implementation of FTPFileSystem in ftp.py + if self._intrans: + self._invalidated_caches_in_transaction.append(path) + + def mkdir(self, path, create_parents=True, **kwargs): + """ + Create directory entry at path + + For systems that don't have true directories, may create an for + this instance only and not touch the real filesystem + + Parameters + ---------- + path: str + location + create_parents: bool + if True, this is equivalent to ``makedirs`` + kwargs: + may be permissions, etc. + """ + pass # not necessary to implement, may not have directories + + def makedirs(self, path, exist_ok=False): + """Recursively make directories + + Creates directory at path and any intervening required directories. + Raises exception if, for instance, the path already exists but is a + file. + + Parameters + ---------- + path: str + leaf directory name + exist_ok: bool (False) + If False, will error if the target already exists + """ + pass # not necessary to implement, may not have directories + + def rmdir(self, path): + """Remove a directory, if empty""" + pass # not necessary to implement, may not have directories + + def ls(self, path, detail=True, **kwargs): + """List objects at path. + + This should include subdirectories and files at that location. The + difference between a file and a directory must be clear when details + are requested. + + The specific keys, or perhaps a FileInfo class, or similar, is TBD, + but must be consistent across implementations. + Must include: + + - full path to the entry (without protocol) + - size of the entry, in bytes. If the value cannot be determined, will + be ``None``. + - type of entry, "file", "directory" or other + + Additional information + may be present, appropriate to the file-system, e.g., generation, + checksum, etc. + + May use refresh=True|False to allow use of self._ls_from_cache to + check for a saved listing and avoid calling the backend. This would be + common where listing may be expensive. + + Parameters + ---------- + path: str + detail: bool + if True, gives a list of dictionaries, where each is the same as + the result of ``info(path)``. If False, gives a list of paths + (str). + kwargs: may have additional backend-specific options, such as version + information + + Returns + ------- + List of strings if detail is False, or list of directory information + dicts if detail is True. + """ + raise NotImplementedError + + def _ls_from_cache(self, path): + """Check cache for listing + + Returns listing, if found (may be empty list for a directly that exists + but contains nothing), None if not in cache. + """ + parent = self._parent(path) + try: + return self.dircache[path.rstrip("/")] + except KeyError: + pass + try: + files = [ + f + for f in self.dircache[parent] + if f["name"] == path + or (f["name"] == path.rstrip("/") and f["type"] == "directory") + ] + if len(files) == 0: + # parent dir was listed but did not contain this file + raise FileNotFoundError(path) + return files + except KeyError: + pass + + def walk(self, path, maxdepth=None, topdown=True, on_error="omit", **kwargs): + """Return all files under the given path. + + List all files, recursing into subdirectories; output is iterator-style, + like ``os.walk()``. For a simple list of files, ``find()`` is available. + + When topdown is True, the caller can modify the dirnames list in-place (perhaps + using del or slice assignment), and walk() will + only recurse into the subdirectories whose names remain in dirnames; + this can be used to prune the search, impose a specific order of visiting, + or even to inform walk() about directories the caller creates or renames before + it resumes walk() again. + Modifying dirnames when topdown is False has no effect. (see os.walk) + + Note that the "files" outputted will include anything that is not + a directory, such as links. + + Parameters + ---------- + path: str + Root to recurse into + maxdepth: int + Maximum recursion depth. None means limitless, but not recommended + on link-based file-systems. + topdown: bool (True) + Whether to walk the directory tree from the top downwards or from + the bottom upwards. + on_error: "omit", "raise", a callable + if omit (default), path with exception will simply be empty; + If raise, an underlying exception will be raised; + if callable, it will be called with a single OSError instance as argument + kwargs: passed to ``ls`` + """ + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + path = self._strip_protocol(path) + full_dirs = {} + dirs = {} + files = {} + + detail = kwargs.pop("detail", False) + try: + listing = self.ls(path, detail=True, **kwargs) + except (FileNotFoundError, OSError) as e: + if on_error == "raise": + raise + if callable(on_error): + on_error(e) + return + + for info in listing: + # each info name must be at least [path]/part , but here + # we check also for names like [path]/part/ + pathname = info["name"].rstrip("/") + name = pathname.rsplit("/", 1)[-1] + if info["type"] == "directory" and pathname != path: + # do not include "self" path + full_dirs[name] = pathname + dirs[name] = info + elif pathname == path: + # file-like with same name as give path + files[""] = info + else: + files[name] = info + + if not detail: + dirs = list(dirs) + files = list(files) + + if topdown: + # Yield before recursion if walking top down + yield path, dirs, files + + if maxdepth is not None: + maxdepth -= 1 + if maxdepth < 1: + if not topdown: + yield path, dirs, files + return + + for d in dirs: + yield from self.walk( + full_dirs[d], + maxdepth=maxdepth, + detail=detail, + topdown=topdown, + **kwargs, + ) + + if not topdown: + # Yield after recursion if walking bottom up + yield path, dirs, files + + def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs): + """List all files below path. + + Like posix ``find`` command without conditions + + Parameters + ---------- + path : str + maxdepth: int or None + If not None, the maximum number of levels to descend + withdirs: bool + Whether to include directory paths in the output. This is True + when used by glob, but users usually only want files. + kwargs are passed to ``ls``. + """ + # TODO: allow equivalent of -name parameter + path = self._strip_protocol(path) + out = {} + + # Add the root directory if withdirs is requested + # This is needed for posix glob compliance + if withdirs and path != "" and self.isdir(path): + out[path] = self.info(path) + + for _, dirs, files in self.walk(path, maxdepth, detail=True, **kwargs): + if withdirs: + files.update(dirs) + out.update({info["name"]: info for name, info in files.items()}) + if not out and self.isfile(path): + # walk works on directories, but find should also return [path] + # when path happens to be a file + out[path] = {} + names = sorted(out) + if not detail: + return names + else: + return {name: out[name] for name in names} + + def du(self, path, total=True, maxdepth=None, withdirs=False, **kwargs): + """Space used by files and optionally directories within a path + + Directory size does not include the size of its contents. + + Parameters + ---------- + path: str + total: bool + Whether to sum all the file sizes + maxdepth: int or None + Maximum number of directory levels to descend, None for unlimited. + withdirs: bool + Whether to include directory paths in the output. + kwargs: passed to ``find`` + + Returns + ------- + Dict of {path: size} if total=False, or int otherwise, where numbers + refer to bytes used. + """ + sizes = {} + if withdirs and self.isdir(path): + # Include top-level directory in output + info = self.info(path) + sizes[info["name"]] = info["size"] + for f in self.find(path, maxdepth=maxdepth, withdirs=withdirs, **kwargs): + info = self.info(f) + sizes[info["name"]] = info["size"] + if total: + return sum(sizes.values()) + else: + return sizes + + def glob(self, path, maxdepth=None, **kwargs): + """Find files by glob-matching. + + Pattern matching capabilities for finding files that match the given pattern. + + Parameters + ---------- + path: str + The glob pattern to match against + maxdepth: int or None + Maximum depth for ``'**'`` patterns. Applied on the first ``'**'`` found. + Must be at least 1 if provided. + kwargs: + Additional arguments passed to ``find`` (e.g., detail=True) + + Returns + ------- + List of matched paths, or dict of paths and their info if detail=True + + Notes + ----- + Supported patterns: + - '*': Matches any sequence of characters within a single directory level + - ``'**'``: Matches any number of directory levels (must be an entire path component) + - '?': Matches exactly one character + - '[abc]': Matches any character in the set + - '[a-z]': Matches any character in the range + - '[!abc]': Matches any character NOT in the set + + Special behaviors: + - If the path ends with '/', only folders are returned + - Consecutive '*' characters are compressed into a single '*' + - Empty brackets '[]' never match anything + - Negated empty brackets '[!]' match any single character + - Special characters in character classes are escaped properly + + Limitations: + - ``'**'`` must be a complete path component (e.g., ``'a/**/b'``, not ``'a**b'``) + - No brace expansion ('{a,b}.txt') + - No extended glob patterns ('+(pattern)', '!(pattern)') + """ + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + import re + + seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,) + ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash + path = self._strip_protocol(path) + append_slash_to_dirname = ends_with_sep or path.endswith( + tuple(sep + "**" for sep in seps) + ) + idx_star = path.find("*") if path.find("*") >= 0 else len(path) + idx_qmark = path.find("?") if path.find("?") >= 0 else len(path) + idx_brace = path.find("[") if path.find("[") >= 0 else len(path) + + min_idx = min(idx_star, idx_qmark, idx_brace) + + detail = kwargs.pop("detail", False) + + if not has_magic(path): + if self.exists(path, **kwargs): + if not detail: + return [path] + else: + return {path: self.info(path, **kwargs)} + else: + if not detail: + return [] # glob of non-existent returns empty + else: + return {} + elif "/" in path[:min_idx]: + min_idx = path[:min_idx].rindex("/") + root = path[: min_idx + 1] + depth = path[min_idx + 1 :].count("/") + 1 + else: + root = "" + depth = path[min_idx + 1 :].count("/") + 1 + + if "**" in path: + if maxdepth is not None: + idx_double_stars = path.find("**") + depth_double_stars = path[idx_double_stars:].count("/") + 1 + depth = depth - depth_double_stars + maxdepth + else: + depth = None + + allpaths = self.find(root, maxdepth=depth, withdirs=True, detail=True, **kwargs) + + pattern = glob_translate(path + ("/" if ends_with_sep else "")) + pattern = re.compile(pattern) + + out = { + p: info + for p, info in sorted(allpaths.items()) + if pattern.match( + p + "/" + if append_slash_to_dirname and info["type"] == "directory" + else p + ) + } + + if detail: + return out + else: + return list(out) + + def exists(self, path, **kwargs): + """Is there a file at the given path""" + try: + self.info(path, **kwargs) + return True + except: # noqa: E722 + # any exception allowed bar FileNotFoundError? + return False + + def lexists(self, path, **kwargs): + """If there is a file at the given path (including + broken links)""" + return self.exists(path) + + def info(self, path, **kwargs): + """Give details of entry at path + + Returns a single dictionary, with exactly the same information as ``ls`` + would with ``detail=True``. + + The default implementation calls ls and could be overridden by a + shortcut. kwargs are passed on to ```ls()``. + + Some file systems might not be able to measure the file's size, in + which case, the returned dict will include ``'size': None``. + + Returns + ------- + dict with keys: name (full path in the FS), size (in bytes), type (file, + directory, or something else) and other FS-specific keys. + """ + path = self._strip_protocol(path) + out = self.ls(self._parent(path), detail=True, **kwargs) + out = [o for o in out if o["name"].rstrip("/") == path] + if out: + return out[0] + out = self.ls(path, detail=True, **kwargs) + path = path.rstrip("/") + out1 = [o for o in out if o["name"].rstrip("/") == path] + if len(out1) == 1: + if "size" not in out1[0]: + out1[0]["size"] = None + return out1[0] + elif len(out1) > 1 or out: + return {"name": path, "size": 0, "type": "directory"} + else: + raise FileNotFoundError(path) + + def checksum(self, path): + """Unique value for current version of file + + If the checksum is the same from one moment to another, the contents + are guaranteed to be the same. If the checksum changes, the contents + *might* have changed. + + This should normally be overridden; default will probably capture + creation/modification timestamp (which would be good) or maybe + access timestamp (which would be bad) + """ + return int(tokenize(self.info(path)), 16) + + def size(self, path): + """Size in bytes of file""" + return self.info(path).get("size", None) + + def sizes(self, paths): + """Size in bytes of each file in a list of paths""" + return [self.size(p) for p in paths] + + def isdir(self, path): + """Is this entry directory-like?""" + try: + return self.info(path)["type"] == "directory" + except OSError: + return False + + def isfile(self, path): + """Is this entry file-like?""" + try: + return self.info(path)["type"] == "file" + except: # noqa: E722 + return False + + def read_text(self, path, encoding=None, errors=None, newline=None, **kwargs): + """Get the contents of the file as a string. + + Parameters + ---------- + path: str + URL of file on this filesystems + encoding, errors, newline: same as `open`. + """ + with self.open( + path, + mode="r", + encoding=encoding, + errors=errors, + newline=newline, + **kwargs, + ) as f: + return f.read() + + def write_text( + self, path, value, encoding=None, errors=None, newline=None, **kwargs + ): + """Write the text to the given file. + + An existing file will be overwritten. + + Parameters + ---------- + path: str + URL of file on this filesystems + value: str + Text to write. + encoding, errors, newline: same as `open`. + """ + with self.open( + path, + mode="w", + encoding=encoding, + errors=errors, + newline=newline, + **kwargs, + ) as f: + return f.write(value) + + def cat_file(self, path, start=None, end=None, **kwargs): + """Get the content of a file + + Parameters + ---------- + path: URL of file on this filesystems + start, end: int + Bytes limits of the read. If negative, backwards from end, + like usual python slices. Either can be None for start or + end of file, respectively + kwargs: passed to ``open()``. + """ + # explicitly set buffering off? + with self.open(path, "rb", **kwargs) as f: + if start is not None: + if start >= 0: + f.seek(start) + else: + f.seek(max(0, f.size + start)) + if end is not None: + if end < 0: + end = f.size + end + return f.read(end - f.tell()) + return f.read() + + def pipe_file(self, path, value, mode="overwrite", **kwargs): + """Set the bytes of given file""" + if mode == "create" and self.exists(path): + # non-atomic but simple way; or could use "xb" in open(), which is likely + # not as well supported + raise FileExistsError + with self.open(path, "wb", **kwargs) as f: + f.write(value) + + def pipe(self, path, value=None, **kwargs): + """Put value into path + + (counterpart to ``cat``) + + Parameters + ---------- + path: string or dict(str, bytes) + If a string, a single remote location to put ``value`` bytes; if a dict, + a mapping of {path: bytesvalue}. + value: bytes, optional + If using a single path, these are the bytes to put there. Ignored if + ``path`` is a dict + """ + if isinstance(path, str): + self.pipe_file(self._strip_protocol(path), value, **kwargs) + elif isinstance(path, dict): + for k, v in path.items(): + self.pipe_file(self._strip_protocol(k), v, **kwargs) + else: + raise ValueError("path must be str or dict") + + def cat_ranges( + self, paths, starts, ends, max_gap=None, on_error="return", **kwargs + ): + """Get the contents of byte ranges from one or more files + + Parameters + ---------- + paths: list + A list of of filepaths on this filesystems + starts, ends: int or list + Bytes limits of the read. If using a single int, the same value will be + used to read all the specified files. + """ + if max_gap is not None: + raise NotImplementedError + if not isinstance(paths, list): + raise TypeError + if not isinstance(starts, list): + starts = [starts] * len(paths) + if not isinstance(ends, list): + ends = [ends] * len(paths) + if len(starts) != len(paths) or len(ends) != len(paths): + raise ValueError + out = [] + for p, s, e in zip(paths, starts, ends): + try: + out.append(self.cat_file(p, s, e)) + except Exception as e: + if on_error == "return": + out.append(e) + else: + raise + return out + + def cat(self, path, recursive=False, on_error="raise", **kwargs): + """Fetch (potentially multiple) paths' contents + + Parameters + ---------- + recursive: bool + If True, assume the path(s) are directories, and get all the + contained files + on_error : "raise", "omit", "return" + If raise, an underlying exception will be raised (converted to KeyError + if the type is in self.missing_exceptions); if omit, keys with exception + will simply not be included in the output; if "return", all keys are + included in the output, but the value will be bytes or an exception + instance. + kwargs: passed to cat_file + + Returns + ------- + dict of {path: contents} if there are multiple paths + or the path has been otherwise expanded + """ + paths = self.expand_path(path, recursive=recursive) + if ( + len(paths) > 1 + or isinstance(path, list) + or paths[0] != self._strip_protocol(path) + ): + out = {} + for path in paths: + try: + out[path] = self.cat_file(path, **kwargs) + except Exception as e: + if on_error == "raise": + raise + if on_error == "return": + out[path] = e + return out + else: + return self.cat_file(paths[0], **kwargs) + + def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, outfile=None, **kwargs): + """Copy single remote file to local""" + from .implementations.local import LocalFileSystem + + if isfilelike(lpath): + outfile = lpath + elif self.isdir(rpath): + os.makedirs(lpath, exist_ok=True) + return None + + fs = LocalFileSystem(auto_mkdir=True) + fs.makedirs(fs._parent(lpath), exist_ok=True) + + with self.open(rpath, "rb", **kwargs) as f1: + if outfile is None: + outfile = open(lpath, "wb") + + try: + callback.set_size(getattr(f1, "size", None)) + data = True + while data: + data = f1.read(self.blocksize) + segment_len = outfile.write(data) + if segment_len is None: + segment_len = len(data) + callback.relative_update(segment_len) + finally: + if not isfilelike(lpath): + outfile.close() + + def get( + self, + rpath, + lpath, + recursive=False, + callback=DEFAULT_CALLBACK, + maxdepth=None, + **kwargs, + ): + """Copy file(s) to local. + + Copies a specific file or tree of files (if recursive=True). If lpath + ends with a "/", it will be assumed to be a directory, and target files + will go within. Can submit a list of paths, which may be glob-patterns + and will be expanded. + + Calls get_file for each source. + """ + if isinstance(lpath, list) and isinstance(rpath, list): + # No need to expand paths when both source and destination + # are provided as lists + rpaths = rpath + lpaths = lpath + else: + from .implementations.local import ( + LocalFileSystem, + make_path_posix, + trailing_sep, + ) + + source_is_str = isinstance(rpath, str) + rpaths = self.expand_path(rpath, recursive=recursive, maxdepth=maxdepth) + if source_is_str and (not recursive or maxdepth is not None): + # Non-recursive glob does not copy directories + rpaths = [p for p in rpaths if not (trailing_sep(p) or self.isdir(p))] + if not rpaths: + return + + if isinstance(lpath, str): + lpath = make_path_posix(lpath) + + source_is_file = len(rpaths) == 1 + dest_is_dir = isinstance(lpath, str) and ( + trailing_sep(lpath) or LocalFileSystem().isdir(lpath) + ) + + exists = source_is_str and ( + (has_magic(rpath) and source_is_file) + or (not has_magic(rpath) and dest_is_dir and not trailing_sep(rpath)) + ) + lpaths = other_paths( + rpaths, + lpath, + exists=exists, + flatten=not source_is_str, + ) + + callback.set_size(len(lpaths)) + for lpath, rpath in callback.wrap(zip(lpaths, rpaths)): + with callback.branched(rpath, lpath) as child: + self.get_file(rpath, lpath, callback=child, **kwargs) + + def put_file( + self, lpath, rpath, callback=DEFAULT_CALLBACK, mode="overwrite", **kwargs + ): + """Copy single file to remote""" + if mode == "create" and self.exists(rpath): + raise FileExistsError + if os.path.isdir(lpath): + self.makedirs(rpath, exist_ok=True) + return None + + with open(lpath, "rb") as f1: + size = f1.seek(0, 2) + callback.set_size(size) + f1.seek(0) + + self.mkdirs(self._parent(os.fspath(rpath)), exist_ok=True) + with self.open(rpath, "wb", **kwargs) as f2: + while f1.tell() < size: + data = f1.read(self.blocksize) + segment_len = f2.write(data) + if segment_len is None: + segment_len = len(data) + callback.relative_update(segment_len) + + def put( + self, + lpath, + rpath, + recursive=False, + callback=DEFAULT_CALLBACK, + maxdepth=None, + **kwargs, + ): + """Copy file(s) from local. + + Copies a specific file or tree of files (if recursive=True). If rpath + ends with a "/", it will be assumed to be a directory, and target files + will go within. + + Calls put_file for each source. + """ + if isinstance(lpath, list) and isinstance(rpath, list): + # No need to expand paths when both source and destination + # are provided as lists + rpaths = rpath + lpaths = lpath + else: + from .implementations.local import ( + LocalFileSystem, + make_path_posix, + trailing_sep, + ) + + source_is_str = isinstance(lpath, str) + if source_is_str: + lpath = make_path_posix(lpath) + fs = LocalFileSystem() + lpaths = fs.expand_path(lpath, recursive=recursive, maxdepth=maxdepth) + if source_is_str and (not recursive or maxdepth is not None): + # Non-recursive glob does not copy directories + lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))] + if not lpaths: + return + + source_is_file = len(lpaths) == 1 + dest_is_dir = isinstance(rpath, str) and ( + trailing_sep(rpath) or self.isdir(rpath) + ) + + rpath = ( + self._strip_protocol(rpath) + if isinstance(rpath, str) + else [self._strip_protocol(p) for p in rpath] + ) + exists = source_is_str and ( + (has_magic(lpath) and source_is_file) + or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath)) + ) + rpaths = other_paths( + lpaths, + rpath, + exists=exists, + flatten=not source_is_str, + ) + + callback.set_size(len(rpaths)) + for lpath, rpath in callback.wrap(zip(lpaths, rpaths)): + with callback.branched(lpath, rpath) as child: + self.put_file(lpath, rpath, callback=child, **kwargs) + + def head(self, path, size=1024): + """Get the first ``size`` bytes from file""" + with self.open(path, "rb") as f: + return f.read(size) + + def tail(self, path, size=1024): + """Get the last ``size`` bytes from file""" + with self.open(path, "rb") as f: + f.seek(max(-size, -f.size), 2) + return f.read() + + def cp_file(self, path1, path2, **kwargs): + raise NotImplementedError + + def copy( + self, path1, path2, recursive=False, maxdepth=None, on_error=None, **kwargs + ): + """Copy within two locations in the filesystem + + on_error : "raise", "ignore" + If raise, any not-found exceptions will be raised; if ignore any + not-found exceptions will cause the path to be skipped; defaults to + raise unless recursive is true, where the default is ignore + """ + if on_error is None and recursive: + on_error = "ignore" + elif on_error is None: + on_error = "raise" + + if isinstance(path1, list) and isinstance(path2, list): + # No need to expand paths when both source and destination + # are provided as lists + paths1 = path1 + paths2 = path2 + else: + from .implementations.local import trailing_sep + + source_is_str = isinstance(path1, str) + paths1 = self.expand_path(path1, recursive=recursive, maxdepth=maxdepth) + if source_is_str and (not recursive or maxdepth is not None): + # Non-recursive glob does not copy directories + paths1 = [p for p in paths1 if not (trailing_sep(p) or self.isdir(p))] + if not paths1: + return + + source_is_file = len(paths1) == 1 + dest_is_dir = isinstance(path2, str) and ( + trailing_sep(path2) or self.isdir(path2) + ) + + exists = source_is_str and ( + (has_magic(path1) and source_is_file) + or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1)) + ) + paths2 = other_paths( + paths1, + path2, + exists=exists, + flatten=not source_is_str, + ) + + for p1, p2 in zip(paths1, paths2): + try: + self.cp_file(p1, p2, **kwargs) + except FileNotFoundError: + if on_error == "raise": + raise + + def expand_path(self, path, recursive=False, maxdepth=None, **kwargs): + """Turn one or more globs or directories into a list of all matching paths + to files or directories. + + kwargs are passed to ``glob`` or ``find``, which may in turn call ``ls`` + """ + + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + if isinstance(path, (str, os.PathLike)): + out = self.expand_path([path], recursive, maxdepth) + else: + out = set() + path = [self._strip_protocol(p) for p in path] + for p in path: + if has_magic(p): + bit = set(self.glob(p, maxdepth=maxdepth, **kwargs)) + out |= bit + if recursive: + # glob call above expanded one depth so if maxdepth is defined + # then decrement it in expand_path call below. If it is zero + # after decrementing then avoid expand_path call. + if maxdepth is not None and maxdepth <= 1: + continue + out |= set( + self.expand_path( + list(bit), + recursive=recursive, + maxdepth=maxdepth - 1 if maxdepth is not None else None, + **kwargs, + ) + ) + continue + elif recursive: + rec = set( + self.find( + p, maxdepth=maxdepth, withdirs=True, detail=False, **kwargs + ) + ) + out |= rec + if p not in out and (recursive is False or self.exists(p)): + # should only check once, for the root + out.add(p) + if not out: + raise FileNotFoundError(path) + return sorted(out) + + def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs): + """Move file(s) from one location to another""" + if path1 == path2: + logger.debug("%s mv: The paths are the same, so no files were moved.", self) + else: + # explicitly raise exception to prevent data corruption + self.copy( + path1, path2, recursive=recursive, maxdepth=maxdepth, onerror="raise" + ) + self.rm(path1, recursive=recursive) + + def rm_file(self, path): + """Delete a file""" + self._rm(path) + + def _rm(self, path): + """Delete one file""" + # this is the old name for the method, prefer rm_file + raise NotImplementedError + + def rm(self, path, recursive=False, maxdepth=None): + """Delete files. + + Parameters + ---------- + path: str or list of str + File(s) to delete. + recursive: bool + If file(s) are directories, recursively delete contents and then + also remove the directory + maxdepth: int or None + Depth to pass to walk for finding files to delete, if recursive. + If None, there will be no limit and infinite recursion may be + possible. + """ + path = self.expand_path(path, recursive=recursive, maxdepth=maxdepth) + for p in reversed(path): + self.rm_file(p) + + @classmethod + def _parent(cls, path): + path = cls._strip_protocol(path) + if "/" in path: + parent = path.rsplit("/", 1)[0].lstrip(cls.root_marker) + return cls.root_marker + parent + else: + return cls.root_marker + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + """Return raw bytes-mode file-like from the file-system""" + return AbstractBufferedFile( + self, + path, + mode, + block_size, + autocommit, + cache_options=cache_options, + **kwargs, + ) + + def open( + self, + path, + mode="rb", + block_size=None, + cache_options=None, + compression=None, + **kwargs, + ): + """ + Return a file-like object from the filesystem + + The resultant instance must function correctly in a context ``with`` + block. + + Parameters + ---------- + path: str + Target file + mode: str like 'rb', 'w' + See builtin ``open()`` + Mode "x" (exclusive write) may be implemented by the backend. Even if + it is, whether it is checked up front or on commit, and whether it is + atomic is implementation-dependent. + block_size: int + Some indication of buffering - this is a value in bytes + cache_options : dict, optional + Extra arguments to pass through to the cache. + compression: string or None + If given, open file using compression codec. Can either be a compression + name (a key in ``fsspec.compression.compr``) or "infer" to guess the + compression from the filename suffix. + encoding, errors, newline: passed on to TextIOWrapper for text mode + """ + import io + + path = self._strip_protocol(path) + if "b" not in mode: + mode = mode.replace("t", "") + "b" + + text_kwargs = { + k: kwargs.pop(k) + for k in ["encoding", "errors", "newline"] + if k in kwargs + } + return io.TextIOWrapper( + self.open( + path, + mode, + block_size=block_size, + cache_options=cache_options, + compression=compression, + **kwargs, + ), + **text_kwargs, + ) + else: + ac = kwargs.pop("autocommit", not self._intrans) + f = self._open( + path, + mode=mode, + block_size=block_size, + autocommit=ac, + cache_options=cache_options, + **kwargs, + ) + if compression is not None: + from fsspec.compression import compr + from fsspec.core import get_compression + + compression = get_compression(path, compression) + compress = compr[compression] + f = compress(f, mode=mode[0]) + + if not ac and "r" not in mode: + self.transaction.files.append(f) + return f + + def touch(self, path, truncate=True, **kwargs): + """Create empty file, or update timestamp + + Parameters + ---------- + path: str + file location + truncate: bool + If True, always set file size to 0; if False, update timestamp and + leave file unchanged, if backend allows this + """ + if truncate or not self.exists(path): + with self.open(path, "wb", **kwargs): + pass + else: + raise NotImplementedError # update timestamp, if possible + + def ukey(self, path): + """Hash of file properties, to tell if it has changed""" + return sha256(str(self.info(path)).encode()).hexdigest() + + def read_block(self, fn, offset, length, delimiter=None): + """Read a block of bytes from + + Starting at ``offset`` of the file, read ``length`` bytes. If + ``delimiter`` is set then we ensure that the read starts and stops at + delimiter boundaries that follow the locations ``offset`` and ``offset + + length``. If ``offset`` is zero then we start at zero. The + bytestring returned WILL include the end delimiter string. + + If offset+length is beyond the eof, reads to eof. + + Parameters + ---------- + fn: string + Path to filename + offset: int + Byte offset to start read + length: int + Number of bytes to read. If None, read to end. + delimiter: bytes (optional) + Ensure reading starts and stops at delimiter bytestring + + Examples + -------- + >>> fs.read_block('data/file.csv', 0, 13) # doctest: +SKIP + b'Alice, 100\\nBo' + >>> fs.read_block('data/file.csv', 0, 13, delimiter=b'\\n') # doctest: +SKIP + b'Alice, 100\\nBob, 200\\n' + + Use ``length=None`` to read to the end of the file. + >>> fs.read_block('data/file.csv', 0, None, delimiter=b'\\n') # doctest: +SKIP + b'Alice, 100\\nBob, 200\\nCharlie, 300' + + See Also + -------- + :func:`fsspec.utils.read_block` + """ + with self.open(fn, "rb") as f: + size = f.size + if length is None: + length = size + if size is not None and offset + length > size: + length = size - offset + return read_block(f, offset, length, delimiter) + + def to_json(self, *, include_password: bool = True) -> str: + """ + JSON representation of this filesystem instance. + + Parameters + ---------- + include_password: bool, default True + Whether to include the password (if any) in the output. + + Returns + ------- + JSON string with keys ``cls`` (the python location of this class), + protocol (text name of this class's protocol, first one in case of + multiple), ``args`` (positional args, usually empty), and all other + keyword arguments as their own keys. + + Warnings + -------- + Serialized filesystems may contain sensitive information which have been + passed to the constructor, such as passwords and tokens. Make sure you + store and send them in a secure environment! + """ + from .json import FilesystemJSONEncoder + + return json.dumps( + self, + cls=type( + "_FilesystemJSONEncoder", + (FilesystemJSONEncoder,), + {"include_password": include_password}, + ), + ) + + @staticmethod + def from_json(blob: str) -> AbstractFileSystem: + """ + Recreate a filesystem instance from JSON representation. + + See ``.to_json()`` for the expected structure of the input. + + Parameters + ---------- + blob: str + + Returns + ------- + file system instance, not necessarily of this particular class. + + Warnings + -------- + This can import arbitrary modules (as determined by the ``cls`` key). + Make sure you haven't installed any modules that may execute malicious code + at import time. + """ + from .json import FilesystemJSONDecoder + + return json.loads(blob, cls=FilesystemJSONDecoder) + + def to_dict(self, *, include_password: bool = True) -> dict[str, Any]: + """ + JSON-serializable dictionary representation of this filesystem instance. + + Parameters + ---------- + include_password: bool, default True + Whether to include the password (if any) in the output. + + Returns + ------- + Dictionary with keys ``cls`` (the python location of this class), + protocol (text name of this class's protocol, first one in case of + multiple), ``args`` (positional args, usually empty), and all other + keyword arguments as their own keys. + + Warnings + -------- + Serialized filesystems may contain sensitive information which have been + passed to the constructor, such as passwords and tokens. Make sure you + store and send them in a secure environment! + """ + from .json import FilesystemJSONEncoder + + json_encoder = FilesystemJSONEncoder() + + cls = type(self) + proto = self.protocol + + storage_options = dict(self.storage_options) + if not include_password: + storage_options.pop("password", None) + + return dict( + cls=f"{cls.__module__}:{cls.__name__}", + protocol=proto[0] if isinstance(proto, (tuple, list)) else proto, + args=json_encoder.make_serializable(self.storage_args), + **json_encoder.make_serializable(storage_options), + ) + + @staticmethod + def from_dict(dct: dict[str, Any]) -> AbstractFileSystem: + """ + Recreate a filesystem instance from dictionary representation. + + See ``.to_dict()`` for the expected structure of the input. + + Parameters + ---------- + dct: Dict[str, Any] + + Returns + ------- + file system instance, not necessarily of this particular class. + + Warnings + -------- + This can import arbitrary modules (as determined by the ``cls`` key). + Make sure you haven't installed any modules that may execute malicious code + at import time. + """ + from .json import FilesystemJSONDecoder + + json_decoder = FilesystemJSONDecoder() + + dct = dict(dct) # Defensive copy + + cls = FilesystemJSONDecoder.try_resolve_fs_cls(dct) + if cls is None: + raise ValueError("Not a serialized AbstractFileSystem") + + dct.pop("cls", None) + dct.pop("protocol", None) + + return cls( + *json_decoder.unmake_serializable(dct.pop("args", ())), + **json_decoder.unmake_serializable(dct), + ) + + def _get_pyarrow_filesystem(self): + """ + Make a version of the FS instance which will be acceptable to pyarrow + """ + # all instances already also derive from pyarrow + return self + + def get_mapper(self, root="", check=False, create=False, missing_exceptions=None): + """Create key/value store based on this file-system + + Makes a MutableMapping interface to the FS at the given root path. + See ``fsspec.mapping.FSMap`` for further details. + """ + from .mapping import FSMap + + return FSMap( + root, + self, + check=check, + create=create, + missing_exceptions=missing_exceptions, + ) + + @classmethod + def clear_instance_cache(cls): + """ + Clear the cache of filesystem instances. + + Notes + ----- + Unless overridden by setting the ``cachable`` class attribute to False, + the filesystem class stores a reference to newly created instances. This + prevents Python's normal rules around garbage collection from working, + since the instances refcount will not drop to zero until + ``clear_instance_cache`` is called. + """ + cls._cache.clear() + + def created(self, path): + """Return the created timestamp of a file as a datetime.datetime""" + raise NotImplementedError + + def modified(self, path): + """Return the modified timestamp of a file as a datetime.datetime""" + raise NotImplementedError + + def tree( + self, + path: str = "/", + recursion_limit: int = 2, + max_display: int = 25, + display_size: bool = False, + prefix: str = "", + is_last: bool = True, + first: bool = True, + indent_size: int = 4, + ) -> str: + """ + Return a tree-like structure of the filesystem starting from the given path as a string. + + Parameters + ---------- + path: Root path to start traversal from + recursion_limit: Maximum depth of directory traversal + max_display: Maximum number of items to display per directory + display_size: Whether to display file sizes + prefix: Current line prefix for visual tree structure + is_last: Whether current item is last in its level + first: Whether this is the first call (displays root path) + indent_size: Number of spaces by indent + + Returns + ------- + str: A string representing the tree structure. + + Example + ------- + >>> from fsspec import filesystem + + >>> fs = filesystem('ftp', host='test.rebex.net', user='demo', password='password') + >>> tree = fs.tree(display_size=True, recursion_limit=3, indent_size=8, max_display=10) + >>> print(tree) + """ + + def format_bytes(n: int) -> str: + """Format bytes as text.""" + for prefix, k in ( + ("P", 2**50), + ("T", 2**40), + ("G", 2**30), + ("M", 2**20), + ("k", 2**10), + ): + if n >= 0.9 * k: + return f"{n / k:.2f} {prefix}b" + return f"{n}B" + + result = [] + + if first: + result.append(path) + + if recursion_limit: + indent = " " * indent_size + contents = self.ls(path, detail=True) + contents.sort( + key=lambda x: (x.get("type") != "directory", x.get("name", "")) + ) + + if max_display is not None and len(contents) > max_display: + displayed_contents = contents[:max_display] + remaining_count = len(contents) - max_display + else: + displayed_contents = contents + remaining_count = 0 + + for i, item in enumerate(displayed_contents): + is_last_item = (i == len(displayed_contents) - 1) and ( + remaining_count == 0 + ) + + branch = ( + "└" + ("─" * (indent_size - 2)) + if is_last_item + else "├" + ("─" * (indent_size - 2)) + ) + branch += " " + new_prefix = prefix + ( + indent if is_last_item else "│" + " " * (indent_size - 1) + ) + + name = os.path.basename(item.get("name", "")) + + if display_size and item.get("type") == "directory": + sub_contents = self.ls(item.get("name", ""), detail=True) + num_files = sum( + 1 for sub_item in sub_contents if sub_item.get("type") == "file" + ) + num_folders = sum( + 1 + for sub_item in sub_contents + if sub_item.get("type") == "directory" + ) + + if num_files == 0 and num_folders == 0: + size = " (empty folder)" + elif num_files == 0: + size = f" ({num_folders} subfolder{'s' if num_folders > 1 else ''})" + elif num_folders == 0: + size = f" ({num_files} file{'s' if num_files > 1 else ''})" + else: + size = f" ({num_files} file{'s' if num_files > 1 else ''}, {num_folders} subfolder{'s' if num_folders > 1 else ''})" + elif display_size and item.get("type") == "file": + size = f" ({format_bytes(item.get('size', 0))})" + else: + size = "" + + result.append(f"{prefix}{branch}{name}{size}") + + if item.get("type") == "directory" and recursion_limit > 0: + result.append( + self.tree( + path=item.get("name", ""), + recursion_limit=recursion_limit - 1, + max_display=max_display, + display_size=display_size, + prefix=new_prefix, + is_last=is_last_item, + first=False, + indent_size=indent_size, + ) + ) + + if remaining_count > 0: + more_message = f"{remaining_count} more item(s) not displayed." + result.append( + f"{prefix}{'└' + ('─' * (indent_size - 2))} {more_message}" + ) + + return "\n".join(_ for _ in result if _) + + # ------------------------------------------------------------------------ + # Aliases + + def read_bytes(self, path, start=None, end=None, **kwargs): + """Alias of `AbstractFileSystem.cat_file`.""" + return self.cat_file(path, start=start, end=end, **kwargs) + + def write_bytes(self, path, value, **kwargs): + """Alias of `AbstractFileSystem.pipe_file`.""" + self.pipe_file(path, value, **kwargs) + + def makedir(self, path, create_parents=True, **kwargs): + """Alias of `AbstractFileSystem.mkdir`.""" + return self.mkdir(path, create_parents=create_parents, **kwargs) + + def mkdirs(self, path, exist_ok=False): + """Alias of `AbstractFileSystem.makedirs`.""" + return self.makedirs(path, exist_ok=exist_ok) + + def listdir(self, path, detail=True, **kwargs): + """Alias of `AbstractFileSystem.ls`.""" + return self.ls(path, detail=detail, **kwargs) + + def cp(self, path1, path2, **kwargs): + """Alias of `AbstractFileSystem.copy`.""" + return self.copy(path1, path2, **kwargs) + + def move(self, path1, path2, **kwargs): + """Alias of `AbstractFileSystem.mv`.""" + return self.mv(path1, path2, **kwargs) + + def stat(self, path, **kwargs): + """Alias of `AbstractFileSystem.info`.""" + return self.info(path, **kwargs) + + def disk_usage(self, path, total=True, maxdepth=None, **kwargs): + """Alias of `AbstractFileSystem.du`.""" + return self.du(path, total=total, maxdepth=maxdepth, **kwargs) + + def rename(self, path1, path2, **kwargs): + """Alias of `AbstractFileSystem.mv`.""" + return self.mv(path1, path2, **kwargs) + + def delete(self, path, recursive=False, maxdepth=None): + """Alias of `AbstractFileSystem.rm`.""" + return self.rm(path, recursive=recursive, maxdepth=maxdepth) + + def upload(self, lpath, rpath, recursive=False, **kwargs): + """Alias of `AbstractFileSystem.put`.""" + return self.put(lpath, rpath, recursive=recursive, **kwargs) + + def download(self, rpath, lpath, recursive=False, **kwargs): + """Alias of `AbstractFileSystem.get`.""" + return self.get(rpath, lpath, recursive=recursive, **kwargs) + + def sign(self, path, expiration=100, **kwargs): + """Create a signed URL representing the given path + + Some implementations allow temporary URLs to be generated, as a + way of delegating credentials. + + Parameters + ---------- + path : str + The path on the filesystem + expiration : int + Number of seconds to enable the URL for (if supported) + + Returns + ------- + URL : str + The signed URL + + Raises + ------ + NotImplementedError : if method is not implemented for a filesystem + """ + raise NotImplementedError("Sign is not implemented for this filesystem") + + def _isfilestore(self): + # Originally inherited from pyarrow DaskFileSystem. Keeping this + # here for backwards compatibility as long as pyarrow uses its + # legacy fsspec-compatible filesystems and thus accepts fsspec + # filesystems as well + return False + + +class AbstractBufferedFile(io.IOBase): + """Convenient class to derive from to provide buffering + + In the case that the backend does not provide a pythonic file-like object + already, this class contains much of the logic to build one. The only + methods that need to be overridden are ``_upload_chunk``, + ``_initiate_upload`` and ``_fetch_range``. + """ + + DEFAULT_BLOCK_SIZE = 5 * 2**20 + _details = None + + def __init__( + self, + fs, + path, + mode="rb", + block_size="default", + autocommit=True, + cache_type="readahead", + cache_options=None, + size=None, + **kwargs, + ): + """ + Template for files with buffered reading and writing + + Parameters + ---------- + fs: instance of FileSystem + path: str + location in file-system + mode: str + Normal file modes. Currently only 'wb', 'ab' or 'rb'. Some file + systems may be read-only, and some may not support append. + block_size: int + Buffer size for reading or writing, 'default' for class default + autocommit: bool + Whether to write to final destination; may only impact what + happens when file is being closed. + cache_type: {"readahead", "none", "mmap", "bytes"}, default "readahead" + Caching policy in read mode. See the definitions in ``core``. + cache_options : dict + Additional options passed to the constructor for the cache specified + by `cache_type`. + size: int + If given and in read mode, suppressed having to look up the file size + kwargs: + Gets stored as self.kwargs + """ + from .core import caches + + self.path = path + self.fs = fs + self.mode = mode + self.blocksize = ( + self.DEFAULT_BLOCK_SIZE if block_size in ["default", None] else block_size + ) + self.loc = 0 + self.autocommit = autocommit + self.end = None + self.start = None + self.closed = False + + if cache_options is None: + cache_options = {} + + if "trim" in kwargs: + warnings.warn( + "Passing 'trim' to control the cache behavior has been deprecated. " + "Specify it within the 'cache_options' argument instead.", + FutureWarning, + ) + cache_options["trim"] = kwargs.pop("trim") + + self.kwargs = kwargs + + if mode not in {"ab", "rb", "wb", "xb"}: + raise NotImplementedError("File mode not supported") + if mode == "rb": + if size is not None: + self.size = size + else: + self.size = self.details["size"] + self.cache = caches[cache_type]( + self.blocksize, self._fetch_range, self.size, **cache_options + ) + else: + self.buffer = io.BytesIO() + self.offset = None + self.forced = False + self.location = None + + @property + def details(self): + if self._details is None: + self._details = self.fs.info(self.path) + return self._details + + @details.setter + def details(self, value): + self._details = value + self.size = value["size"] + + @property + def full_name(self): + return _unstrip_protocol(self.path, self.fs) + + @property + def closed(self): + # get around this attr being read-only in IOBase + # use getattr here, since this can be called during del + return getattr(self, "_closed", True) + + @closed.setter + def closed(self, c): + self._closed = c + + def __hash__(self): + if "w" in self.mode: + return id(self) + else: + return int(tokenize(self.details), 16) + + def __eq__(self, other): + """Files are equal if they have the same checksum, only in read mode""" + if self is other: + return True + return ( + isinstance(other, type(self)) + and self.mode == "rb" + and other.mode == "rb" + and hash(self) == hash(other) + ) + + def commit(self): + """Move from temp to final destination""" + + def discard(self): + """Throw away temporary file""" + + def info(self): + """File information about this path""" + if self.readable(): + return self.details + else: + raise ValueError("Info not available while writing") + + def tell(self): + """Current file location""" + return self.loc + + def seek(self, loc, whence=0): + """Set current file location + + Parameters + ---------- + loc: int + byte location + whence: {0, 1, 2} + from start of file, current location or end of file, resp. + """ + loc = int(loc) + if not self.mode == "rb": + raise OSError(ESPIPE, "Seek only available in read mode") + if whence == 0: + nloc = loc + elif whence == 1: + nloc = self.loc + loc + elif whence == 2: + nloc = self.size + loc + else: + raise ValueError(f"invalid whence ({whence}, should be 0, 1 or 2)") + if nloc < 0: + raise ValueError("Seek before start of file") + self.loc = nloc + return self.loc + + def write(self, data): + """ + Write data to buffer. + + Buffer only sent on flush() or if buffer is greater than + or equal to blocksize. + + Parameters + ---------- + data: bytes + Set of bytes to be written. + """ + if not self.writable(): + raise ValueError("File not in write mode") + if self.closed: + raise ValueError("I/O operation on closed file.") + if self.forced: + raise ValueError("This file has been force-flushed, can only close") + out = self.buffer.write(data) + self.loc += out + if self.buffer.tell() >= self.blocksize: + self.flush() + return out + + def flush(self, force=False): + """ + Write buffered data to backend store. + + Writes the current buffer, if it is larger than the block-size, or if + the file is being closed. + + Parameters + ---------- + force: bool + When closing, write the last block even if it is smaller than + blocks are allowed to be. Disallows further writing to this file. + """ + + if self.closed: + raise ValueError("Flush on closed file") + if force and self.forced: + raise ValueError("Force flush cannot be called more than once") + if force: + self.forced = True + + if self.readable(): + # no-op to flush on read-mode + return + + if not force and self.buffer.tell() < self.blocksize: + # Defer write on small block + return + + if self.offset is None: + # Initialize a multipart upload + self.offset = 0 + try: + self._initiate_upload() + except: + self.closed = True + raise + + if self._upload_chunk(final=force) is not False: + self.offset += self.buffer.seek(0, 2) + self.buffer = io.BytesIO() + + def _upload_chunk(self, final=False): + """Write one part of a multi-block file upload + + Parameters + ========== + final: bool + This is the last block, so should complete file, if + self.autocommit is True. + """ + # may not yet have been initialized, may need to call _initialize_upload + + def _initiate_upload(self): + """Create remote file/upload""" + pass + + def _fetch_range(self, start, end): + """Get the specified set of bytes from remote""" + return self.fs.cat_file(self.path, start=start, end=end) + + def read(self, length=-1): + """ + Return data from cache, or fetch pieces as necessary + + Parameters + ---------- + length: int (-1) + Number of bytes to read; if <0, all remaining bytes. + """ + length = -1 if length is None else int(length) + if self.mode != "rb": + raise ValueError("File not in read mode") + if length < 0: + length = self.size - self.loc + if self.closed: + raise ValueError("I/O operation on closed file.") + if length == 0: + # don't even bother calling fetch + return b"" + out = self.cache._fetch(self.loc, self.loc + length) + + logger.debug( + "%s read: %i - %i %s", + self, + self.loc, + self.loc + length, + self.cache._log_stats(), + ) + self.loc += len(out) + return out + + def readinto(self, b): + """mirrors builtin file's readinto method + + https://docs.python.org/3/library/io.html#io.RawIOBase.readinto + """ + out = memoryview(b).cast("B") + data = self.read(out.nbytes) + out[: len(data)] = data + return len(data) + + def readuntil(self, char=b"\n", blocks=None): + """Return data between current position and first occurrence of char + + char is included in the output, except if the end of the tile is + encountered first. + + Parameters + ---------- + char: bytes + Thing to find + blocks: None or int + How much to read in each go. Defaults to file blocksize - which may + mean a new read on every call. + """ + out = [] + while True: + start = self.tell() + part = self.read(blocks or self.blocksize) + if len(part) == 0: + break + found = part.find(char) + if found > -1: + out.append(part[: found + len(char)]) + self.seek(start + found + len(char)) + break + out.append(part) + return b"".join(out) + + def readline(self): + """Read until and including the first occurrence of newline character + + Note that, because of character encoding, this is not necessarily a + true line ending. + """ + return self.readuntil(b"\n") + + def __next__(self): + out = self.readline() + if out: + return out + raise StopIteration + + def __iter__(self): + return self + + def readlines(self): + """Return all data, split by the newline character, including the newline character""" + data = self.read() + lines = data.split(b"\n") + out = [l + b"\n" for l in lines[:-1]] + if data.endswith(b"\n"): + return out + else: + return out + [lines[-1]] + # return list(self) ??? + + def readinto1(self, b): + return self.readinto(b) + + def close(self): + """Close file + + Finalizes writes, discards cache + """ + if getattr(self, "_unclosable", False): + return + if self.closed: + return + try: + if self.mode == "rb": + self.cache = None + else: + if not self.forced: + self.flush(force=True) + + if self.fs is not None: + self.fs.invalidate_cache(self.path) + self.fs.invalidate_cache(self.fs._parent(self.path)) + finally: + self.closed = True + + def readable(self): + """Whether opened for reading""" + return "r" in self.mode and not self.closed + + def seekable(self): + """Whether is seekable (only in read mode)""" + return self.readable() + + def writable(self): + """Whether opened for writing""" + return self.mode in {"wb", "ab", "xb"} and not self.closed + + def __reduce__(self): + if self.mode != "rb": + raise RuntimeError("Pickling a writeable file is not supported") + + return reopen, ( + self.fs, + self.path, + self.mode, + self.blocksize, + self.loc, + self.size, + self.autocommit, + self.cache.name if self.cache else "none", + self.kwargs, + ) + + def __del__(self): + if not self.closed: + self.close() + + def __str__(self): + return f"" + + __repr__ = __str__ + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + +def reopen(fs, path, mode, blocksize, loc, size, autocommit, cache_type, kwargs): + file = fs.open( + path, + mode=mode, + block_size=blocksize, + autocommit=autocommit, + cache_type=cache_type, + size=size, + **kwargs, + ) + if loc > 0: + file.seek(loc) + return file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ed2ad802ecaf021106c25c03112f29e75c7b2f8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/__init__.py @@ -0,0 +1,289 @@ +import os +from hashlib import md5 + +import pytest + +from fsspec.implementations.local import LocalFileSystem +from fsspec.tests.abstract.copy import AbstractCopyTests # noqa: F401 +from fsspec.tests.abstract.get import AbstractGetTests # noqa: F401 +from fsspec.tests.abstract.open import AbstractOpenTests # noqa: F401 +from fsspec.tests.abstract.pipe import AbstractPipeTests # noqa: F401 +from fsspec.tests.abstract.put import AbstractPutTests # noqa: F401 + + +class BaseAbstractFixtures: + """ + Abstract base class containing fixtures that are used by but never need to + be overridden in derived filesystem-specific classes to run the abstract + tests on such filesystems. + """ + + @pytest.fixture + def fs_bulk_operations_scenario_0(self, fs, fs_join, fs_path): + """ + Scenario on remote filesystem that is used for many cp/get/put tests. + + Cleans up at the end of each test it which it is used. + """ + source = self._bulk_operations_scenario_0(fs, fs_join, fs_path) + yield source + fs.rm(source, recursive=True) + + @pytest.fixture + def fs_glob_edge_cases_files(self, fs, fs_join, fs_path): + """ + Scenario on remote filesystem that is used for glob edge cases cp/get/put tests. + + Cleans up at the end of each test it which it is used. + """ + source = self._glob_edge_cases_files(fs, fs_join, fs_path) + yield source + fs.rm(source, recursive=True) + + @pytest.fixture + def fs_dir_and_file_with_same_name_prefix(self, fs, fs_join, fs_path): + """ + Scenario on remote filesystem that is used to check cp/get/put on directory + and file with the same name prefixes. + + Cleans up at the end of each test it which it is used. + """ + source = self._dir_and_file_with_same_name_prefix(fs, fs_join, fs_path) + yield source + fs.rm(source, recursive=True) + + @pytest.fixture + def fs_10_files_with_hashed_names(self, fs, fs_join, fs_path): + """ + Scenario on remote filesystem that is used to check cp/get/put files order + when source and destination are lists. + + Cleans up at the end of each test it which it is used. + """ + source = self._10_files_with_hashed_names(fs, fs_join, fs_path) + yield source + fs.rm(source, recursive=True) + + @pytest.fixture + def fs_target(self, fs, fs_join, fs_path): + """ + Return name of remote directory that does not yet exist to copy into. + + Cleans up at the end of each test it which it is used. + """ + target = fs_join(fs_path, "target") + yield target + if fs.exists(target): + fs.rm(target, recursive=True) + + @pytest.fixture + def local_bulk_operations_scenario_0(self, local_fs, local_join, local_path): + """ + Scenario on local filesystem that is used for many cp/get/put tests. + + Cleans up at the end of each test it which it is used. + """ + source = self._bulk_operations_scenario_0(local_fs, local_join, local_path) + yield source + local_fs.rm(source, recursive=True) + + @pytest.fixture + def local_glob_edge_cases_files(self, local_fs, local_join, local_path): + """ + Scenario on local filesystem that is used for glob edge cases cp/get/put tests. + + Cleans up at the end of each test it which it is used. + """ + source = self._glob_edge_cases_files(local_fs, local_join, local_path) + yield source + local_fs.rm(source, recursive=True) + + @pytest.fixture + def local_dir_and_file_with_same_name_prefix( + self, local_fs, local_join, local_path + ): + """ + Scenario on local filesystem that is used to check cp/get/put on directory + and file with the same name prefixes. + + Cleans up at the end of each test it which it is used. + """ + source = self._dir_and_file_with_same_name_prefix( + local_fs, local_join, local_path + ) + yield source + local_fs.rm(source, recursive=True) + + @pytest.fixture + def local_10_files_with_hashed_names(self, local_fs, local_join, local_path): + """ + Scenario on local filesystem that is used to check cp/get/put files order + when source and destination are lists. + + Cleans up at the end of each test it which it is used. + """ + source = self._10_files_with_hashed_names(local_fs, local_join, local_path) + yield source + local_fs.rm(source, recursive=True) + + @pytest.fixture + def local_target(self, local_fs, local_join, local_path): + """ + Return name of local directory that does not yet exist to copy into. + + Cleans up at the end of each test it which it is used. + """ + target = local_join(local_path, "target") + yield target + if local_fs.exists(target): + local_fs.rm(target, recursive=True) + + def _glob_edge_cases_files(self, some_fs, some_join, some_path): + """ + Scenario that is used for glob edge cases cp/get/put tests. + Creates the following directory and file structure: + + 📁 source + ├── 📄 file1 + ├── 📄 file2 + ├── 📁 subdir0 + │ ├── 📄 subfile1 + │ ├── 📄 subfile2 + │ └── 📁 nesteddir + │ └── 📄 nestedfile + └── 📁 subdir1 + ├── 📄 subfile1 + ├── 📄 subfile2 + └── 📁 nesteddir + └── 📄 nestedfile + """ + source = some_join(some_path, "source") + some_fs.touch(some_join(source, "file1")) + some_fs.touch(some_join(source, "file2")) + + for subdir_idx in range(2): + subdir = some_join(source, f"subdir{subdir_idx}") + nesteddir = some_join(subdir, "nesteddir") + some_fs.makedirs(nesteddir) + some_fs.touch(some_join(subdir, "subfile1")) + some_fs.touch(some_join(subdir, "subfile2")) + some_fs.touch(some_join(nesteddir, "nestedfile")) + + return source + + def _bulk_operations_scenario_0(self, some_fs, some_join, some_path): + """ + Scenario that is used for many cp/get/put tests. Creates the following + directory and file structure: + + 📁 source + ├── 📄 file1 + ├── 📄 file2 + └── 📁 subdir + ├── 📄 subfile1 + ├── 📄 subfile2 + └── 📁 nesteddir + └── 📄 nestedfile + """ + source = some_join(some_path, "source") + subdir = some_join(source, "subdir") + nesteddir = some_join(subdir, "nesteddir") + some_fs.makedirs(nesteddir) + some_fs.touch(some_join(source, "file1")) + some_fs.touch(some_join(source, "file2")) + some_fs.touch(some_join(subdir, "subfile1")) + some_fs.touch(some_join(subdir, "subfile2")) + some_fs.touch(some_join(nesteddir, "nestedfile")) + return source + + def _dir_and_file_with_same_name_prefix(self, some_fs, some_join, some_path): + """ + Scenario that is used to check cp/get/put on directory and file with + the same name prefixes. Creates the following directory and file structure: + + 📁 source + ├── 📄 subdir.txt + └── 📁 subdir + └── 📄 subfile.txt + """ + source = some_join(some_path, "source") + subdir = some_join(source, "subdir") + file = some_join(source, "subdir.txt") + subfile = some_join(subdir, "subfile.txt") + some_fs.makedirs(subdir) + some_fs.touch(file) + some_fs.touch(subfile) + return source + + def _10_files_with_hashed_names(self, some_fs, some_join, some_path): + """ + Scenario that is used to check cp/get/put files order when source and + destination are lists. Creates the following directory and file structure: + + 📁 source + └── 📄 {hashed([0-9])}.txt + """ + source = some_join(some_path, "source") + for i in range(10): + hashed_i = md5(str(i).encode("utf-8")).hexdigest() + path = some_join(source, f"{hashed_i}.txt") + some_fs.pipe(path=path, value=f"{i}".encode()) + return source + + +class AbstractFixtures(BaseAbstractFixtures): + """ + Abstract base class containing fixtures that may be overridden in derived + filesystem-specific classes to run the abstract tests on such filesystems. + + For any particular filesystem some of these fixtures must be overridden, + such as ``fs`` and ``fs_path``, and others may be overridden if the + default functions here are not appropriate, such as ``fs_join``. + """ + + @pytest.fixture + def fs(self): + raise NotImplementedError("This function must be overridden in derived classes") + + @pytest.fixture + def fs_join(self): + """ + Return a function that joins its arguments together into a path. + + Most fsspec implementations join paths in a platform-dependent way, + but some will override this to always use a forward slash. + """ + return os.path.join + + @pytest.fixture + def fs_path(self): + raise NotImplementedError("This function must be overridden in derived classes") + + @pytest.fixture(scope="class") + def local_fs(self): + # Maybe need an option for auto_mkdir=False? This is only relevant + # for certain implementations. + return LocalFileSystem(auto_mkdir=True) + + @pytest.fixture + def local_join(self): + """ + Return a function that joins its arguments together into a path, on + the local filesystem. + """ + return os.path.join + + @pytest.fixture + def local_path(self, tmpdir): + return tmpdir + + @pytest.fixture + def supports_empty_directories(self): + """ + Return whether this implementation supports empty directories. + """ + return True + + @pytest.fixture + def fs_sanitize_path(self): + return lambda x: x diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/common.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/common.py new file mode 100644 index 0000000000000000000000000000000000000000..22e7c4140404ab2a8928689721419cf05c2760b9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/common.py @@ -0,0 +1,175 @@ +GLOB_EDGE_CASES_TESTS = { + "argnames": ("path", "recursive", "maxdepth", "expected"), + "argvalues": [ + ("fil?1", False, None, ["file1"]), + ("fil?1", True, None, ["file1"]), + ("file[1-2]", False, None, ["file1", "file2"]), + ("file[1-2]", True, None, ["file1", "file2"]), + ("*", False, None, ["file1", "file2"]), + ( + "*", + True, + None, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir0/nesteddir/nestedfile", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ("*", True, 1, ["file1", "file2"]), + ( + "*", + True, + 2, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir1/subfile1", + "subdir1/subfile2", + ], + ), + ("*1", False, None, ["file1"]), + ( + "*1", + True, + None, + [ + "file1", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ("*1", True, 2, ["file1", "subdir1/subfile1", "subdir1/subfile2"]), + ( + "**", + False, + None, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir0/nesteddir/nestedfile", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ( + "**", + True, + None, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir0/nesteddir/nestedfile", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ("**", True, 1, ["file1", "file2"]), + ( + "**", + True, + 2, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir0/nesteddir/nestedfile", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ( + "**", + False, + 2, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir1/subfile1", + "subdir1/subfile2", + ], + ), + ("**/*1", False, None, ["file1", "subdir0/subfile1", "subdir1/subfile1"]), + ( + "**/*1", + True, + None, + [ + "file1", + "subdir0/subfile1", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ("**/*1", True, 1, ["file1"]), + ( + "**/*1", + True, + 2, + ["file1", "subdir0/subfile1", "subdir1/subfile1", "subdir1/subfile2"], + ), + ("**/*1", False, 2, ["file1", "subdir0/subfile1", "subdir1/subfile1"]), + ("**/subdir0", False, None, []), + ("**/subdir0", True, None, ["subfile1", "subfile2", "nesteddir/nestedfile"]), + ("**/subdir0/nested*", False, 2, []), + ("**/subdir0/nested*", True, 2, ["nestedfile"]), + ("subdir[1-2]", False, None, []), + ("subdir[1-2]", True, None, ["subfile1", "subfile2", "nesteddir/nestedfile"]), + ("subdir[1-2]", True, 2, ["subfile1", "subfile2"]), + ("subdir[0-1]", False, None, []), + ( + "subdir[0-1]", + True, + None, + [ + "subdir0/subfile1", + "subdir0/subfile2", + "subdir0/nesteddir/nestedfile", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ( + "subdir[0-1]/*fil[e]*", + False, + None, + [ + "subdir0/subfile1", + "subdir0/subfile2", + "subdir1/subfile1", + "subdir1/subfile2", + ], + ), + ( + "subdir[0-1]/*fil[e]*", + True, + None, + [ + "subdir0/subfile1", + "subdir0/subfile2", + "subdir1/subfile1", + "subdir1/subfile2", + ], + ), + ], +} diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/copy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/copy.py new file mode 100644 index 0000000000000000000000000000000000000000..e39e57e5f7d52bfda8ab5e2398b04cc2303630a0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/copy.py @@ -0,0 +1,557 @@ +from hashlib import md5 +from itertools import product + +import pytest + +from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS + + +class AbstractCopyTests: + def test_copy_file_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 1a + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + fs.touch(fs_join(target, "dummy")) + assert fs.isdir(target) + + target_file2 = fs_join(target, "file2") + target_subfile1 = fs_join(target, "subfile1") + + # Copy from source directory + fs.cp(fs_join(source, "file2"), target) + assert fs.isfile(target_file2) + + # Copy from sub directory + fs.cp(fs_join(source, "subdir", "subfile1"), target) + assert fs.isfile(target_subfile1) + + # Remove copied files + fs.rm([target_file2, target_subfile1]) + assert not fs.exists(target_file2) + assert not fs.exists(target_subfile1) + + # Repeat with trailing slash on target + fs.cp(fs_join(source, "file2"), target + "/") + assert fs.isdir(target) + assert fs.isfile(target_file2) + + fs.cp(fs_join(source, "subdir", "subfile1"), target + "/") + assert fs.isfile(target_subfile1) + + def test_copy_file_to_new_directory( + self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target + ): + # Copy scenario 1b + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + fs.cp( + fs_join(source, "subdir", "subfile1"), fs_join(target, "newdir/") + ) # Note trailing slash + assert fs.isdir(target) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + + def test_copy_file_to_file_in_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 1c + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + fs.touch(fs_join(target, "dummy")) + assert fs.isdir(target) + + fs.cp(fs_join(source, "subdir", "subfile1"), fs_join(target, "newfile")) + assert fs.isfile(fs_join(target, "newfile")) + + def test_copy_file_to_file_in_new_directory( + self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target + ): + # Copy scenario 1d + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + fs.cp( + fs_join(source, "subdir", "subfile1"), fs_join(target, "newdir", "newfile") + ) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "newfile")) + + def test_copy_directory_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 1e + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = target + "/" if target_slash else target + + # Without recursive does nothing + fs.cp(s, t) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # With recursive + fs.cp(s, t, recursive=True) + if source_slash: + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert fs.isdir(fs_join(target, "nesteddir")) + assert fs.isfile(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + fs_join(target, "nesteddir"), + ], + recursive=True, + ) + else: + assert fs.isdir(fs_join(target, "subdir")) + assert fs.isfile(fs_join(target, "subdir", "subfile1")) + assert fs.isfile(fs_join(target, "subdir", "subfile2")) + assert fs.isdir(fs_join(target, "subdir", "nesteddir")) + assert fs.isfile(fs_join(target, "subdir", "nesteddir", "nestedfile")) + + fs.rm(fs_join(target, "subdir"), recursive=True) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # Limit recursive by maxdepth + fs.cp(s, t, recursive=True, maxdepth=1) + if source_slash: + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.exists(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + else: + assert fs.isdir(fs_join(target, "subdir")) + assert fs.isfile(fs_join(target, "subdir", "subfile1")) + assert fs.isfile(fs_join(target, "subdir", "subfile2")) + assert not fs.exists(fs_join(target, "subdir", "nesteddir")) + + fs.rm(fs_join(target, "subdir"), recursive=True) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_copy_directory_to_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 1f + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = fs_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive does nothing + fs.cp(s, t) + if supports_empty_directories: + assert fs.ls(target) == [] + else: + with pytest.raises(FileNotFoundError): + fs.ls(target) + + # With recursive + fs.cp(s, t, recursive=True) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert fs.isdir(fs_join(target, "newdir", "nesteddir")) + assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # Limit recursive by maxdepth + fs.cp(s, t, recursive=True, maxdepth=1) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + def test_copy_glob_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 1g + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + # Without recursive + fs.cp(fs_join(source, "subdir", "*"), t) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.isdir(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.cp(fs_join(source, "subdir", glob), t, recursive=recursive) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert fs.isdir(fs_join(target, "nesteddir")) + assert fs.isfile(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + fs_join(target, "nesteddir"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # Limit recursive by maxdepth + fs.cp( + fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1 + ) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.exists(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_copy_glob_to_new_directory( + self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target + ): + # Copy scenario 1h + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + for target_slash in [False, True]: + t = fs_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive + fs.cp(fs_join(source, "subdir", "*"), t) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.cp(fs_join(source, "subdir", glob), t, recursive=recursive) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert fs.isdir(fs_join(target, "newdir", "nesteddir")) + assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # Limit recursive by maxdepth + fs.cp( + fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1 + ) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + @pytest.mark.parametrize( + GLOB_EDGE_CASES_TESTS["argnames"], + GLOB_EDGE_CASES_TESTS["argvalues"], + ) + def test_copy_glob_edge_cases( + self, + path, + recursive, + maxdepth, + expected, + fs, + fs_join, + fs_glob_edge_cases_files, + fs_target, + fs_sanitize_path, + ): + # Copy scenario 1g + source = fs_glob_edge_cases_files + + target = fs_target + + for new_dir, target_slash in product([True, False], [True, False]): + fs.mkdir(target) + + t = fs_join(target, "newdir") if new_dir else target + t = t + "/" if target_slash else t + + fs.copy(fs_join(source, path), t, recursive=recursive, maxdepth=maxdepth) + + output = fs.find(target) + if new_dir: + prefixed_expected = [ + fs_sanitize_path(fs_join(target, "newdir", p)) for p in expected + ] + else: + prefixed_expected = [ + fs_sanitize_path(fs_join(target, p)) for p in expected + ] + assert sorted(output) == sorted(prefixed_expected) + + try: + fs.rm(target, recursive=True) + except FileNotFoundError: + pass + + def test_copy_list_of_files_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 2a + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + source_files = [ + fs_join(source, "file1"), + fs_join(source, "file2"), + fs_join(source, "subdir", "subfile1"), + ] + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + fs.cp(source_files, t) + assert fs.isfile(fs_join(target, "file1")) + assert fs.isfile(fs_join(target, "file2")) + assert fs.isfile(fs_join(target, "subfile1")) + + fs.rm( + [ + fs_join(target, "file1"), + fs_join(target, "file2"), + fs_join(target, "subfile1"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_copy_list_of_files_to_new_directory( + self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target + ): + # Copy scenario 2b + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + source_files = [ + fs_join(source, "file1"), + fs_join(source, "file2"), + fs_join(source, "subdir", "subfile1"), + ] + + fs.cp(source_files, fs_join(target, "newdir") + "/") # Note trailing slash + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "file1")) + assert fs.isfile(fs_join(target, "newdir", "file2")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + + def test_copy_two_files_new_directory( + self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target + ): + # This is a duplicate of test_copy_list_of_files_to_new_directory and + # can eventually be removed. + source = fs_bulk_operations_scenario_0 + + target = fs_target + assert not fs.exists(target) + fs.cp([fs_join(source, "file1"), fs_join(source, "file2")], target) + + assert fs.isdir(target) + assert fs.isfile(fs_join(target, "file1")) + assert fs.isfile(fs_join(target, "file2")) + + def test_copy_directory_without_files_with_same_name_prefix( + self, + fs, + fs_join, + fs_target, + fs_dir_and_file_with_same_name_prefix, + supports_empty_directories, + ): + # Create the test dirs + source = fs_dir_and_file_with_same_name_prefix + target = fs_target + + # Test without glob + fs.cp(fs_join(source, "subdir"), target, recursive=True) + + assert fs.isfile(fs_join(target, "subfile.txt")) + assert not fs.isfile(fs_join(target, "subdir.txt")) + + fs.rm([fs_join(target, "subfile.txt")]) + if supports_empty_directories: + assert fs.ls(target) == [] + else: + assert not fs.exists(target) + + # Test with glob + fs.cp(fs_join(source, "subdir*"), target, recursive=True) + + assert fs.isdir(fs_join(target, "subdir")) + assert fs.isfile(fs_join(target, "subdir", "subfile.txt")) + assert fs.isfile(fs_join(target, "subdir.txt")) + + def test_copy_with_source_and_destination_as_list( + self, fs, fs_target, fs_join, fs_10_files_with_hashed_names + ): + # Create the test dir + source = fs_10_files_with_hashed_names + target = fs_target + + # Create list of files for source and destination + source_files = [] + destination_files = [] + for i in range(10): + hashed_i = md5(str(i).encode("utf-8")).hexdigest() + source_files.append(fs_join(source, f"{hashed_i}.txt")) + destination_files.append(fs_join(target, f"{hashed_i}.txt")) + + # Copy and assert order was kept + fs.copy(path1=source_files, path2=destination_files) + + for i in range(10): + file_content = fs.cat(destination_files[i]).decode("utf-8") + assert file_content == str(i) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/get.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/get.py new file mode 100644 index 0000000000000000000000000000000000000000..851ab81ee581e74cac41c64c83ef0af75826d6b0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/get.py @@ -0,0 +1,587 @@ +from hashlib import md5 +from itertools import product + +import pytest + +from fsspec.implementations.local import make_path_posix +from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS + + +class AbstractGetTests: + def test_get_file_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1a + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + assert local_fs.isdir(target) + + target_file2 = local_join(target, "file2") + target_subfile1 = local_join(target, "subfile1") + + # Copy from source directory + fs.get(fs_join(source, "file2"), target) + assert local_fs.isfile(target_file2) + + # Copy from sub directory + fs.get(fs_join(source, "subdir", "subfile1"), target) + assert local_fs.isfile(target_subfile1) + + # Remove copied files + local_fs.rm([target_file2, target_subfile1]) + assert not local_fs.exists(target_file2) + assert not local_fs.exists(target_subfile1) + + # Repeat with trailing slash on target + fs.get(fs_join(source, "file2"), target + "/") + assert local_fs.isdir(target) + assert local_fs.isfile(target_file2) + + fs.get(fs_join(source, "subdir", "subfile1"), target + "/") + assert local_fs.isfile(target_subfile1) + + def test_get_file_to_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1b + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + fs.get( + fs_join(source, "subdir", "subfile1"), local_join(target, "newdir/") + ) # Note trailing slash + + assert local_fs.isdir(target) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + + def test_get_file_to_file_in_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1c + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + fs.get(fs_join(source, "subdir", "subfile1"), local_join(target, "newfile")) + assert local_fs.isfile(local_join(target, "newfile")) + + def test_get_file_to_file_in_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1d + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + fs.get( + fs_join(source, "subdir", "subfile1"), + local_join(target, "newdir", "newfile"), + ) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "newfile")) + + def test_get_directory_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1e + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + assert local_fs.isdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = target + "/" if target_slash else target + + # Without recursive does nothing + fs.get(s, t) + assert local_fs.ls(target) == [] + + # With recursive + fs.get(s, t, recursive=True) + if source_slash: + assert local_fs.isfile(local_join(target, "subfile1")) + assert local_fs.isfile(local_join(target, "subfile2")) + assert local_fs.isdir(local_join(target, "nesteddir")) + assert local_fs.isfile(local_join(target, "nesteddir", "nestedfile")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm( + [ + local_join(target, "subfile1"), + local_join(target, "subfile2"), + local_join(target, "nesteddir"), + ], + recursive=True, + ) + else: + assert local_fs.isdir(local_join(target, "subdir")) + assert local_fs.isfile(local_join(target, "subdir", "subfile1")) + assert local_fs.isfile(local_join(target, "subdir", "subfile2")) + assert local_fs.isdir(local_join(target, "subdir", "nesteddir")) + assert local_fs.isfile( + local_join(target, "subdir", "nesteddir", "nestedfile") + ) + + local_fs.rm(local_join(target, "subdir"), recursive=True) + assert local_fs.ls(target) == [] + + # Limit recursive by maxdepth + fs.get(s, t, recursive=True, maxdepth=1) + if source_slash: + assert local_fs.isfile(local_join(target, "subfile1")) + assert local_fs.isfile(local_join(target, "subfile2")) + assert not local_fs.exists(local_join(target, "nesteddir")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm( + [ + local_join(target, "subfile1"), + local_join(target, "subfile2"), + ], + recursive=True, + ) + else: + assert local_fs.isdir(local_join(target, "subdir")) + assert local_fs.isfile(local_join(target, "subdir", "subfile1")) + assert local_fs.isfile(local_join(target, "subdir", "subfile2")) + assert not local_fs.exists(local_join(target, "subdir", "nesteddir")) + + local_fs.rm(local_join(target, "subdir"), recursive=True) + assert local_fs.ls(target) == [] + + def test_get_directory_to_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1f + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = local_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive does nothing + fs.get(s, t) + assert local_fs.ls(target) == [] + + # With recursive + fs.get(s, t, recursive=True) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + assert local_fs.isfile(local_join(target, "newdir", "subfile2")) + assert local_fs.isdir(local_join(target, "newdir", "nesteddir")) + assert local_fs.isfile( + local_join(target, "newdir", "nesteddir", "nestedfile") + ) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm(local_join(target, "newdir"), recursive=True) + assert local_fs.ls(target) == [] + + # Limit recursive by maxdepth + fs.get(s, t, recursive=True, maxdepth=1) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + assert local_fs.isfile(local_join(target, "newdir", "subfile2")) + assert not local_fs.exists(local_join(target, "newdir", "nesteddir")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm(local_join(target, "newdir"), recursive=True) + assert not local_fs.exists(local_join(target, "newdir")) + + def test_get_glob_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1g + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + # Without recursive + fs.get(fs_join(source, "subdir", "*"), t) + assert local_fs.isfile(local_join(target, "subfile1")) + assert local_fs.isfile(local_join(target, "subfile2")) + assert not local_fs.isdir(local_join(target, "nesteddir")) + assert not local_fs.exists(local_join(target, "nesteddir", "nestedfile")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm( + [ + local_join(target, "subfile1"), + local_join(target, "subfile2"), + ], + recursive=True, + ) + assert local_fs.ls(target) == [] + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.get(fs_join(source, "subdir", glob), t, recursive=recursive) + assert local_fs.isfile(local_join(target, "subfile1")) + assert local_fs.isfile(local_join(target, "subfile2")) + assert local_fs.isdir(local_join(target, "nesteddir")) + assert local_fs.isfile(local_join(target, "nesteddir", "nestedfile")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm( + [ + local_join(target, "subfile1"), + local_join(target, "subfile2"), + local_join(target, "nesteddir"), + ], + recursive=True, + ) + assert local_fs.ls(target) == [] + + # Limit recursive by maxdepth + fs.get( + fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1 + ) + assert local_fs.isfile(local_join(target, "subfile1")) + assert local_fs.isfile(local_join(target, "subfile2")) + assert not local_fs.exists(local_join(target, "nesteddir")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm( + [ + local_join(target, "subfile1"), + local_join(target, "subfile2"), + ], + recursive=True, + ) + assert local_fs.ls(target) == [] + + def test_get_glob_to_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1h + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + for target_slash in [False, True]: + t = fs_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive + fs.get(fs_join(source, "subdir", "*"), t) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + assert local_fs.isfile(local_join(target, "newdir", "subfile2")) + assert not local_fs.exists(local_join(target, "newdir", "nesteddir")) + assert not local_fs.exists( + local_join(target, "newdir", "nesteddir", "nestedfile") + ) + assert not local_fs.exists(local_join(target, "subdir")) + assert not local_fs.exists(local_join(target, "newdir", "subdir")) + + local_fs.rm(local_join(target, "newdir"), recursive=True) + assert local_fs.ls(target) == [] + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.get(fs_join(source, "subdir", glob), t, recursive=recursive) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + assert local_fs.isfile(local_join(target, "newdir", "subfile2")) + assert local_fs.isdir(local_join(target, "newdir", "nesteddir")) + assert local_fs.isfile( + local_join(target, "newdir", "nesteddir", "nestedfile") + ) + assert not local_fs.exists(local_join(target, "subdir")) + assert not local_fs.exists(local_join(target, "newdir", "subdir")) + + local_fs.rm(local_join(target, "newdir"), recursive=True) + assert not local_fs.exists(local_join(target, "newdir")) + + # Limit recursive by maxdepth + fs.get( + fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1 + ) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + assert local_fs.isfile(local_join(target, "newdir", "subfile2")) + assert not local_fs.exists(local_join(target, "newdir", "nesteddir")) + assert not local_fs.exists(local_join(target, "subdir")) + assert not local_fs.exists(local_join(target, "newdir", "subdir")) + + local_fs.rm(local_fs.ls(target, detail=False), recursive=True) + assert not local_fs.exists(local_join(target, "newdir")) + + @pytest.mark.parametrize( + GLOB_EDGE_CASES_TESTS["argnames"], + GLOB_EDGE_CASES_TESTS["argvalues"], + ) + def test_get_glob_edge_cases( + self, + path, + recursive, + maxdepth, + expected, + fs, + fs_join, + fs_glob_edge_cases_files, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1g + source = fs_glob_edge_cases_files + + target = local_target + + for new_dir, target_slash in product([True, False], [True, False]): + local_fs.mkdir(target) + + t = local_join(target, "newdir") if new_dir else target + t = t + "/" if target_slash else t + + fs.get(fs_join(source, path), t, recursive=recursive, maxdepth=maxdepth) + + output = local_fs.find(target) + if new_dir: + prefixed_expected = [ + make_path_posix(local_join(target, "newdir", p)) for p in expected + ] + else: + prefixed_expected = [ + make_path_posix(local_join(target, p)) for p in expected + ] + assert sorted(output) == sorted(prefixed_expected) + + try: + local_fs.rm(target, recursive=True) + except FileNotFoundError: + pass + + def test_get_list_of_files_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 2a + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + source_files = [ + fs_join(source, "file1"), + fs_join(source, "file2"), + fs_join(source, "subdir", "subfile1"), + ] + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + fs.get(source_files, t) + assert local_fs.isfile(local_join(target, "file1")) + assert local_fs.isfile(local_join(target, "file2")) + assert local_fs.isfile(local_join(target, "subfile1")) + + local_fs.rm( + [ + local_join(target, "file1"), + local_join(target, "file2"), + local_join(target, "subfile1"), + ], + recursive=True, + ) + assert local_fs.ls(target) == [] + + def test_get_list_of_files_to_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 2b + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + source_files = [ + fs_join(source, "file1"), + fs_join(source, "file2"), + fs_join(source, "subdir", "subfile1"), + ] + + fs.get(source_files, local_join(target, "newdir") + "/") # Note trailing slash + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "file1")) + assert local_fs.isfile(local_join(target, "newdir", "file2")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + + def test_get_directory_recursive( + self, fs, fs_join, fs_path, local_fs, local_join, local_target + ): + # https://github.com/fsspec/filesystem_spec/issues/1062 + # Recursive cp/get/put of source directory into non-existent target directory. + src = fs_join(fs_path, "src") + src_file = fs_join(src, "file") + fs.mkdir(src) + fs.touch(src_file) + + target = local_target + + # get without slash + assert not local_fs.exists(target) + for loop in range(2): + fs.get(src, target, recursive=True) + assert local_fs.isdir(target) + + if loop == 0: + assert local_fs.isfile(local_join(target, "file")) + assert not local_fs.exists(local_join(target, "src")) + else: + assert local_fs.isfile(local_join(target, "file")) + assert local_fs.isdir(local_join(target, "src")) + assert local_fs.isfile(local_join(target, "src", "file")) + + local_fs.rm(target, recursive=True) + + # get with slash + assert not local_fs.exists(target) + for loop in range(2): + fs.get(src + "/", target, recursive=True) + assert local_fs.isdir(target) + assert local_fs.isfile(local_join(target, "file")) + assert not local_fs.exists(local_join(target, "src")) + + def test_get_directory_without_files_with_same_name_prefix( + self, + fs, + fs_join, + local_fs, + local_join, + local_target, + fs_dir_and_file_with_same_name_prefix, + ): + # Create the test dirs + source = fs_dir_and_file_with_same_name_prefix + target = local_target + + # Test without glob + fs.get(fs_join(source, "subdir"), target, recursive=True) + + assert local_fs.isfile(local_join(target, "subfile.txt")) + assert not local_fs.isfile(local_join(target, "subdir.txt")) + + local_fs.rm([local_join(target, "subfile.txt")]) + assert local_fs.ls(target) == [] + + # Test with glob + fs.get(fs_join(source, "subdir*"), target, recursive=True) + + assert local_fs.isdir(local_join(target, "subdir")) + assert local_fs.isfile(local_join(target, "subdir", "subfile.txt")) + assert local_fs.isfile(local_join(target, "subdir.txt")) + + def test_get_with_source_and_destination_as_list( + self, + fs, + fs_join, + local_fs, + local_join, + local_target, + fs_10_files_with_hashed_names, + ): + # Create the test dir + source = fs_10_files_with_hashed_names + target = local_target + + # Create list of files for source and destination + source_files = [] + destination_files = [] + for i in range(10): + hashed_i = md5(str(i).encode("utf-8")).hexdigest() + source_files.append(fs_join(source, f"{hashed_i}.txt")) + destination_files.append( + make_path_posix(local_join(target, f"{hashed_i}.txt")) + ) + + # Copy and assert order was kept + fs.get(rpath=source_files, lpath=destination_files) + + for i in range(10): + file_content = local_fs.cat(destination_files[i]).decode("utf-8") + assert file_content == str(i) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/mv.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/mv.py new file mode 100644 index 0000000000000000000000000000000000000000..39f6caa3de815e024fa84de2acecc986c823ed29 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/mv.py @@ -0,0 +1,57 @@ +import os + +import pytest + +import fsspec + + +def test_move_raises_error_with_tmpdir(tmpdir): + # Create a file in the temporary directory + source = tmpdir.join("source_file.txt") + source.write("content") + + # Define a destination that simulates a protected or invalid path + destination = tmpdir.join("non_existent_directory/destination_file.txt") + + # Instantiate the filesystem (assuming the local file system interface) + fs = fsspec.filesystem("file") + + # Use the actual file paths as string + with pytest.raises(FileNotFoundError): + fs.mv(str(source), str(destination)) + + +@pytest.mark.parametrize("recursive", (True, False)) +def test_move_raises_error_with_tmpdir_permission(recursive, tmpdir): + # Create a file in the temporary directory + source = tmpdir.join("source_file.txt") + source.write("content") + + # Create a protected directory (non-writable) + protected_dir = tmpdir.mkdir("protected_directory") + protected_path = str(protected_dir) + + # Set the directory to read-only + if os.name == "nt": + os.system(f'icacls "{protected_path}" /deny Everyone:(W)') + else: + os.chmod(protected_path, 0o555) # Sets the directory to read-only + + # Define a destination inside the protected directory + destination = protected_dir.join("destination_file.txt") + + # Instantiate the filesystem (assuming the local file system interface) + fs = fsspec.filesystem("file") + + # Try to move the file to the read-only directory, expecting a permission error + with pytest.raises(PermissionError): + fs.mv(str(source), str(destination), recursive=recursive) + + # Assert the file was not created in the destination + assert not os.path.exists(destination) + + # Cleanup: Restore permissions so the directory can be cleaned up + if os.name == "nt": + os.system(f'icacls "{protected_path}" /remove:d Everyone') + else: + os.chmod(protected_path, 0o755) # Restore write permission for cleanup diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/open.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/open.py new file mode 100644 index 0000000000000000000000000000000000000000..bb75ea852276fb8d834345883813b8e27a0ae24c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/open.py @@ -0,0 +1,11 @@ +import pytest + + +class AbstractOpenTests: + def test_open_exclusive(self, fs, fs_target): + with fs.open(fs_target, "wb") as f: + f.write(b"data") + with fs.open(fs_target, "rb") as f: + assert f.read() == b"data" + with pytest.raises(FileExistsError): + fs.open(fs_target, "xb") diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/pipe.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/pipe.py new file mode 100644 index 0000000000000000000000000000000000000000..8ecca96e9d23ff268a253c48269d5cca451ea270 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/pipe.py @@ -0,0 +1,11 @@ +import pytest + + +class AbstractPipeTests: + def test_pipe_exclusive(self, fs, fs_target): + fs.pipe_file(fs_target, b"data") + assert fs.cat_file(fs_target) == b"data" + with pytest.raises(FileExistsError): + fs.pipe_file(fs_target, b"data", mode="create") + fs.pipe_file(fs_target, b"new data", mode="overwrite") + assert fs.cat_file(fs_target) == b"new data" diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/put.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/put.py new file mode 100644 index 0000000000000000000000000000000000000000..9fc349977f0384d9fc86126498be5c6ad99a21d3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/tests/abstract/put.py @@ -0,0 +1,591 @@ +from hashlib import md5 +from itertools import product + +import pytest + +from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS + + +class AbstractPutTests: + def test_put_file_to_existing_directory( + self, + fs, + fs_join, + fs_target, + local_join, + local_bulk_operations_scenario_0, + supports_empty_directories, + ): + # Copy scenario 1a + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + fs.touch(fs_join(target, "dummy")) + assert fs.isdir(target) + + target_file2 = fs_join(target, "file2") + target_subfile1 = fs_join(target, "subfile1") + + # Copy from source directory + fs.put(local_join(source, "file2"), target) + assert fs.isfile(target_file2) + + # Copy from sub directory + fs.put(local_join(source, "subdir", "subfile1"), target) + assert fs.isfile(target_subfile1) + + # Remove copied files + fs.rm([target_file2, target_subfile1]) + assert not fs.exists(target_file2) + assert not fs.exists(target_subfile1) + + # Repeat with trailing slash on target + fs.put(local_join(source, "file2"), target + "/") + assert fs.isdir(target) + assert fs.isfile(target_file2) + + fs.put(local_join(source, "subdir", "subfile1"), target + "/") + assert fs.isfile(target_subfile1) + + def test_put_file_to_new_directory( + self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0 + ): + # Copy scenario 1b + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + fs.put( + local_join(source, "subdir", "subfile1"), fs_join(target, "newdir/") + ) # Note trailing slash + assert fs.isdir(target) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + + def test_put_file_to_file_in_existing_directory( + self, + fs, + fs_join, + fs_target, + local_join, + supports_empty_directories, + local_bulk_operations_scenario_0, + ): + # Copy scenario 1c + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + fs.touch(fs_join(target, "dummy")) + assert fs.isdir(target) + + fs.put(local_join(source, "subdir", "subfile1"), fs_join(target, "newfile")) + assert fs.isfile(fs_join(target, "newfile")) + + def test_put_file_to_file_in_new_directory( + self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0 + ): + # Copy scenario 1d + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + fs.put( + local_join(source, "subdir", "subfile1"), + fs_join(target, "newdir", "newfile"), + ) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "newfile")) + + def test_put_directory_to_existing_directory( + self, + fs, + fs_join, + fs_target, + local_bulk_operations_scenario_0, + supports_empty_directories, + ): + # Copy scenario 1e + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = target + "/" if target_slash else target + + # Without recursive does nothing + fs.put(s, t) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # With recursive + fs.put(s, t, recursive=True) + if source_slash: + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert fs.isdir(fs_join(target, "nesteddir")) + assert fs.isfile(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + fs_join(target, "nesteddir"), + ], + recursive=True, + ) + else: + assert fs.isdir(fs_join(target, "subdir")) + assert fs.isfile(fs_join(target, "subdir", "subfile1")) + assert fs.isfile(fs_join(target, "subdir", "subfile2")) + assert fs.isdir(fs_join(target, "subdir", "nesteddir")) + assert fs.isfile(fs_join(target, "subdir", "nesteddir", "nestedfile")) + + fs.rm(fs_join(target, "subdir"), recursive=True) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # Limit recursive by maxdepth + fs.put(s, t, recursive=True, maxdepth=1) + if source_slash: + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.exists(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + else: + assert fs.isdir(fs_join(target, "subdir")) + assert fs.isfile(fs_join(target, "subdir", "subfile1")) + assert fs.isfile(fs_join(target, "subdir", "subfile2")) + assert not fs.exists(fs_join(target, "subdir", "nesteddir")) + + fs.rm(fs_join(target, "subdir"), recursive=True) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_put_directory_to_new_directory( + self, + fs, + fs_join, + fs_target, + local_bulk_operations_scenario_0, + supports_empty_directories, + ): + # Copy scenario 1f + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = fs_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive does nothing + fs.put(s, t) + if supports_empty_directories: + assert fs.ls(target) == [] + else: + with pytest.raises(FileNotFoundError): + fs.ls(target) + + # With recursive + fs.put(s, t, recursive=True) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert fs.isdir(fs_join(target, "newdir", "nesteddir")) + assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # Limit recursive by maxdepth + fs.put(s, t, recursive=True, maxdepth=1) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + def test_put_glob_to_existing_directory( + self, + fs, + fs_join, + fs_target, + local_join, + supports_empty_directories, + local_bulk_operations_scenario_0, + ): + # Copy scenario 1g + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + # Without recursive + fs.put(local_join(source, "subdir", "*"), t) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.isdir(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.put(local_join(source, "subdir", glob), t, recursive=recursive) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert fs.isdir(fs_join(target, "nesteddir")) + assert fs.isfile(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + fs_join(target, "nesteddir"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # Limit recursive by maxdepth + fs.put( + local_join(source, "subdir", glob), + t, + recursive=recursive, + maxdepth=1, + ) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.exists(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_put_glob_to_new_directory( + self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0 + ): + # Copy scenario 1h + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + for target_slash in [False, True]: + t = fs_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive + fs.put(local_join(source, "subdir", "*"), t) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.put(local_join(source, "subdir", glob), t, recursive=recursive) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert fs.isdir(fs_join(target, "newdir", "nesteddir")) + assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # Limit recursive by maxdepth + fs.put( + local_join(source, "subdir", glob), + t, + recursive=recursive, + maxdepth=1, + ) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + @pytest.mark.parametrize( + GLOB_EDGE_CASES_TESTS["argnames"], + GLOB_EDGE_CASES_TESTS["argvalues"], + ) + def test_put_glob_edge_cases( + self, + path, + recursive, + maxdepth, + expected, + fs, + fs_join, + fs_target, + local_glob_edge_cases_files, + local_join, + fs_sanitize_path, + ): + # Copy scenario 1g + source = local_glob_edge_cases_files + + target = fs_target + + for new_dir, target_slash in product([True, False], [True, False]): + fs.mkdir(target) + + t = fs_join(target, "newdir") if new_dir else target + t = t + "/" if target_slash else t + + fs.put(local_join(source, path), t, recursive=recursive, maxdepth=maxdepth) + + output = fs.find(target) + if new_dir: + prefixed_expected = [ + fs_sanitize_path(fs_join(target, "newdir", p)) for p in expected + ] + else: + prefixed_expected = [ + fs_sanitize_path(fs_join(target, p)) for p in expected + ] + assert sorted(output) == sorted(prefixed_expected) + + try: + fs.rm(target, recursive=True) + except FileNotFoundError: + pass + + def test_put_list_of_files_to_existing_directory( + self, + fs, + fs_join, + fs_target, + local_join, + local_bulk_operations_scenario_0, + supports_empty_directories, + ): + # Copy scenario 2a + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + source_files = [ + local_join(source, "file1"), + local_join(source, "file2"), + local_join(source, "subdir", "subfile1"), + ] + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + fs.put(source_files, t) + assert fs.isfile(fs_join(target, "file1")) + assert fs.isfile(fs_join(target, "file2")) + assert fs.isfile(fs_join(target, "subfile1")) + + fs.rm( + [ + fs_join(target, "file1"), + fs_join(target, "file2"), + fs_join(target, "subfile1"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_put_list_of_files_to_new_directory( + self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0 + ): + # Copy scenario 2b + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + source_files = [ + local_join(source, "file1"), + local_join(source, "file2"), + local_join(source, "subdir", "subfile1"), + ] + + fs.put(source_files, fs_join(target, "newdir") + "/") # Note trailing slash + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "file1")) + assert fs.isfile(fs_join(target, "newdir", "file2")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + + def test_put_directory_recursive( + self, fs, fs_join, fs_target, local_fs, local_join, local_path + ): + # https://github.com/fsspec/filesystem_spec/issues/1062 + # Recursive cp/get/put of source directory into non-existent target directory. + src = local_join(local_path, "src") + src_file = local_join(src, "file") + local_fs.mkdir(src) + local_fs.touch(src_file) + + target = fs_target + + # put without slash + assert not fs.exists(target) + for loop in range(2): + fs.put(src, target, recursive=True) + assert fs.isdir(target) + + if loop == 0: + assert fs.isfile(fs_join(target, "file")) + assert not fs.exists(fs_join(target, "src")) + else: + assert fs.isfile(fs_join(target, "file")) + assert fs.isdir(fs_join(target, "src")) + assert fs.isfile(fs_join(target, "src", "file")) + + fs.rm(target, recursive=True) + + # put with slash + assert not fs.exists(target) + for loop in range(2): + fs.put(src + "/", target, recursive=True) + assert fs.isdir(target) + assert fs.isfile(fs_join(target, "file")) + assert not fs.exists(fs_join(target, "src")) + + def test_put_directory_without_files_with_same_name_prefix( + self, + fs, + fs_join, + fs_target, + local_join, + local_dir_and_file_with_same_name_prefix, + supports_empty_directories, + ): + # Create the test dirs + source = local_dir_and_file_with_same_name_prefix + target = fs_target + + # Test without glob + fs.put(local_join(source, "subdir"), fs_target, recursive=True) + + assert fs.isfile(fs_join(fs_target, "subfile.txt")) + assert not fs.isfile(fs_join(fs_target, "subdir.txt")) + + fs.rm([fs_join(target, "subfile.txt")]) + if supports_empty_directories: + assert fs.ls(target) == [] + else: + assert not fs.exists(target) + + # Test with glob + fs.put(local_join(source, "subdir*"), fs_target, recursive=True) + + assert fs.isdir(fs_join(fs_target, "subdir")) + assert fs.isfile(fs_join(fs_target, "subdir", "subfile.txt")) + assert fs.isfile(fs_join(fs_target, "subdir.txt")) + + def test_copy_with_source_and_destination_as_list( + self, fs, fs_target, fs_join, local_join, local_10_files_with_hashed_names + ): + # Create the test dir + source = local_10_files_with_hashed_names + target = fs_target + + # Create list of files for source and destination + source_files = [] + destination_files = [] + for i in range(10): + hashed_i = md5(str(i).encode("utf-8")).hexdigest() + source_files.append(local_join(source, f"{hashed_i}.txt")) + destination_files.append(fs_join(target, f"{hashed_i}.txt")) + + # Copy and assert order was kept + fs.put(lpath=source_files, rpath=destination_files) + + for i in range(10): + file_content = fs.cat(destination_files[i]).decode("utf-8") + assert file_content == str(i) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/transaction.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/transaction.py new file mode 100644 index 0000000000000000000000000000000000000000..77293f63ecc5f611e19d849ef236d53e9c258efc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/transaction.py @@ -0,0 +1,90 @@ +from collections import deque + + +class Transaction: + """Filesystem transaction write context + + Gathers files for deferred commit or discard, so that several write + operations can be finalized semi-atomically. This works by having this + instance as the ``.transaction`` attribute of the given filesystem + """ + + def __init__(self, fs, **kwargs): + """ + Parameters + ---------- + fs: FileSystem instance + """ + self.fs = fs + self.files = deque() + + def __enter__(self): + self.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """End transaction and commit, if exit is not due to exception""" + # only commit if there was no exception + self.complete(commit=exc_type is None) + if self.fs: + self.fs._intrans = False + self.fs._transaction = None + self.fs = None + + def start(self): + """Start a transaction on this FileSystem""" + self.files = deque() # clean up after previous failed completions + self.fs._intrans = True + + def complete(self, commit=True): + """Finish transaction: commit or discard all deferred files""" + while self.files: + f = self.files.popleft() + if commit: + f.commit() + else: + f.discard() + self.fs._intrans = False + self.fs._transaction = None + self.fs = None + + +class FileActor: + def __init__(self): + self.files = [] + + def commit(self): + for f in self.files: + f.commit() + self.files.clear() + + def discard(self): + for f in self.files: + f.discard() + self.files.clear() + + def append(self, f): + self.files.append(f) + + +class DaskTransaction(Transaction): + def __init__(self, fs): + """ + Parameters + ---------- + fs: FileSystem instance + """ + import distributed + + super().__init__(fs) + client = distributed.default_client() + self.files = client.submit(FileActor, actor=True).result() + + def complete(self, commit=True): + """Finish transaction: commit or discard all deferred files""" + if commit: + self.files.commit().result() + else: + self.files.discard().result() + self.fs._intrans = False + self.fs = None diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/utils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6441c5b1d3a766e7911161e54c6d7fba8eb3032e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fsspec/utils.py @@ -0,0 +1,737 @@ +from __future__ import annotations + +import contextlib +import logging +import math +import os +import re +import sys +import tempfile +from collections.abc import Iterable, Iterator, Sequence +from functools import partial +from hashlib import md5 +from importlib.metadata import version +from typing import ( + IO, + TYPE_CHECKING, + Any, + Callable, + TypeVar, +) +from urllib.parse import urlsplit + +if TYPE_CHECKING: + import pathlib + + from typing_extensions import TypeGuard + + from fsspec.spec import AbstractFileSystem + + +DEFAULT_BLOCK_SIZE = 5 * 2**20 + +T = TypeVar("T") + + +def infer_storage_options( + urlpath: str, inherit_storage_options: dict[str, Any] | None = None +) -> dict[str, Any]: + """Infer storage options from URL path and merge it with existing storage + options. + + Parameters + ---------- + urlpath: str or unicode + Either local absolute file path or URL (hdfs://namenode:8020/file.csv) + inherit_storage_options: dict (optional) + Its contents will get merged with the inferred information from the + given path + + Returns + ------- + Storage options dict. + + Examples + -------- + >>> infer_storage_options('/mnt/datasets/test.csv') # doctest: +SKIP + {"protocol": "file", "path", "/mnt/datasets/test.csv"} + >>> infer_storage_options( + ... 'hdfs://username:pwd@node:123/mnt/datasets/test.csv?q=1', + ... inherit_storage_options={'extra': 'value'}, + ... ) # doctest: +SKIP + {"protocol": "hdfs", "username": "username", "password": "pwd", + "host": "node", "port": 123, "path": "/mnt/datasets/test.csv", + "url_query": "q=1", "extra": "value"} + """ + # Handle Windows paths including disk name in this special case + if ( + re.match(r"^[a-zA-Z]:[\\/]", urlpath) + or re.match(r"^[a-zA-Z0-9]+://", urlpath) is None + ): + return {"protocol": "file", "path": urlpath} + + parsed_path = urlsplit(urlpath) + protocol = parsed_path.scheme or "file" + if parsed_path.fragment: + path = "#".join([parsed_path.path, parsed_path.fragment]) + else: + path = parsed_path.path + if protocol == "file": + # Special case parsing file protocol URL on Windows according to: + # https://msdn.microsoft.com/en-us/library/jj710207.aspx + windows_path = re.match(r"^/([a-zA-Z])[:|]([\\/].*)$", path) + if windows_path: + drive, path = windows_path.groups() + path = f"{drive}:{path}" + + if protocol in ["http", "https"]: + # for HTTP, we don't want to parse, as requests will anyway + return {"protocol": protocol, "path": urlpath} + + options: dict[str, Any] = {"protocol": protocol, "path": path} + + if parsed_path.netloc: + # Parse `hostname` from netloc manually because `parsed_path.hostname` + # lowercases the hostname which is not always desirable (e.g. in S3): + # https://github.com/dask/dask/issues/1417 + options["host"] = parsed_path.netloc.rsplit("@", 1)[-1].rsplit(":", 1)[0] + + if protocol in ("s3", "s3a", "gcs", "gs"): + options["path"] = options["host"] + options["path"] + else: + options["host"] = options["host"] + if parsed_path.port: + options["port"] = parsed_path.port + if parsed_path.username: + options["username"] = parsed_path.username + if parsed_path.password: + options["password"] = parsed_path.password + + if parsed_path.query: + options["url_query"] = parsed_path.query + if parsed_path.fragment: + options["url_fragment"] = parsed_path.fragment + + if inherit_storage_options: + update_storage_options(options, inherit_storage_options) + + return options + + +def update_storage_options( + options: dict[str, Any], inherited: dict[str, Any] | None = None +) -> None: + if not inherited: + inherited = {} + collisions = set(options) & set(inherited) + if collisions: + for collision in collisions: + if options.get(collision) != inherited.get(collision): + raise KeyError( + f"Collision between inferred and specified storage " + f"option:\n{collision}" + ) + options.update(inherited) + + +# Compression extensions registered via fsspec.compression.register_compression +compressions: dict[str, str] = {} + + +def infer_compression(filename: str) -> str | None: + """Infer compression, if available, from filename. + + Infer a named compression type, if registered and available, from filename + extension. This includes builtin (gz, bz2, zip) compressions, as well as + optional compressions. See fsspec.compression.register_compression. + """ + extension = os.path.splitext(filename)[-1].strip(".").lower() + if extension in compressions: + return compressions[extension] + return None + + +def build_name_function(max_int: float) -> Callable[[int], str]: + """Returns a function that receives a single integer + and returns it as a string padded by enough zero characters + to align with maximum possible integer + + >>> name_f = build_name_function(57) + + >>> name_f(7) + '07' + >>> name_f(31) + '31' + >>> build_name_function(1000)(42) + '0042' + >>> build_name_function(999)(42) + '042' + >>> build_name_function(0)(0) + '0' + """ + # handle corner cases max_int is 0 or exact power of 10 + max_int += 1e-8 + + pad_length = int(math.ceil(math.log10(max_int))) + + def name_function(i: int) -> str: + return str(i).zfill(pad_length) + + return name_function + + +def seek_delimiter(file: IO[bytes], delimiter: bytes, blocksize: int) -> bool: + r"""Seek current file to file start, file end, or byte after delimiter seq. + + Seeks file to next chunk delimiter, where chunks are defined on file start, + a delimiting sequence, and file end. Use file.tell() to see location afterwards. + Note that file start is a valid split, so must be at offset > 0 to seek for + delimiter. + + Parameters + ---------- + file: a file + delimiter: bytes + a delimiter like ``b'\n'`` or message sentinel, matching file .read() type + blocksize: int + Number of bytes to read from the file at once. + + + Returns + ------- + Returns True if a delimiter was found, False if at file start or end. + + """ + + if file.tell() == 0: + # beginning-of-file, return without seek + return False + + # Interface is for binary IO, with delimiter as bytes, but initialize last + # with result of file.read to preserve compatibility with text IO. + last: bytes | None = None + while True: + current = file.read(blocksize) + if not current: + # end-of-file without delimiter + return False + full = last + current if last else current + try: + if delimiter in full: + i = full.index(delimiter) + file.seek(file.tell() - (len(full) - i) + len(delimiter)) + return True + elif len(current) < blocksize: + # end-of-file without delimiter + return False + except (OSError, ValueError): + pass + last = full[-len(delimiter) :] + + +def read_block( + f: IO[bytes], + offset: int, + length: int | None, + delimiter: bytes | None = None, + split_before: bool = False, +) -> bytes: + """Read a block of bytes from a file + + Parameters + ---------- + f: File + Open file + offset: int + Byte offset to start read + length: int + Number of bytes to read, read through end of file if None + delimiter: bytes (optional) + Ensure reading starts and stops at delimiter bytestring + split_before: bool (optional) + Start/stop read *before* delimiter bytestring. + + + If using the ``delimiter=`` keyword argument we ensure that the read + starts and stops at delimiter boundaries that follow the locations + ``offset`` and ``offset + length``. If ``offset`` is zero then we + start at zero, regardless of delimiter. The bytestring returned WILL + include the terminating delimiter string. + + Examples + -------- + + >>> from io import BytesIO # doctest: +SKIP + >>> f = BytesIO(b'Alice, 100\\nBob, 200\\nCharlie, 300') # doctest: +SKIP + >>> read_block(f, 0, 13) # doctest: +SKIP + b'Alice, 100\\nBo' + + >>> read_block(f, 0, 13, delimiter=b'\\n') # doctest: +SKIP + b'Alice, 100\\nBob, 200\\n' + + >>> read_block(f, 10, 10, delimiter=b'\\n') # doctest: +SKIP + b'Bob, 200\\nCharlie, 300' + """ + if delimiter: + f.seek(offset) + found_start_delim = seek_delimiter(f, delimiter, 2**16) + if length is None: + return f.read() + start = f.tell() + length -= start - offset + + f.seek(start + length) + found_end_delim = seek_delimiter(f, delimiter, 2**16) + end = f.tell() + + # Adjust split location to before delimiter if seek found the + # delimiter sequence, not start or end of file. + if found_start_delim and split_before: + start -= len(delimiter) + + if found_end_delim and split_before: + end -= len(delimiter) + + offset = start + length = end - start + + f.seek(offset) + + # TODO: allow length to be None and read to the end of the file? + assert length is not None + b = f.read(length) + return b + + +def tokenize(*args: Any, **kwargs: Any) -> str: + """Deterministic token + + (modified from dask.base) + + >>> tokenize([1, 2, '3']) + '9d71491b50023b06fc76928e6eddb952' + + >>> tokenize('Hello') == tokenize('Hello') + True + """ + if kwargs: + args += (kwargs,) + try: + h = md5(str(args).encode()) + except ValueError: + # FIPS systems: https://github.com/fsspec/filesystem_spec/issues/380 + h = md5(str(args).encode(), usedforsecurity=False) + return h.hexdigest() + + +def stringify_path(filepath: str | os.PathLike[str] | pathlib.Path) -> str: + """Attempt to convert a path-like object to a string. + + Parameters + ---------- + filepath: object to be converted + + Returns + ------- + filepath_str: maybe a string version of the object + + Notes + ----- + Objects supporting the fspath protocol are coerced according to its + __fspath__ method. + + For backwards compatibility with older Python version, pathlib.Path + objects are specially coerced. + + Any other object is passed through unchanged, which includes bytes, + strings, buffers, or anything else that's not even path-like. + """ + if isinstance(filepath, str): + return filepath + elif hasattr(filepath, "__fspath__"): + return filepath.__fspath__() + elif hasattr(filepath, "path"): + return filepath.path + else: + return filepath # type: ignore[return-value] + + +def make_instance( + cls: Callable[..., T], args: Sequence[Any], kwargs: dict[str, Any] +) -> T: + inst = cls(*args, **kwargs) + inst._determine_worker() # type: ignore[attr-defined] + return inst + + +def common_prefix(paths: Iterable[str]) -> str: + """For a list of paths, find the shortest prefix common to all""" + parts = [p.split("/") for p in paths] + lmax = min(len(p) for p in parts) + end = 0 + for i in range(lmax): + end = all(p[i] == parts[0][i] for p in parts) + if not end: + break + i += end + return "/".join(parts[0][:i]) + + +def other_paths( + paths: list[str], + path2: str | list[str], + exists: bool = False, + flatten: bool = False, +) -> list[str]: + """In bulk file operations, construct a new file tree from a list of files + + Parameters + ---------- + paths: list of str + The input file tree + path2: str or list of str + Root to construct the new list in. If this is already a list of str, we just + assert it has the right number of elements. + exists: bool (optional) + For a str destination, it is already exists (and is a dir), files should + end up inside. + flatten: bool (optional) + Whether to flatten the input directory tree structure so that the output files + are in the same directory. + + Returns + ------- + list of str + """ + + if isinstance(path2, str): + path2 = path2.rstrip("/") + + if flatten: + path2 = ["/".join((path2, p.split("/")[-1])) for p in paths] + else: + cp = common_prefix(paths) + if exists: + cp = cp.rsplit("/", 1)[0] + if not cp and all(not s.startswith("/") for s in paths): + path2 = ["/".join([path2, p]) for p in paths] + else: + path2 = [p.replace(cp, path2, 1) for p in paths] + else: + assert len(paths) == len(path2) + return path2 + + +def is_exception(obj: Any) -> bool: + return isinstance(obj, BaseException) + + +def isfilelike(f: Any) -> TypeGuard[IO[bytes]]: + return all(hasattr(f, attr) for attr in ["read", "close", "tell"]) + + +def get_protocol(url: str) -> str: + url = stringify_path(url) + parts = re.split(r"(\:\:|\://)", url, maxsplit=1) + if len(parts) > 1: + return parts[0] + return "file" + + +def can_be_local(path: str) -> bool: + """Can the given URL be used with open_local?""" + from fsspec import get_filesystem_class + + try: + return getattr(get_filesystem_class(get_protocol(path)), "local_file", False) + except (ValueError, ImportError): + # not in registry or import failed + return False + + +def get_package_version_without_import(name: str) -> str | None: + """For given package name, try to find the version without importing it + + Import and package.__version__ is still the backup here, so an import + *might* happen. + + Returns either the version string, or None if the package + or the version was not readily found. + """ + if name in sys.modules: + mod = sys.modules[name] + if hasattr(mod, "__version__"): + return mod.__version__ + try: + return version(name) + except: # noqa: E722 + pass + try: + import importlib + + mod = importlib.import_module(name) + return mod.__version__ + except (ImportError, AttributeError): + return None + + +def setup_logging( + logger: logging.Logger | None = None, + logger_name: str | None = None, + level: str = "DEBUG", + clear: bool = True, +) -> logging.Logger: + if logger is None and logger_name is None: + raise ValueError("Provide either logger object or logger name") + logger = logger or logging.getLogger(logger_name) + handle = logging.StreamHandler() + formatter = logging.Formatter( + "%(asctime)s - %(name)s - %(levelname)s - %(funcName)s -- %(message)s" + ) + handle.setFormatter(formatter) + if clear: + logger.handlers.clear() + logger.addHandler(handle) + logger.setLevel(level) + return logger + + +def _unstrip_protocol(name: str, fs: AbstractFileSystem) -> str: + return fs.unstrip_protocol(name) + + +def mirror_from( + origin_name: str, methods: Iterable[str] +) -> Callable[[type[T]], type[T]]: + """Mirror attributes and methods from the given + origin_name attribute of the instance to the + decorated class""" + + def origin_getter(method: str, self: Any) -> Any: + origin = getattr(self, origin_name) + return getattr(origin, method) + + def wrapper(cls: type[T]) -> type[T]: + for method in methods: + wrapped_method = partial(origin_getter, method) + setattr(cls, method, property(wrapped_method)) + return cls + + return wrapper + + +@contextlib.contextmanager +def nullcontext(obj: T) -> Iterator[T]: + yield obj + + +def merge_offset_ranges( + paths: list[str], + starts: list[int] | int, + ends: list[int] | int, + max_gap: int = 0, + max_block: int | None = None, + sort: bool = True, +) -> tuple[list[str], list[int], list[int]]: + """Merge adjacent byte-offset ranges when the inter-range + gap is <= `max_gap`, and when the merged byte range does not + exceed `max_block` (if specified). By default, this function + will re-order the input paths and byte ranges to ensure sorted + order. If the user can guarantee that the inputs are already + sorted, passing `sort=False` will skip the re-ordering. + """ + # Check input + if not isinstance(paths, list): + raise TypeError + if not isinstance(starts, list): + starts = [starts] * len(paths) + if not isinstance(ends, list): + ends = [ends] * len(paths) + if len(starts) != len(paths) or len(ends) != len(paths): + raise ValueError + + # Early Return + if len(starts) <= 1: + return paths, starts, ends + + starts = [s or 0 for s in starts] + # Sort by paths and then ranges if `sort=True` + if sort: + paths, starts, ends = ( + list(v) + for v in zip( + *sorted( + zip(paths, starts, ends), + ) + ) + ) + + if paths: + # Loop through the coupled `paths`, `starts`, and + # `ends`, and merge adjacent blocks when appropriate + new_paths = paths[:1] + new_starts = starts[:1] + new_ends = ends[:1] + for i in range(1, len(paths)): + if paths[i] == paths[i - 1] and new_ends[-1] is None: + continue + elif ( + paths[i] != paths[i - 1] + or ((starts[i] - new_ends[-1]) > max_gap) + or (max_block is not None and (ends[i] - new_starts[-1]) > max_block) + ): + # Cannot merge with previous block. + # Add new `paths`, `starts`, and `ends` elements + new_paths.append(paths[i]) + new_starts.append(starts[i]) + new_ends.append(ends[i]) + else: + # Merge with previous block by updating the + # last element of `ends` + new_ends[-1] = ends[i] + return new_paths, new_starts, new_ends + + # `paths` is empty. Just return input lists + return paths, starts, ends + + +def file_size(filelike: IO[bytes]) -> int: + """Find length of any open read-mode file-like""" + pos = filelike.tell() + try: + return filelike.seek(0, 2) + finally: + filelike.seek(pos) + + +@contextlib.contextmanager +def atomic_write(path: str, mode: str = "wb"): + """ + A context manager that opens a temporary file next to `path` and, on exit, + replaces `path` with the temporary file, thereby updating `path` + atomically. + """ + fd, fn = tempfile.mkstemp( + dir=os.path.dirname(path), prefix=os.path.basename(path) + "-" + ) + try: + with open(fd, mode) as fp: + yield fp + except BaseException: + with contextlib.suppress(FileNotFoundError): + os.unlink(fn) + raise + else: + os.replace(fn, path) + + +def _translate(pat, STAR, QUESTION_MARK): + # Copied from: https://github.com/python/cpython/pull/106703. + res: list[str] = [] + add = res.append + i, n = 0, len(pat) + while i < n: + c = pat[i] + i = i + 1 + if c == "*": + # compress consecutive `*` into one + if (not res) or res[-1] is not STAR: + add(STAR) + elif c == "?": + add(QUESTION_MARK) + elif c == "[": + j = i + if j < n and pat[j] == "!": + j = j + 1 + if j < n and pat[j] == "]": + j = j + 1 + while j < n and pat[j] != "]": + j = j + 1 + if j >= n: + add("\\[") + else: + stuff = pat[i:j] + if "-" not in stuff: + stuff = stuff.replace("\\", r"\\") + else: + chunks = [] + k = i + 2 if pat[i] == "!" else i + 1 + while True: + k = pat.find("-", k, j) + if k < 0: + break + chunks.append(pat[i:k]) + i = k + 1 + k = k + 3 + chunk = pat[i:j] + if chunk: + chunks.append(chunk) + else: + chunks[-1] += "-" + # Remove empty ranges -- invalid in RE. + for k in range(len(chunks) - 1, 0, -1): + if chunks[k - 1][-1] > chunks[k][0]: + chunks[k - 1] = chunks[k - 1][:-1] + chunks[k][1:] + del chunks[k] + # Escape backslashes and hyphens for set difference (--). + # Hyphens that create ranges shouldn't be escaped. + stuff = "-".join( + s.replace("\\", r"\\").replace("-", r"\-") for s in chunks + ) + # Escape set operations (&&, ~~ and ||). + stuff = re.sub(r"([&~|])", r"\\\1", stuff) + i = j + 1 + if not stuff: + # Empty range: never match. + add("(?!)") + elif stuff == "!": + # Negated empty range: match any character. + add(".") + else: + if stuff[0] == "!": + stuff = "^" + stuff[1:] + elif stuff[0] in ("^", "["): + stuff = "\\" + stuff + add(f"[{stuff}]") + else: + add(re.escape(c)) + assert i == n + return res + + +def glob_translate(pat): + # Copied from: https://github.com/python/cpython/pull/106703. + # The keyword parameters' values are fixed to: + # recursive=True, include_hidden=True, seps=None + """Translate a pathname with shell wildcards to a regular expression.""" + if os.path.altsep: + seps = os.path.sep + os.path.altsep + else: + seps = os.path.sep + escaped_seps = "".join(map(re.escape, seps)) + any_sep = f"[{escaped_seps}]" if len(seps) > 1 else escaped_seps + not_sep = f"[^{escaped_seps}]" + one_last_segment = f"{not_sep}+" + one_segment = f"{one_last_segment}{any_sep}" + any_segments = f"(?:.+{any_sep})?" + any_last_segments = ".*" + results = [] + parts = re.split(any_sep, pat) + last_part_idx = len(parts) - 1 + for idx, part in enumerate(parts): + if part == "*": + results.append(one_segment if idx < last_part_idx else one_last_segment) + continue + if part == "**": + results.append(any_segments if idx < last_part_idx else any_last_segments) + continue + elif "**" in part: + raise ValueError( + "Invalid pattern: '**' can only be an entire path component" + ) + if part: + results.extend(_translate(part, f"{not_sep}*", not_sep)) + if idx < last_part_idx: + results.append(any_sep) + res = "".join(results) + return rf"(?s:{res})\Z" diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/INSTALLER b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/METADATA b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..267439298875d4fb658a6913dc51b48c9026e3ea --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/METADATA @@ -0,0 +1,45 @@ +Metadata-Version: 2.4 +Name: nvidia-nccl-cu12 +Version: 2.27.5 +Summary: NVIDIA Collective Communication Library (NCCL) Runtime +Home-page: https://developer.nvidia.com/cuda-zone +Author: Nvidia CUDA Installer Team +Author-email: compute_installer@nvidia.com +License: BSD-3-Clause +Keywords: cuda,nvidia,runtime,machine learning,deep learning +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: Other/Proprietary License +Classifier: Natural Language :: English +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Requires-Python: >=3 +License-File: License.txt +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: requires-python +Dynamic: summary + +NCCL (pronounced "Nickel") is a stand-alone library of standard collective communication routines for GPUs, implementing all-reduce, all-gather, reduce, broadcast, and reduce-scatter. It has been optimized to achieve high bandwidth on any platform using PCIe, NVLink, NVswitch, as well as networking using InfiniBand Verbs or TCP/IP sockets. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/RECORD b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..394254ba8d2994b3c8b4a076303041129c0b9620 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/RECORD @@ -0,0 +1,9 @@ +nvidia/nccl/include/nccl.h,sha256=SyQKH6eYWMqM3_z1wvxArqyos-rsYXKCE3FfCQKro6g,22566 +nvidia/nccl/lib/libnccl.so.2,sha256=HZwQMi76zeaVz2QNsfKfwVhskp8Qh_DhIC0tXnD7cWg,429628328 +nvidia_nccl_cu12-2.27.5.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +nvidia_nccl_cu12-2.27.5.dist-info/METADATA,sha256=8QYX3uAOzTd6A-kQPrzyDDMwXQ30cZGlQEmKtF-Kxn0,2019 +nvidia_nccl_cu12-2.27.5.dist-info/RECORD,, +nvidia_nccl_cu12-2.27.5.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia_nccl_cu12-2.27.5.dist-info/WHEEL,sha256=gy6FWQgpujK_dnYc155G2NL32NQjpi5ebTEXjh8SGZQ,144 +nvidia_nccl_cu12-2.27.5.dist-info/licenses/License.txt,sha256=DwF0prTgszrCY3W_cpUzB1sy9MUaW2gCo9dC19zcmnY,1895 +nvidia_nccl_cu12-2.27.5.dist-info/top_level.txt,sha256=fTkAtiFuL16nUrB9ytDDtpytz2t0B4NvYTnRzwAhO14,7 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/REQUESTED b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/WHEEL b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..29738220b339f398b2cbbc9ac8ccb38a39bdd7b2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-manylinux2014_x86_64 +Tag: py3-none-manylinux_2_17_x86_64 + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/licenses/License.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/licenses/License.txt new file mode 100644 index 0000000000000000000000000000000000000000..bcd1867a02a6a8c1e592b92e2e50f34e531f2d87 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/licenses/License.txt @@ -0,0 +1,39 @@ + + Copyright (c) 2015-2020, NVIDIA CORPORATION. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of NVIDIA CORPORATION, Lawrence Berkeley National + Laboratory, the U.S. Department of Energy, nor the names of their + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + The U.S. Department of Energy funded the development of this software + under subcontract 7078610 with Lawrence Berkeley National Laboratory. + + +This code also includes files from the NVIDIA Tools Extension SDK project. + +See: + + https://github.com/NVIDIA/NVTX + +for more information and license details. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/top_level.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..862f7abf232cdfbb928609856247292e81c9decb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nccl_cu12-2.27.5.dist-info/top_level.txt @@ -0,0 +1 @@ +nvidia diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/INSTALLER b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/License.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/License.txt new file mode 100644 index 0000000000000000000000000000000000000000..bd8b243dfa02d4e7080150180520f742d2861d15 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/License.txt @@ -0,0 +1,218 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +--- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/METADATA b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b31bb610bfc7d774be17ed73f760af6e477d819b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/METADATA @@ -0,0 +1,44 @@ +Metadata-Version: 2.2 +Name: nvidia-nvtx-cu12 +Version: 12.8.90 +Summary: NVIDIA Tools Extension +Home-page: https://developer.nvidia.com/cuda-zone +Author: Nvidia CUDA Installer Team +Author-email: compute_installer@nvidia.com +License: Apache 2.0 +Keywords: cuda,nvidia,runtime,machine learning,deep learning +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: Other/Proprietary License +Classifier: Natural Language :: English +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Requires-Python: >=3 +License-File: License.txt +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: requires-python +Dynamic: summary + +A C-based API for annotating events, code ranges, and resources in your applications. Applications which integrate NVTX can use the Visual Profiler to capture and visualize these events and ranges. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/RECORD b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..da96e8802ca498ff45250b4c1dc28f291438c75f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/RECORD @@ -0,0 +1,33 @@ +nvidia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/nvtx/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/nvtx/include/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/nvtx/include/nvToolsExt.h,sha256=TFV6WIqHrKh2wbll0lk3SsSL3KMoDav5cnwgEGuCbXI,55254 +nvidia/nvtx/include/nvToolsExtCuda.h,sha256=UDA1pbmvoRFmlJ11Et9tIMEztOtOVw-10mO27Q6K8jg,6009 +nvidia/nvtx/include/nvToolsExtCudaRt.h,sha256=6IbgdRGObly53jzRqvsZ4FQoTrXJOJwSyCOLuXr9ncA,5192 +nvidia/nvtx/include/nvToolsExtOpenCL.h,sha256=gETZH9ch_o6MYE_BYQ2pj9SSuxyAo1H4ptmRK-DMWSo,8360 +nvidia/nvtx/include/nvToolsExtSync.h,sha256=wqONIiycUPaUUCzQBmCippilgKt8sOL9tpzG773u0nY,14562 +nvidia/nvtx/include/nvtx3/nvToolsExt.h,sha256=TFEF3fx1043EwMdbS7FqvvavwK0koZeGrIOAsCrB12s,52247 +nvidia/nvtx/include/nvtx3/nvToolsExtCuda.h,sha256=4ZbZHUMcmHRf4SdKB7nH0E3uHd_9ZhZBuwuWPItK-Vs,6204 +nvidia/nvtx/include/nvtx3/nvToolsExtCudaRt.h,sha256=boW0zdYobNFFE9wwxCyzBGBLcSGtdbQ5osKjQGNC2E8,5393 +nvidia/nvtx/include/nvtx3/nvToolsExtOpenCL.h,sha256=RPfsZl3lHAPIOCzTipmz07-vaiIO4cxelcx12EjB2L0,8563 +nvidia/nvtx/include/nvtx3/nvToolsExtSync.h,sha256=C-HIVBaupxYom3BqMggQ_ePq1bxFhw8kXsOfYJKBWrI,14756 +nvidia/nvtx/include/nvtx3/nvtxDetail/nvtxImpl.h,sha256=jEnYF3MyLsD72euw2It3Bz0X0GK4Xv_htEd8BeIrPjY,23333 +nvidia/nvtx/include/nvtx3/nvtxDetail/nvtxImplCore.h,sha256=sYpWqZfYrjsMddxtezPX3qSTIbAOn4dlEoLiYQ9M2nM,9756 +nvidia/nvtx/include/nvtx3/nvtxDetail/nvtxImplCudaRt_v3.h,sha256=SoaiprvsI80yLmEAnlFX0iFufv6RtKjjMMrVwQZjjQI,4775 +nvidia/nvtx/include/nvtx3/nvtxDetail/nvtxImplCuda_v3.h,sha256=IEor-ISqComCRGVDdIzKBLU3eWCuDI0Igqz-eRKKcvg,5550 +nvidia/nvtx/include/nvtx3/nvtxDetail/nvtxImplOpenCL_v3.h,sha256=iPR2x74bJE3plFQBT9FWGBaTm4sC-Pll6WAjpKRnz7g,8275 +nvidia/nvtx/include/nvtx3/nvtxDetail/nvtxImplSync_v3.h,sha256=TqwQfEUVbwc58bpHioE13NMweFhOuHXNql65BnLzhvc,5022 +nvidia/nvtx/include/nvtx3/nvtxDetail/nvtxInit.h,sha256=foajOFacvLGx3BN5ntw5v8o4J3OY4hqkVZE5ZC0x3e4,14716 +nvidia/nvtx/include/nvtx3/nvtxDetail/nvtxInitDecls.h,sha256=-Qyxcy9CDXOBhEtYZ8L7iYd6daJ9aCeyQM48X0BafMM,9361 +nvidia/nvtx/include/nvtx3/nvtxDetail/nvtxInitDefs.h,sha256=dLhOV4knhNrmT2DnUNzXreOt_Qc6GAa3yIlmqJFCeVI,35432 +nvidia/nvtx/include/nvtx3/nvtxDetail/nvtxLinkOnce.h,sha256=Jp-z6LTz_p8fKRulcFfdcskIxzcZ6ybbHkGB9mpJa2M,3863 +nvidia/nvtx/include/nvtx3/nvtxDetail/nvtxTypes.h,sha256=jkbCwyvIP1G-Ef8SwYp4kDi69hjZbzaxKSk7ScgrNI8,17352 +nvidia/nvtx/lib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/nvtx/lib/libnvToolsExt.so.1,sha256=xJj8urAgKIbCegrerESr8jOt4D0waA_6LSq-k6uI2RM,36024 +nvidia_nvtx_cu12-12.8.90.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +nvidia_nvtx_cu12-12.8.90.dist-info/License.txt,sha256=nkXoVr7czun2clQILKEYUdlU3i_tdEjEvtGa2aq5mpE,12262 +nvidia_nvtx_cu12-12.8.90.dist-info/METADATA,sha256=xjwj4E6M8EFDch_3GMuoeirlYwpQRRt3-DV6DSYTPPE,1820 +nvidia_nvtx_cu12-12.8.90.dist-info/RECORD,, +nvidia_nvtx_cu12-12.8.90.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia_nvtx_cu12-12.8.90.dist-info/WHEEL,sha256=ygM8qpYgOvrn5C-8vbfzPi-0iFPECh71lLWqkqrTjYw,144 +nvidia_nvtx_cu12-12.8.90.dist-info/top_level.txt,sha256=fTkAtiFuL16nUrB9ytDDtpytz2t0B4NvYTnRzwAhO14,7 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/REQUESTED b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/WHEEL b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..287a9d7e1a3d4435e9542cc8216b8c5eaf2c0ed2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.8.0) +Root-Is-Purelib: true +Tag: py3-none-manylinux2014_x86_64 +Tag: py3-none-manylinux_2_17_x86_64 + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/top_level.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..862f7abf232cdfbb928609856247292e81c9decb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_nvtx_cu12-12.8.90.dist-info/top_level.txt @@ -0,0 +1 @@ +nvidia diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b057eb43802b02d6a10d2c5a62046db1d271670c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/__init__.py @@ -0,0 +1,57 @@ +from optuna import distributions +from optuna import exceptions +from optuna import integration +from optuna import logging +from optuna import pruners +from optuna import samplers +from optuna import search_space +from optuna import storages +from optuna import study +from optuna import trial +from optuna import version +from optuna._imports import _LazyImport +from optuna.exceptions import TrialPruned +from optuna.study import copy_study +from optuna.study import create_study +from optuna.study import delete_study +from optuna.study import get_all_study_names +from optuna.study import get_all_study_summaries +from optuna.study import load_study +from optuna.study import Study +from optuna.trial import create_trial +from optuna.trial import Trial +from optuna.version import __version__ + + +__all__ = [ + "Study", + "Trial", + "TrialPruned", + "__version__", + "artifacts", + "copy_study", + "create_study", + "create_trial", + "delete_study", + "distributions", + "exceptions", + "get_all_study_names", + "get_all_study_summaries", + "importance", + "integration", + "load_study", + "logging", + "pruners", + "samplers", + "search_space", + "storages", + "study", + "trial", + "version", + "visualization", +] + + +artifacts = _LazyImport("optuna.artifacts") +importance = _LazyImport("optuna.importance") +visualization = _LazyImport("optuna.visualization") diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e44e43c5eaa3d6e70a265764914b5d504c808c2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/__pycache__/distributions.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/__pycache__/distributions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcee1120adea7b279e0ebb010871ae7867512f33 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/__pycache__/distributions.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_callbacks.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..6eb1897eb4c65b8ab738289156ac7f12fb3c16c2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_callbacks.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from optuna.trial import TrialState + + +if TYPE_CHECKING: + from collections.abc import Container + + from optuna.study import Study + from optuna.trial import FrozenTrial + + +class MaxTrialsCallback: + """Set a maximum number of trials before ending the study. + + While the ``n_trials`` argument of :meth:`optuna.study.Study.optimize` sets the number of + trials that will be run, you may want to continue running until you have a certain number of + successfully completed trials or stop the study when you have a certain number of trials that + fail. This ``MaxTrialsCallback`` class allows you to set a maximum number of trials for a + particular :class:`~optuna.trial.TrialState` before stopping the study. + + Example: + + .. testcode:: + + import optuna + from optuna.study import MaxTrialsCallback + from optuna.trial import TrialState + + + def objective(trial): + x = trial.suggest_float("x", -1, 1) + return x**2 + + + study = optuna.create_study() + study.optimize( + objective, + callbacks=[MaxTrialsCallback(10, states=(TrialState.COMPLETE,))], + ) + + Args: + n_trials: + The max number of trials. Must be set to an integer. + states: + Tuple of the :class:`~optuna.trial.TrialState` to be counted + towards the max trials limit. Default value is ``(TrialState.COMPLETE,)``. + If :obj:`None`, count all states. + """ + + def __init__( + self, n_trials: int, states: Container[TrialState] | None = (TrialState.COMPLETE,) + ) -> None: + self._n_trials = n_trials + self._states = states + + def __call__(self, study: Study, trial: FrozenTrial) -> None: + trials = study.get_trials(deepcopy=False, states=self._states) + n_complete = len(trials) + if n_complete >= self._n_trials: + study.stop() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_convert_positional_args.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_convert_positional_args.py new file mode 100644 index 0000000000000000000000000000000000000000..4865d9e6297cee46073e167d12ac04c0fca64ed7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_convert_positional_args.py @@ -0,0 +1,139 @@ +from __future__ import annotations + +from functools import wraps +from inspect import Parameter +from inspect import signature +from typing import Any +from typing import TYPE_CHECKING +from typing import TypeVar +import warnings + +from optuna._deprecated import _validate_two_version +from optuna._experimental import _validate_version + + +if TYPE_CHECKING: + from collections.abc import Callable + from collections.abc import Sequence + + from typing_extensions import ParamSpec + + _P = ParamSpec("_P") + _T = TypeVar("_T") + + +_DEPRECATION_WARNING_TEMPLATE = ( + "Positional arguments {deprecated_positional_arg_names} in {func_name}() " + "have been deprecated since v{d_ver}. " + "They will be replaced with the corresponding keyword arguments in v{r_ver}, " + "so please use the keyword specification instead. " + "See https://github.com/optuna/optuna/releases/tag/v{d_ver} for details." +) + + +def _get_positional_arg_names(func: "Callable[_P, _T]") -> list[str]: + params = signature(func).parameters + positional_arg_names = [ + name + for name, p in params.items() + if p.default == Parameter.empty and p.kind == p.POSITIONAL_OR_KEYWORD + ] + return positional_arg_names + + +def _infer_kwargs(previous_positional_arg_names: Sequence[str], *args: Any) -> dict[str, Any]: + inferred_kwargs = {arg_name: val for val, arg_name in zip(args, previous_positional_arg_names)} + return inferred_kwargs + + +def convert_positional_args( + *, + previous_positional_arg_names: Sequence[str], + deprecated_version: str, + removed_version: str, + warning_stacklevel: int = 2, +) -> "Callable[[Callable[_P, _T]], Callable[_P, _T]]": + """Convert positional arguments to keyword arguments. + + Args: + previous_positional_arg_names: + List of names previously given as positional arguments. + warning_stacklevel: + Level of the stack trace where decorated function locates. + deprecated_version: + The version in which the use of positional arguments is deprecated. + removed_version: + The version in which the use of positional arguments will be removed. + """ + + if deprecated_version is not None or removed_version is not None: + if deprecated_version is None: + raise ValueError( + "deprecated_version must not be None when removed_version is specified." + ) + if removed_version is None: + raise ValueError( + "removed_version must not be None when deprecated_version is specified." + ) + + _validate_version(deprecated_version) + _validate_version(removed_version) + _validate_two_version(deprecated_version, removed_version) + + def converter_decorator(func: "Callable[_P, _T]") -> "Callable[_P, _T]": + + assert set(previous_positional_arg_names).issubset(set(signature(func).parameters)), ( + f"{set(previous_positional_arg_names)} is not a subset of" + f" {set(signature(func).parameters)}" + ) + + @wraps(func) + def converter_wrapper(*args: Any, **kwargs: Any) -> "_T": + warning_messages = [] + positional_arg_names = _get_positional_arg_names(func) + inferred_kwargs = _infer_kwargs(previous_positional_arg_names, *args) + + if len(inferred_kwargs) > len(positional_arg_names): + expected_kwds = set(inferred_kwargs) - set(positional_arg_names) + warning_messages.append( + f"{func.__name__}() got {expected_kwds} as positional arguments " + "but they were expected to be given as keyword arguments." + ) + + if deprecated_version or removed_version: + warning_messages.append( + _DEPRECATION_WARNING_TEMPLATE.format( + deprecated_positional_arg_names=previous_positional_arg_names, + func_name=func.__name__, + d_ver=deprecated_version, + r_ver=removed_version, + ) + ) + + if warning_messages: + warnings.warn( + "\n".join(warning_messages), FutureWarning, stacklevel=warning_stacklevel + ) + + if len(args) > len(previous_positional_arg_names): + raise TypeError( + f"{func.__name__}() takes {len(previous_positional_arg_names)} positional" + f" arguments but {len(args)} were given." + ) + + duplicated_kwds = set(kwargs).intersection(inferred_kwargs) + if len(duplicated_kwds): + # When specifying positional arguments that are not located at the end of args as + # keyword arguments, raise TypeError as follows by imitating the Python standard + # behavior + raise TypeError( + f"{func.__name__}() got multiple values for arguments {duplicated_kwds}." + ) + + kwargs.update(inferred_kwargs) + + return func(**kwargs) # type: ignore[call-arg] + + return converter_wrapper + + return converter_decorator diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_deprecated.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..b5c621352933058afe207f205c56760f89a69d22 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_deprecated.py @@ -0,0 +1,199 @@ +from __future__ import annotations + +import functools +import textwrap +from typing import Any +from typing import TYPE_CHECKING +from typing import TypeVar +import warnings + +from packaging import version + +from optuna._experimental import _get_docstring_indent +from optuna._experimental import _validate_version + + +if TYPE_CHECKING: + from collections.abc import Callable + + from typing_extensions import ParamSpec + + FT = TypeVar("FT") + FP = ParamSpec("FP") + CT = TypeVar("CT") + + +_DEPRECATION_NOTE_TEMPLATE = """ + +.. warning:: + Deprecated in v{d_ver}. This feature will be removed in the future. The removal of this + feature is currently scheduled for v{r_ver}, but this schedule is subject to change. + See https://github.com/optuna/optuna/releases/tag/v{d_ver}. +""" + + +_DEPRECATION_WARNING_TEMPLATE = ( + "{name} has been deprecated in v{d_ver}. " + "This feature will be removed in v{r_ver}. " + "See https://github.com/optuna/optuna/releases/tag/v{d_ver}." +) + + +def _validate_two_version(old_version: str, new_version: str) -> None: + if version.parse(old_version) > version.parse(new_version): + raise ValueError( + "Invalid version relationship. The deprecated version must be smaller than " + "the removed version, but (deprecated version, removed version) = ({}, {}) are " + "specified.".format(old_version, new_version) + ) + + +def _format_text(text: str) -> str: + return "\n\n" + textwrap.indent(text.strip(), " ") + "\n" + + +def deprecated_func( + deprecated_version: str, + removed_version: str, + name: str | None = None, + text: str | None = None, +) -> "Callable[[Callable[FP, FT]], Callable[FP, FT]]": + """Decorate function as deprecated. + + Args: + deprecated_version: + The version in which the target feature is deprecated. + removed_version: + The version in which the target feature will be removed. + name: + The name of the feature. Defaults to the function name. Optional. + text: + The additional text for the deprecation note. The default note is build using specified + ``deprecated_version`` and ``removed_version``. If you want to provide additional + information, please specify this argument yourself. + + .. note:: + The default deprecation note is as follows: "Deprecated in v{d_ver}. This feature + will be removed in the future. The removal of this feature is currently scheduled + for v{r_ver}, but this schedule is subject to change. See + https://github.com/optuna/optuna/releases/tag/v{d_ver}." + + .. note:: + The specified text is concatenated after the default deprecation note. + """ + + _validate_version(deprecated_version) + _validate_version(removed_version) + _validate_two_version(deprecated_version, removed_version) + + def decorator(func: "Callable[FP, FT]") -> "Callable[FP, FT]": + if func.__doc__ is None: + func.__doc__ = "" + + note = _DEPRECATION_NOTE_TEMPLATE.format(d_ver=deprecated_version, r_ver=removed_version) + if text is not None: + note += _format_text(text) + indent = _get_docstring_indent(func.__doc__) + func.__doc__ = func.__doc__.strip() + textwrap.indent(note, indent) + indent + + @functools.wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> "FT": + """Decorates a function as deprecated. + + This decorator is supposed to be applied to the deprecated function. + """ + + message = _DEPRECATION_WARNING_TEMPLATE.format( + name=(name if name is not None else func.__name__), + d_ver=deprecated_version, + r_ver=removed_version, + ) + if text is not None: + message += " " + text + warnings.warn(message, FutureWarning, stacklevel=2) + + return func(*args, **kwargs) + + return wrapper + + return decorator + + +def deprecated_class( + deprecated_version: str, + removed_version: str, + name: str | None = None, + text: str | None = None, +) -> "Callable[[CT], CT]": + """Decorate class as deprecated. + + Args: + deprecated_version: + The version in which the target feature is deprecated. + removed_version: + The version in which the target feature will be removed. + name: + The name of the feature. Defaults to the class name. Optional. + text: + The additional text for the deprecation note. The default note is build using specified + ``deprecated_version`` and ``removed_version``. If you want to provide additional + information, please specify this argument yourself. + + .. note:: + The default deprecation note is as follows: "Deprecated in v{d_ver}. This feature + will be removed in the future. The removal of this feature is currently scheduled + for v{r_ver}, but this schedule is subject to change. See + https://github.com/optuna/optuna/releases/tag/v{d_ver}." + + .. note:: + The specified text is concatenated after the default deprecation note. + """ + + _validate_version(deprecated_version) + _validate_version(removed_version) + _validate_two_version(deprecated_version, removed_version) + + def decorator(cls: "CT") -> "CT": + def wrapper(cls: "CT") -> "CT": + """Decorates a class as deprecated. + + This decorator is supposed to be applied to the deprecated class. + """ + _original_init = getattr(cls, "__init__") + _original_name = getattr(cls, "__name__") + + @functools.wraps(_original_init) + def wrapped_init(self: Any, *args: Any, **kwargs: Any) -> None: + message = _DEPRECATION_WARNING_TEMPLATE.format( + name=(name if name is not None else _original_name), + d_ver=deprecated_version, + r_ver=removed_version, + ) + if text is not None: + message += " " + text + warnings.warn( + message, + FutureWarning, + stacklevel=2, + ) + + _original_init(self, *args, **kwargs) + + setattr(cls, "__init__", wrapped_init) + + if cls.__doc__ is None: + cls.__doc__ = "" + + note = _DEPRECATION_NOTE_TEMPLATE.format( + d_ver=deprecated_version, r_ver=removed_version + ) + if text is not None: + note += _format_text(text) + indent = _get_docstring_indent(cls.__doc__) + cls.__doc__ = cls.__doc__.strip() + textwrap.indent(note, indent) + indent + + return cls + + return wrapper(cls) + + return decorator diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_experimental.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_experimental.py new file mode 100644 index 0000000000000000000000000000000000000000..8cb0f87554299e8a5a4db372186e9882e9e6df2f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_experimental.py @@ -0,0 +1,140 @@ +from __future__ import annotations + +import functools +import textwrap +from typing import Any +from typing import TYPE_CHECKING +from typing import TypeVar +import warnings + +from optuna.exceptions import ExperimentalWarning + + +if TYPE_CHECKING: + from collections.abc import Callable + + from typing_extensions import ParamSpec + + FT = TypeVar("FT") + FP = ParamSpec("FP") + CT = TypeVar("CT") + + +_EXPERIMENTAL_NOTE_TEMPLATE = """ + +.. note:: + Added in v{ver} as an experimental feature. The interface may change in newer versions + without prior notice. See https://github.com/optuna/optuna/releases/tag/v{ver}. +""" + + +def warn_experimental_argument(option_name: str) -> None: + warnings.warn( + f"Argument ``{option_name}`` is an experimental feature." + " The interface can change in the future.", + ExperimentalWarning, + ) + + +def _validate_version(version: str) -> None: + if not isinstance(version, str) or len(version.split(".")) != 3: + raise ValueError( + "Invalid version specification. Must follow `x.y.z` format but `{}` is given".format( + version + ) + ) + + +def _get_docstring_indent(docstring: str) -> str: + return docstring.split("\n")[-1] if "\n" in docstring else "" + + +def experimental_func( + version: str, + name: str | None = None, +) -> Callable[[Callable[FP, FT]], Callable[FP, FT]]: + """Decorate function as experimental. + + Args: + version: The first version that supports the target feature. + name: The name of the feature. Defaults to fully qualified name of + the function, i.e. `f"{func.__module__}.{func.__qualname__}"`. Optional. + """ + + _validate_version(version) + + def decorator(func: Callable[FP, FT]) -> Callable[FP, FT]: + if func.__doc__ is None: + func.__doc__ = "" + + note = _EXPERIMENTAL_NOTE_TEMPLATE.format(ver=version) + indent = _get_docstring_indent(func.__doc__) + func.__doc__ = func.__doc__.strip() + textwrap.indent(note, indent) + indent + + _name = name or f"{func.__module__}.{func.__qualname__}" + + @functools.wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> FT: + warnings.warn( + "{} is experimental (supported from v{}). " + "The interface can change in the future.".format(_name, version), + ExperimentalWarning, + stacklevel=2, + ) + + return func(*args, **kwargs) + + return wrapper + + return decorator + + +def experimental_class( + version: str, + name: str | None = None, +) -> Callable[[CT], CT]: + """Decorate class as experimental. + + Args: + version: The first version that supports the target feature. + name: The name of the feature. Defaults to the class name. Optional. + """ + + _validate_version(version) + + def decorator(cls: CT) -> CT: + def wrapper(cls: CT) -> CT: + """Decorates a class as experimental. + + This decorator is supposed to be applied to the experimental class. + """ + _original_init = getattr(cls, "__init__") + _original_name = getattr(cls, "__name__") + + @functools.wraps(_original_init) + def wrapped_init(self: Any, *args: Any, **kwargs: Any) -> None: + warnings.warn( + "{} is experimental (supported from v{}). " + "The interface can change in the future.".format( + name if name is not None else _original_name, version + ), + ExperimentalWarning, + stacklevel=2, + ) + + _original_init(self, *args, **kwargs) + + setattr(cls, "__init__", wrapped_init) + + if cls.__doc__ is None: + cls.__doc__ = "" + + note = _EXPERIMENTAL_NOTE_TEMPLATE.format(ver=version) + indent = _get_docstring_indent(cls.__doc__) + cls.__doc__ = cls.__doc__.strip() + textwrap.indent(note, indent) + indent + + return cls + + return wrapper(cls) + + return decorator diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/acqf.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/acqf.py new file mode 100644 index 0000000000000000000000000000000000000000..dff9f7799d3c75cc8723b1df1a5a4a47c2304205 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/acqf.py @@ -0,0 +1,310 @@ +from __future__ import annotations + +from abc import ABC +from abc import abstractmethod +import math +from typing import cast +from typing import TYPE_CHECKING + +import numpy as np + +from optuna._hypervolume import get_non_dominated_box_bounds +from optuna.study._multi_objective import _is_pareto_front + + +if TYPE_CHECKING: + import torch + + from optuna._gp.gp import GPRegressor + from optuna._gp.search_space import SearchSpace +else: + from optuna._imports import _LazyImport + + torch = _LazyImport("torch") + + +def _sample_from_normal_sobol(dim: int, n_samples: int, seed: int | None) -> torch.Tensor: + # NOTE(nabenabe): Normal Sobol sampling based on BoTorch. + # https://github.com/pytorch/botorch/blob/v0.13.0/botorch/sampling/qmc.py#L26-L97 + # https://github.com/pytorch/botorch/blob/v0.13.0/botorch/utils/sampling.py#L109-L138 + sobol_samples = torch.quasirandom.SobolEngine( # type: ignore[no-untyped-call] + dimension=dim, scramble=True, seed=seed + ).draw(n_samples, dtype=torch.float64) + samples = 2.0 * (sobol_samples - 0.5) # The Sobol sequence in [-1, 1]. + # Inverse transform to standard normal (values to close to -1 or 1 result in infinity). + return torch.erfinv(samples) * float(np.sqrt(2)) + + +def logehvi( + Y_post: torch.Tensor, # (..., n_qmc_samples, n_objectives) + non_dominated_box_lower_bounds: torch.Tensor, # (n_boxes, n_objectives) + non_dominated_box_upper_bounds: torch.Tensor, # (n_boxes, n_objectives) +) -> torch.Tensor: # (..., ) + log_n_qmc_samples = float(np.log(Y_post.shape[-2])) + # This function calculates Eq. (1) of https://arxiv.org/abs/2006.05078. + # TODO(nabenabe): Adapt to Eq. (3) when we support batch optimization. + # TODO(nabenabe): Make the calculation here more numerically stable. + # cf. https://arxiv.org/abs/2310.20708 + # Check the implementations here: + # https://github.com/pytorch/botorch/blob/v0.13.0/botorch/utils/safe_math.py + # https://github.com/pytorch/botorch/blob/v0.13.0/botorch/acquisition/multi_objective/logei.py#L146-L266 + _EPS = torch.tensor(1e-12, dtype=torch.float64) # NOTE(nabenabe): grad becomes nan when EPS=0. + diff = torch.maximum( + _EPS, + torch.minimum(Y_post[..., None, :], non_dominated_box_upper_bounds) + - non_dominated_box_lower_bounds, + ) + # NOTE(nabenabe): logsumexp with dim=-1 is for the HVI calculation and that with dim=-2 is for + # expectation of the HVIs over the fixed_samples. + return torch.special.logsumexp(diff.log().sum(dim=-1), dim=(-2, -1)) - log_n_qmc_samples + + +def standard_logei(z: torch.Tensor) -> torch.Tensor: + # Return E_{x ~ N(0, 1)}[max(0, x+z)] + + # We switch the implementation depending on the value of z to + # avoid numerical instability. + small = z < -25 + + vals = torch.empty_like(z) + # Eq. (9) in ref: https://arxiv.org/pdf/2310.20708.pdf + # NOTE: We do not use the third condition because ours is good enough. + z_small = z[small] + z_normal = z[~small] + sqrt_2pi = math.sqrt(2 * math.pi) + # First condition + cdf = 0.5 * torch.special.erfc(-z_normal * math.sqrt(0.5)) + pdf = torch.exp(-0.5 * z_normal**2) * (1 / sqrt_2pi) + vals[~small] = torch.log(z_normal * cdf + pdf) + # Second condition + r = math.sqrt(0.5 * math.pi) * torch.special.erfcx(-z_small * math.sqrt(0.5)) + vals[small] = -0.5 * z_small**2 + torch.log((z_small * r + 1) * (1 / sqrt_2pi)) + return vals + + +def logei(mean: torch.Tensor, var: torch.Tensor, f0: float) -> torch.Tensor: + # Return E_{y ~ N(mean, var)}[max(0, y-f0)] + sigma = torch.sqrt(var) + st_val = standard_logei((mean - f0) / sigma) + val = torch.log(sigma) + st_val + return val + + +class BaseAcquisitionFunc(ABC): + def __init__(self, length_scales: np.ndarray, search_space: SearchSpace) -> None: + self.length_scales = length_scales + self.search_space = search_space + + @abstractmethod + def eval_acqf(self, x: torch.Tensor) -> torch.Tensor: + raise NotImplementedError + + def eval_acqf_no_grad(self, x: np.ndarray) -> np.ndarray: + with torch.no_grad(): + return self.eval_acqf(torch.from_numpy(x)).detach().numpy() + + def eval_acqf_with_grad(self, x: np.ndarray) -> tuple[float, np.ndarray]: + assert x.ndim == 1 + x_tensor = torch.from_numpy(x).requires_grad_(True) + val = self.eval_acqf(x_tensor) + val.backward() # type: ignore + return val.item(), x_tensor.grad.detach().numpy() # type: ignore + + +class LogEI(BaseAcquisitionFunc): + def __init__( + self, + gpr: GPRegressor, + search_space: SearchSpace, + threshold: float, + stabilizing_noise: float = 1e-12, + ) -> None: + self._gpr = gpr + self._stabilizing_noise = stabilizing_noise + self._threshold = threshold + super().__init__(gpr.length_scales, search_space) + + def eval_acqf(self, x: torch.Tensor) -> torch.Tensor: + mean, var = self._gpr.posterior(x) + # If there are no feasible trials, max_Y is set to -np.inf. + # If max_Y is set to -np.inf, we set logEI to zero to ignore it. + return ( + logei(mean=mean, var=var + self._stabilizing_noise, f0=self._threshold) + if not np.isneginf(self._threshold) + else torch.zeros(x.shape[:-1], dtype=torch.float64) + ) + + +class LogPI(BaseAcquisitionFunc): + def __init__( + self, + gpr: GPRegressor, + search_space: SearchSpace, + threshold: float, + stabilizing_noise: float = 1e-12, + ) -> None: + self._gpr = gpr + self._stabilizing_noise = stabilizing_noise + self._threshold = threshold + super().__init__(gpr.length_scales, search_space) + + def eval_acqf(self, x: torch.Tensor) -> torch.Tensor: + # Return the integral of N(mean, var) from f0 to inf. + # This is identical to the integral of N(0, 1) from (f0-mean)/sigma to inf. + # Return E_{y ~ N(mean, var)}[bool(y >= f0)] + mean, var = self._gpr.posterior(x) + sigma = torch.sqrt(var + self._stabilizing_noise) + # NOTE(nabenabe): integral from a to b of f(x) is integral from -b to -a of f(-x). + return torch.special.log_ndtr((mean - self._threshold) / sigma) + + +class UCB(BaseAcquisitionFunc): + def __init__( + self, + gpr: GPRegressor, + search_space: SearchSpace, + beta: float, + ) -> None: + self._gpr = gpr + self._beta = beta + super().__init__(gpr.length_scales, search_space) + + def eval_acqf(self, x: torch.Tensor) -> torch.Tensor: + mean, var = self._gpr.posterior(x) + return mean + torch.sqrt(self._beta * var) + + +class LCB(BaseAcquisitionFunc): + def __init__( + self, + gpr: GPRegressor, + search_space: SearchSpace, + beta: float, + ) -> None: + self._gpr = gpr + self._beta = beta + super().__init__(gpr.length_scales, search_space) + + def eval_acqf(self, x: torch.Tensor) -> torch.Tensor: + mean, var = self._gpr.posterior(x) + return mean - torch.sqrt(self._beta * var) + + +class ConstrainedLogEI(BaseAcquisitionFunc): + def __init__( + self, + gpr: GPRegressor, + search_space: SearchSpace, + threshold: float, + constraints_gpr_list: list[GPRegressor], + constraints_threshold_list: list[float], + stabilizing_noise: float = 1e-12, + ) -> None: + assert ( + len(constraints_gpr_list) == len(constraints_threshold_list) and constraints_gpr_list + ) + self._acqf = LogEI(gpr, search_space, threshold, stabilizing_noise) + self._constraints_acqf_list = [ + LogPI(_gpr, search_space, _threshold, stabilizing_noise) + for _gpr, _threshold in zip(constraints_gpr_list, constraints_threshold_list) + ] + super().__init__(gpr.length_scales, search_space) + + def eval_acqf(self, x: torch.Tensor) -> torch.Tensor: + # TODO(kAIto47802): Handle the infeasible case inside `ConstrainedLogEI` + # instead of `LogEI`. + return self._acqf.eval_acqf(x) + sum( + acqf.eval_acqf(x) for acqf in self._constraints_acqf_list + ) + + +class LogEHVI(BaseAcquisitionFunc): + def __init__( + self, + gpr_list: list[GPRegressor], + search_space: SearchSpace, + Y_train: torch.Tensor, + n_qmc_samples: int, + qmc_seed: int | None, + stabilizing_noise: float = 1e-12, + ) -> None: + def _get_non_dominated_box_bounds() -> tuple[torch.Tensor, torch.Tensor]: + # NOTE(nabenabe): Y is to be maximized, loss_vals is to be minimized. + loss_vals = -Y_train.numpy() + pareto_sols = loss_vals[_is_pareto_front(loss_vals, assume_unique_lexsorted=False)] + ref_point = np.max(loss_vals, axis=0) + ref_point = np.nextafter(np.maximum(1.1 * ref_point, 0.9 * ref_point), np.inf) + lbs, ubs = get_non_dominated_box_bounds(pareto_sols, ref_point) + # NOTE(nabenabe): Flip back the sign to make them compatible with maximization. + return torch.from_numpy(-ubs), torch.from_numpy(-lbs) + + self._stabilizing_noise = stabilizing_noise + self._gpr_list = gpr_list + self._fixed_samples = _sample_from_normal_sobol( + dim=Y_train.shape[-1], n_samples=n_qmc_samples, seed=qmc_seed + ) + self._non_dominated_box_lower_bounds, self._non_dominated_box_upper_bounds = ( + _get_non_dominated_box_bounds() + ) + # Since all the objectives are equally important, we simply use the mean of + # inverse of squared mean lengthscales over all the objectives. + # inverse_squared_lengthscales is used in optim_mixed.py. + # cf. https://github.com/optuna/optuna/blob/v4.3.0/optuna/_gp/optim_mixed.py#L200-L209 + super().__init__(np.mean([gpr.length_scales for gpr in gpr_list], axis=0), search_space) + + def eval_acqf(self, x: torch.Tensor) -> torch.Tensor: + Y_post = [] + for i, gpr in enumerate(self._gpr_list): + mean, var = gpr.posterior(x) + stdev = torch.sqrt(var + self._stabilizing_noise) + # NOTE(nabenabe): By using fixed samples from the Sobol sequence, EHVI becomes + # deterministic, making it possible to optimize the acqf by l-BFGS. + # Sobol is better than the standard Monte-Carlo w.r.t. the approximation stability. + # cf. Appendix D of https://arxiv.org/pdf/2006.05078 + Y_post.append(mean[..., None] + stdev[..., None] * self._fixed_samples[..., i]) + + # NOTE(nabenabe): Use the following once multi-task GP is supported. + # L = torch.linalg.cholesky(cov) + # Y_post = means[..., None, :] + torch.einsum("...MM,SM->...SM", L, fixed_samples) + return logehvi( + Y_post=torch.stack(Y_post, dim=-1), + non_dominated_box_lower_bounds=self._non_dominated_box_lower_bounds, + non_dominated_box_upper_bounds=self._non_dominated_box_upper_bounds, + ) + + +class ConstrainedLogEHVI(BaseAcquisitionFunc): + def __init__( + self, + gpr_list: list[GPRegressor], + search_space: SearchSpace, + Y_feasible: torch.Tensor | None, + n_qmc_samples: int, + qmc_seed: int | None, + constraints_gpr_list: list[GPRegressor], + constraints_threshold_list: list[float], + stabilizing_noise: float = 1e-12, + ) -> None: + assert ( + len(constraints_gpr_list) == len(constraints_threshold_list) and constraints_gpr_list + ) + self._acqf = ( + LogEHVI(gpr_list, search_space, Y_feasible, n_qmc_samples, qmc_seed, stabilizing_noise) + if Y_feasible is not None + else None + ) + self._constraints_acqf_list = [ + LogPI(_gpr, search_space, _threshold, stabilizing_noise) + for _gpr, _threshold in zip(constraints_gpr_list, constraints_threshold_list) + ] + # Since all the objectives are equally important, we simply use the mean of + # inverse of squared mean lengthscales over all the objectives. + # inverse_squared_lengthscales is used in optim_mixed.py. + # cf. https://github.com/optuna/optuna/blob/v4.3.0/optuna/_gp/optim_mixed.py#L200-L209 + super().__init__(np.mean([gpr.length_scales for gpr in gpr_list], axis=0), search_space) + + def eval_acqf(self, x: torch.Tensor) -> torch.Tensor: + constraints_acqf_values = sum(acqf.eval_acqf(x) for acqf in self._constraints_acqf_list) + if self._acqf is None: + return cast(torch.Tensor, constraints_acqf_values) + return constraints_acqf_values + self._acqf.eval_acqf(x) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/gp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/gp.py new file mode 100644 index 0000000000000000000000000000000000000000..f0eccc1d9427895188daa43a9f91a94a23a1c820 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/gp.py @@ -0,0 +1,340 @@ +"""Notations in this Gaussian process implementation + +X_train: Observed parameter values with the shape of (len(trials), len(params)). +y_train: Observed objective values with the shape of (len(trials), ). +x: (Possibly batched) parameter value(s) to evaluate with the shape of (..., len(params)). +cov_fX_fX: Kernel matrix X = V[f(X)] with the shape of (len(trials), len(trials)). +cov_fx_fX: Kernel matrix Cov[f(x), f(X)] with the shape of (..., len(trials)). +cov_fx_fx: Kernel scalar value x = V[f(x)]. This value is constant for the Matern 5/2 kernel. +cov_Y_Y_inv: + The inverse of the covariance matrix (V[f(X) + noise_var])^-1 with the shape of + (len(trials), len(trials)). +cov_Y_Y_inv_Y: `cov_Y_Y_inv @ y` with the shape of (len(trials), ). +max_Y: The maximum of Y (Note that we transform the objective values such that it is maximized.) +d2: The squared distance between two points. +is_categorical: + A boolean array with the shape of (len(params), ). If is_categorical[i] is True, the i-th + parameter is categorical. +""" + +from __future__ import annotations + +import math +from typing import Any +from typing import TYPE_CHECKING +import warnings + +import numpy as np + +from optuna._gp.scipy_blas_thread_patch import single_blas_thread_if_scipy_v1_15_or_newer +from optuna.logging import get_logger + + +if TYPE_CHECKING: + from collections.abc import Callable + + import scipy.optimize as so + import torch +else: + from optuna._imports import _LazyImport + + so = _LazyImport("scipy.optimize") + torch = _LazyImport("torch") + +logger = get_logger(__name__) + + +def warn_and_convert_inf(values: np.ndarray) -> np.ndarray: + is_values_finite = np.isfinite(values) + if np.all(is_values_finite): + return values + + warnings.warn("Clip non-finite values to the min/max finite values for GP fittings.") + is_any_finite = np.any(is_values_finite, axis=0) + # NOTE(nabenabe): values cannot include nan to apply np.clip properly, but Optuna anyways won't + # pass nan in values by design. + return np.clip( + values, + np.where(is_any_finite, np.min(np.where(is_values_finite, values, np.inf), axis=0), 0.0), + np.where(is_any_finite, np.max(np.where(is_values_finite, values, -np.inf), axis=0), 0.0), + ) + + +class Matern52Kernel(torch.autograd.Function): + @staticmethod + def forward(ctx: Any, squared_distance: torch.Tensor) -> torch.Tensor: + """ + This method calculates `exp(-sqrt5d) * (1/3 * sqrt5d ** 2 + sqrt5d + 1)` where + `sqrt5d = sqrt(5 * squared_distance)`. + + Please note that automatic differentiation by PyTorch does not work well at + `squared_distance = 0` due to zero division, so we manually save the derivative, i.e., + `-5/6 * (1 + sqrt5d) * exp(-sqrt5d)`, for the exact derivative calculation. + + Notice that the derivative of this function is taken w.r.t. d**2, but not w.r.t. d. + """ + sqrt5d = torch.sqrt(5 * squared_distance) + exp_part = torch.exp(-sqrt5d) + val = exp_part * ((5 / 3) * squared_distance + sqrt5d + 1) + deriv = (-5 / 6) * (sqrt5d + 1) * exp_part + ctx.save_for_backward(deriv) + return val + + @staticmethod + def backward(ctx: Any, grad: torch.Tensor) -> torch.Tensor: + """ + Let x be squared_distance, f(x) be forward(ctx, x), and g(f) be a provided function, then + deriv := df/dx, grad := dg/df, and deriv * grad = df/dx * dg/df = dg/dx. + """ + (deriv,) = ctx.saved_tensors + return deriv * grad + + +class GPRegressor: + def __init__( + self, + is_categorical: torch.Tensor, + X_train: torch.Tensor, + y_train: torch.Tensor, + inverse_squared_lengthscales: torch.Tensor, # (len(params), ) + kernel_scale: torch.Tensor, # Scalar + noise_var: torch.Tensor, # Scalar + ) -> None: + self._is_categorical = is_categorical + self._X_train = X_train + self._y_train = y_train + self._cov_Y_Y_inv: torch.Tensor | None = None + self._cov_Y_Y_inv_Y: torch.Tensor | None = None + # TODO(nabenabe): Rename the attributes to private with `_`. + self.inverse_squared_lengthscales = inverse_squared_lengthscales + self.kernel_scale = kernel_scale + self.noise_var = noise_var + + @property + def length_scales(self) -> np.ndarray: + return 1.0 / np.sqrt(self.inverse_squared_lengthscales.detach().numpy()) + + def _cache_matrix(self) -> None: + with torch.no_grad(): + cov_Y_Y = self.kernel(self._X_train, self._X_train).detach().numpy() + + cov_Y_Y[np.diag_indices(self._X_train.shape[0])] += self.noise_var.item() + cov_Y_Y_inv = np.linalg.inv(cov_Y_Y) + cov_Y_Y_inv_Y = cov_Y_Y_inv @ self._y_train.numpy() + # NOTE(nabenabe): Here we use NumPy to guarantee the reproducibility from the past. + self._cov_Y_Y_inv = torch.from_numpy(cov_Y_Y_inv) + self._cov_Y_Y_inv_Y = torch.from_numpy(cov_Y_Y_inv_Y) + + def kernel(self, X1: torch.Tensor, X2: torch.Tensor) -> torch.Tensor: + """ + Return the kernel matrix with the shape of (..., n_A, n_B) given X1 and X2 each with the + shapes of (..., n_A, len(params)) and (..., n_B, len(params)). + + If x1 and x2 have the shape of (len(params), ), kernel(x1, x2) is computed as: + kernel_scale * Matern52Kernel.apply( + d2(x1, x2) @ inverse_squared_lengthscales + ) + where if x1[i] is continuous, d2(x1, x2)[i] = (x1[i] - x2[i]) ** 2 and if x1[i] is + categorical, d2(x1, x2)[i] = int(x1[i] != x2[i]). + Note that the distance for categorical parameters is the Hamming distance. + """ + d2 = (X1[..., :, None, :] - X2[..., None, :, :]) ** 2 + d2[..., self._is_categorical] = (d2[..., self._is_categorical] > 0.0).type(torch.float64) + d2 = (d2 * self.inverse_squared_lengthscales).sum(dim=-1) + return Matern52Kernel.apply(d2) * self.kernel_scale # type: ignore + + def posterior(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """ + This method computes the posterior mean and variance given the points `x` where both mean + and variance tensors will have the shape of x.shape[:-1]. + + The posterior mean and variance are computed as: + mean = cov_fx_fX @ inv(cov_fX_fX + noise_var * I) @ y, and + var = cov_fx_fx - cov_fx_fX @ inv(cov_fX_fX + noise_var * I) @ cov_fx_fX.T. + + Please note that we clamp the variance to avoid negative values due to numerical errors. + """ + assert ( + self._cov_Y_Y_inv is not None and self._cov_Y_Y_inv_Y is not None + ), "Call cache_matrix before calling posterior." + cov_fx_fX = self.kernel(x[..., None, :], self._X_train)[..., 0, :] + cov_fx_fx = self.kernel_scale # kernel(x, x) = kernel_scale + mean = cov_fx_fX @ self._cov_Y_Y_inv_Y + var = cov_fx_fx - (cov_fx_fX * (cov_fx_fX @ self._cov_Y_Y_inv)).sum(dim=-1) + return mean, torch.clamp(var, min=0.0) + + def marginal_log_likelihood(self) -> torch.Tensor: # Scalar + """ + This method computes the marginal log-likelihood of the kernel hyperparameters given the + training dataset (X, y). + Assume that N = len(X) in this method. + + Mathematically, the closed form is given as: + -0.5 * log((2*pi)**N * det(C)) - 0.5 * y.T @ inv(C) @ y + = -0.5 * log(det(C)) - 0.5 * y.T @ inv(C) @ y + const, + where C = cov_Y_Y = cov_fX_fX + noise_var * I and inv(...) is the inverse operator. + + We exploit the full advantages of the Cholesky decomposition (C = L @ L.T) in this method: + 1. The determinant of a lower triangular matrix is the diagonal product, which can be + computed with N flops where log(det(C)) = log(det(L.T @ L)) = 2 * log(det(L)). + 2. Solving linear system L @ u = y, which yields u = inv(L) @ y, costs N**2 flops. + Note that given `u = inv(L) @ y` and `inv(C) = inv(L @ L.T) = inv(L).T @ inv(L)`, + y.T @ inv(C) @ y is calculated as (inv(L) @ y) @ (inv(L) @ y). + + In principle, we could invert the matrix C first, but in this case, it costs: + 1. 1/3*N**3 flops for the determinant of inv(C). + 2. 2*N**2-N flops to solve C @ alpha = y, which is alpha = inv(C) @ y. + + Since the Cholesky decomposition costs 1/3*N**3 flops and the matrix inversion costs + 2/3*N**3 flops, the overall cost for the former is 1/3*N**3+N**2+N flops and that for the + latter is N**3+2*N**2-N flops. + """ + n_points = self._X_train.shape[0] + const = -0.5 * n_points * math.log(2 * math.pi) + cov_Y_Y = self.kernel(self._X_train, self._X_train) + self.noise_var * torch.eye( + n_points, dtype=torch.float64 + ) + L = torch.linalg.cholesky(cov_Y_Y) + logdet_part = -L.diagonal().log().sum() + inv_L_y = torch.linalg.solve_triangular(L, self._y_train[:, None], upper=False)[:, 0] + quad_part = -0.5 * (inv_L_y @ inv_L_y) + return logdet_part + const + quad_part + + +def _fit_kernel_params( + X: np.ndarray, + Y: np.ndarray, + is_categorical: np.ndarray, + log_prior: Callable[[GPRegressor], torch.Tensor], + minimum_noise: float, + deterministic_objective: bool, + gpr_cache: GPRegressor, + gtol: float, +) -> GPRegressor: + n_params = X.shape[1] + + # We apply log transform to enforce the positivity of the kernel parameters. + # Note that we cannot just use the constraint because of the numerical unstability + # of the marginal log likelihood. + # We also enforce the noise parameter to be greater than `minimum_noise` to avoid + # pathological behavior of maximum likelihood estimation. + initial_raw_params = np.concatenate( + [ + np.log(gpr_cache.inverse_squared_lengthscales.detach().numpy()), + [ + np.log(gpr_cache.kernel_scale.item()), + # We add 0.01 * minimum_noise to initial noise_var to avoid instability. + np.log(gpr_cache.noise_var.item() - 0.99 * minimum_noise), + ], + ] + ) + + def loss_func(raw_params: np.ndarray) -> tuple[float, np.ndarray]: + raw_params_tensor = torch.from_numpy(raw_params) + raw_params_tensor.requires_grad_(True) + with torch.enable_grad(): # type: ignore[no-untyped-call] + gpr = GPRegressor( + is_categorical=torch.from_numpy(is_categorical), + X_train=torch.from_numpy(X), + y_train=torch.from_numpy(Y), + inverse_squared_lengthscales=torch.exp(raw_params_tensor[:n_params]), + kernel_scale=torch.exp(raw_params_tensor[n_params]), + noise_var=( + torch.tensor(minimum_noise, dtype=torch.float64) + if deterministic_objective + else torch.exp(raw_params_tensor[n_params + 1]) + minimum_noise + ), + ) + loss = -gpr.marginal_log_likelihood() - log_prior(gpr) + loss.backward() # type: ignore + # scipy.minimize requires all the gradients to be zero for termination. + raw_noise_var_grad = raw_params_tensor.grad[n_params + 1] # type: ignore + assert not deterministic_objective or raw_noise_var_grad == 0 + return loss.item(), raw_params_tensor.grad.detach().numpy() # type: ignore + + with single_blas_thread_if_scipy_v1_15_or_newer(): + # jac=True means loss_func returns the gradient for gradient descent. + res = so.minimize( + # Too small `gtol` causes instability in loss_func optimization. + loss_func, + initial_raw_params, + jac=True, + method="l-bfgs-b", + options={"gtol": gtol}, + ) + if not res.success: + raise RuntimeError(f"Optimization failed: {res.message}") + + raw_params_opt_tensor = torch.from_numpy(res.x) + + gpr = GPRegressor( + is_categorical=torch.from_numpy(is_categorical), + X_train=torch.from_numpy(X), + y_train=torch.from_numpy(Y), + inverse_squared_lengthscales=torch.exp(raw_params_opt_tensor[:n_params]), + kernel_scale=torch.exp(raw_params_opt_tensor[n_params]), + noise_var=( + torch.tensor(minimum_noise, dtype=torch.float64) + if deterministic_objective + else minimum_noise + torch.exp(raw_params_opt_tensor[n_params + 1]) + ), + ) + gpr._cache_matrix() + return gpr + + +def fit_kernel_params( + X: np.ndarray, + Y: np.ndarray, + is_categorical: np.ndarray, + log_prior: Callable[[GPRegressor], torch.Tensor], + minimum_noise: float, + deterministic_objective: bool, + gpr_cache: GPRegressor | None = None, + gtol: float = 1e-2, +) -> GPRegressor: + default_kernel_params = torch.ones(X.shape[1] + 2, dtype=torch.float64) + default_gpr_cache = GPRegressor( + is_categorical=torch.from_numpy(is_categorical), + X_train=torch.from_numpy(X), + y_train=torch.from_numpy(Y), + inverse_squared_lengthscales=default_kernel_params[:-2].clone(), + kernel_scale=default_kernel_params[-2].clone(), + noise_var=default_kernel_params[-1].clone(), + ) + if gpr_cache is None: + gpr_cache = default_gpr_cache + + error = None + # First try optimizing the kernel params with the provided kernel parameters in gpr_cache, + # but if it fails, rerun the optimization with the default kernel parameters above. + # This increases the robustness of the optimization. + for gpr_cache_to_use in [gpr_cache, default_gpr_cache]: + try: + return _fit_kernel_params( + X=X, + Y=Y, + is_categorical=is_categorical, + log_prior=log_prior, + minimum_noise=minimum_noise, + gpr_cache=gpr_cache_to_use, + deterministic_objective=deterministic_objective, + gtol=gtol, + ) + except RuntimeError as e: + error = e + + logger.warning( + f"The optimization of kernel parameters failed: \n{error}\n" + "The default initial kernel parameters will be used instead." + ) + default_gpr = GPRegressor( + is_categorical=torch.from_numpy(is_categorical), + X_train=torch.from_numpy(X), + y_train=torch.from_numpy(Y), + inverse_squared_lengthscales=default_kernel_params[:-2].clone(), + kernel_scale=default_kernel_params[-2].clone(), + noise_var=default_kernel_params[-1].clone(), + ) + default_gpr._cache_matrix() + return default_gpr diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/optim_mixed.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/optim_mixed.py new file mode 100644 index 0000000000000000000000000000000000000000..156f49ebcf0a8792b302ed302f0c67ae1f3832e7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/optim_mixed.py @@ -0,0 +1,306 @@ +from __future__ import annotations + +import math +from typing import TYPE_CHECKING + +import numpy as np + +from optuna._gp.scipy_blas_thread_patch import single_blas_thread_if_scipy_v1_15_or_newer +from optuna.logging import get_logger + + +if TYPE_CHECKING: + import scipy.optimize as so + + from optuna._gp.acqf import BaseAcquisitionFunc +else: + from optuna import _LazyImport + + so = _LazyImport("scipy.optimize") + +_logger = get_logger(__name__) + + +def _gradient_ascent( + acqf: BaseAcquisitionFunc, + initial_params: np.ndarray, + initial_fval: float, + continuous_indices: np.ndarray, + lengthscales: np.ndarray, + tol: float, +) -> tuple[np.ndarray, float, bool]: + """ + This function optimizes the acquisition function using preconditioning. + Preconditioning equalizes the variances caused by each parameter and + speeds up the convergence. + + In Optuna, acquisition functions use Matern 5/2 kernel, which is a function of `x / l` + where `x` is `normalized_params` and `l` is the corresponding lengthscales. + Then acquisition functions are a function of `x / l`, i.e. `f(x / l)`. + As `l` has different values for each param, it makes the function ill-conditioned. + By transforming `x / l` to `zl / l = z`, the function becomes `f(z)` and has + equal variances w.r.t. `z`. + So optimization w.r.t. `z` instead of `x` is the preconditioning here and + speeds up the convergence. + As the domain of `x` is [0, 1], that of `z` becomes [0, 1/l]. + """ + if len(continuous_indices) == 0: + return initial_params, initial_fval, False + normalized_params = initial_params.copy() + + def negative_acqf_with_grad(scaled_x: np.ndarray) -> tuple[float, np.ndarray]: + # Scale back to the original domain, i.e. [0, 1], from [0, 1/s]. + normalized_params[continuous_indices] = scaled_x * lengthscales + (fval, grad) = acqf.eval_acqf_with_grad(normalized_params) + # Flip sign because scipy minimizes functions. + # Let the scaled acqf be g(x) and the acqf be f(sx), then dg/dx = df/dx * s. + return -fval, -grad[continuous_indices] * lengthscales + + with single_blas_thread_if_scipy_v1_15_or_newer(): + scaled_cont_x_opt, neg_fval_opt, info = so.fmin_l_bfgs_b( + func=negative_acqf_with_grad, + x0=normalized_params[continuous_indices] / lengthscales, + bounds=[(0, 1 / s) for s in lengthscales], + pgtol=math.sqrt(tol), + maxiter=200, + ) + + if -neg_fval_opt > initial_fval and info["nit"] > 0: # Improved. + # `nit` is the number of iterations. + normalized_params[continuous_indices] = scaled_cont_x_opt * lengthscales + return normalized_params, -neg_fval_opt, True + + return initial_params, initial_fval, False # No improvement. + + +def _exhaustive_search( + acqf: BaseAcquisitionFunc, + initial_params: np.ndarray, + initial_fval: float, + param_idx: int, + choices: np.ndarray, +) -> tuple[np.ndarray, float, bool]: + choices_except_current = choices[choices != initial_params[param_idx]] + + all_params = np.repeat(initial_params[None, :], len(choices_except_current), axis=0) + all_params[:, param_idx] = choices_except_current + fvals = acqf.eval_acqf_no_grad(all_params) + best_idx = np.argmax(fvals) + + if fvals[best_idx] > initial_fval: # Improved. + return all_params[best_idx, :], fvals[best_idx], True + + return initial_params, initial_fval, False # No improvement. + + +def _discrete_line_search( + acqf: BaseAcquisitionFunc, + initial_params: np.ndarray, + initial_fval: float, + param_idx: int, + grids: np.ndarray, + xtol: float, +) -> tuple[np.ndarray, float, bool]: + if len(grids) == 1: + # Do not optimize anything when there's only one choice. + return initial_params, initial_fval, False + + def find_nearest_index(x: float) -> int: + i = int(np.clip(np.searchsorted(grids, x), 1, len(grids) - 1)) + return i - 1 if abs(x - grids[i - 1]) < abs(x - grids[i]) else i + + current_choice_i = find_nearest_index(initial_params[param_idx]) + assert np.isclose(initial_params[param_idx], grids[current_choice_i]) + + negative_fval_cache = {current_choice_i: -initial_fval} + + normalized_params = initial_params.copy() + + def negative_acqf_with_cache(i: int) -> float: + # Function value at choices[i]. + cache_val = negative_fval_cache.get(i) + if cache_val is not None: + return cache_val + normalized_params[param_idx] = grids[i] + + # Flip sign because scipy minimizes functions. + negval = -float(acqf.eval_acqf_no_grad(normalized_params)) + negative_fval_cache[i] = negval + return negval + + def interpolated_negative_acqf(x: float) -> float: + if x < grids[0] or x > grids[-1]: + return np.inf + right = int(np.clip(np.searchsorted(grids, x), 1, len(grids) - 1)) + left = right - 1 + neg_acqf_left, neg_acqf_right = negative_acqf_with_cache(left), negative_acqf_with_cache( + right + ) + w_left = (grids[right] - x) / (grids[right] - grids[left]) + w_right = 1.0 - w_left + return w_left * neg_acqf_left + w_right * neg_acqf_right + + EPS = 1e-12 + res = so.minimize_scalar( + interpolated_negative_acqf, + # The values of this bracket are (inf, -fval, inf). + # This trivially satisfies the bracket condition if fval is finite. + bracket=(grids[0] - EPS, grids[current_choice_i], grids[-1] + EPS), + method="brent", + tol=xtol, + ) + opt_idx = find_nearest_index(res.x) + fval_opt = -negative_acqf_with_cache(opt_idx) + + # We check both conditions because of numerical errors. + if opt_idx != current_choice_i and fval_opt > initial_fval: + normalized_params[param_idx] = grids[opt_idx] + return normalized_params, fval_opt, True + + return initial_params, initial_fval, False # No improvement. + + +def _local_search_discrete( + acqf: BaseAcquisitionFunc, + initial_params: np.ndarray, + initial_fval: float, + param_idx: int, + choices: np.ndarray, + xtol: float, +) -> tuple[np.ndarray, float, bool]: + + # If the number of possible parameter values is small, we just perform an exhaustive search. + # This is faster and better than the line search. + MAX_INT_EXHAUSTIVE_SEARCH_PARAMS = 16 + + is_categorical = acqf.search_space.is_categorical[param_idx] + if is_categorical or len(choices) <= MAX_INT_EXHAUSTIVE_SEARCH_PARAMS: + return _exhaustive_search(acqf, initial_params, initial_fval, param_idx, choices) + else: + return _discrete_line_search(acqf, initial_params, initial_fval, param_idx, choices, xtol) + + +def local_search_mixed( + acqf: BaseAcquisitionFunc, + initial_normalized_params: np.ndarray, + *, + tol: float = 1e-4, + max_iter: int = 100, +) -> tuple[np.ndarray, float]: + continuous_indices = acqf.search_space.continuous_indices + + # This is a technique for speeding up optimization. + # We use an isotropic kernel, so scaling the gradient will make + # the hessian better-conditioned. + # NOTE: Ideally, separating lengthscales should be used for the constraint functions, + # but for simplicity, the ones from the objective function are being reused. + # TODO(kAIto47802): Think of a better way to handle this. + lengthscales = acqf.length_scales[continuous_indices] + + choices_of_discrete_params = acqf.search_space.get_choices_of_discrete_params() + + discrete_xtols = [ + # Terminate discrete optimizations once the change in x becomes smaller than this. + # Basically, if the change is smaller than min(dx) / 4, it is useless to see more details. + np.min(np.diff(choices), initial=np.inf) / 4 + for choices in choices_of_discrete_params + ] + + best_normalized_params = initial_normalized_params.copy() + best_fval = float(acqf.eval_acqf_no_grad(best_normalized_params)) + + CONTINUOUS = -1 + last_changed_param: int | None = None + + for _ in range(max_iter): + if last_changed_param == CONTINUOUS: + # Parameters not changed since last time. + return best_normalized_params, best_fval + (best_normalized_params, best_fval, updated) = _gradient_ascent( + acqf, + best_normalized_params, + best_fval, + continuous_indices, + lengthscales, + tol, + ) + if updated: + last_changed_param = CONTINUOUS + + for i, choices, xtol in zip( + acqf.search_space.discrete_indices, choices_of_discrete_params, discrete_xtols + ): + if last_changed_param == i: + # Parameters not changed since last time. + return best_normalized_params, best_fval + (best_normalized_params, best_fval, updated) = _local_search_discrete( + acqf, best_normalized_params, best_fval, i, choices, xtol + ) + if updated: + last_changed_param = i + + if last_changed_param is None: + # Parameters not changed from the beginning. + return best_normalized_params, best_fval + + _logger.warning("local_search_mixed: Local search did not converge.") + return best_normalized_params, best_fval + + +def optimize_acqf_mixed( + acqf: BaseAcquisitionFunc, + *, + warmstart_normalized_params_array: np.ndarray | None = None, + n_preliminary_samples: int = 2048, + n_local_search: int = 10, + tol: float = 1e-4, + rng: np.random.RandomState | None = None, +) -> tuple[np.ndarray, float]: + + rng = rng or np.random.RandomState() + + if warmstart_normalized_params_array is None: + warmstart_normalized_params_array = np.empty((0, acqf.search_space.dim)) + + assert ( + len(warmstart_normalized_params_array) <= n_local_search - 1 + ), "We must choose at least 1 best sampled point + given_initial_xs as start points." + + sampled_xs = acqf.search_space.sample_normalized_params(n_preliminary_samples, rng=rng) + + # Evaluate all values at initial samples + f_vals = acqf.eval_acqf_no_grad(sampled_xs) + assert isinstance(f_vals, np.ndarray) + + max_i = np.argmax(f_vals) + + # TODO(nabenabe): Benchmark the BoTorch roulette selection as well. + # https://github.com/pytorch/botorch/blob/v0.14.0/botorch/optim/initializers.py#L942 + # We use a modified roulette wheel selection to pick the initial param for each local search. + probs = np.exp(f_vals - f_vals[max_i]) + probs[max_i] = 0.0 # We already picked the best param, so remove it from roulette. + probs /= probs.sum() + n_non_zero_probs_improvement = int(np.count_nonzero(probs > 0.0)) + # n_additional_warmstart becomes smaller when study starts to converge. + n_additional_warmstart = min( + n_local_search - len(warmstart_normalized_params_array) - 1, n_non_zero_probs_improvement + ) + if n_additional_warmstart == n_non_zero_probs_improvement: + _logger.warning("Study already converged, so the number of local search is reduced.") + chosen_idxs = np.array([max_i]) + if n_additional_warmstart > 0: + additional_idxs = rng.choice( + len(sampled_xs), size=n_additional_warmstart, replace=False, p=probs + ) + chosen_idxs = np.append(chosen_idxs, additional_idxs) + + best_x = sampled_xs[max_i, :] + best_f = float(f_vals[max_i]) + + for x_warmstart in np.vstack([sampled_xs[chosen_idxs, :], warmstart_normalized_params_array]): + x, f = local_search_mixed(acqf, x_warmstart, tol=tol) + if f > best_f: + best_x = x + best_f = f + + return best_x, best_f diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/optim_sample.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/optim_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..8e4c5e29c8ff37f9577920b10d79f6fa4d06910a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/optim_sample.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +import numpy as np + +from optuna._gp import acqf as acqf_module + + +def optimize_acqf_sample( + acqf: acqf_module.BaseAcquisitionFunc, + *, + n_samples: int = 2048, + rng: np.random.RandomState | None = None, +) -> tuple[np.ndarray, float]: + # Normalized parameter values are sampled. + xs = acqf.search_space.sample_normalized_params(n_samples, rng=rng) + res = acqf.eval_acqf_no_grad(xs) + + best_i = np.argmax(res) + return xs[best_i, :], res[best_i] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/prior.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/prior.py new file mode 100644 index 0000000000000000000000000000000000000000..e5bb7c58c7aefae57dc7f939efa08b566135d4e9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/prior.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + import torch + + from optuna._gp import gp +else: + from optuna._imports import _LazyImport + + torch = _LazyImport("torch") + + +DEFAULT_MINIMUM_NOISE_VAR = 1e-6 + + +def default_log_prior(gpr: gp.GPRegressor) -> torch.Tensor: + # Log of prior distribution of kernel parameters. + + def gamma_log_prior(x: torch.Tensor, concentration: float, rate: float) -> torch.Tensor: + # We omit the constant factor `rate ** concentration / Gamma(concentration)`. + return (concentration - 1) * torch.log(x) - rate * x + + # NOTE(contramundum53): The priors below (params and function + # shape for inverse_squared_lengthscales) were picked by heuristics. + # TODO(contramundum53): Check whether these priors are appropriate. + return ( + -(0.1 / gpr.inverse_squared_lengthscales + 0.1 * gpr.inverse_squared_lengthscales).sum() + + gamma_log_prior(gpr.kernel_scale, 2, 1) + + gamma_log_prior(gpr.noise_var, 1.1, 30) + ) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/scipy_blas_thread_patch.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/scipy_blas_thread_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..921fdaa2ccc2a4a8f43de44a72f6884e471c5c39 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/scipy_blas_thread_patch.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from contextlib import contextmanager +import os +from typing import TYPE_CHECKING + +from packaging.version import Version +import scipy + + +if TYPE_CHECKING: + from typing import Generator + + +@contextmanager +def single_blas_thread_if_scipy_v1_15_or_newer() -> Generator[None, None, None]: + """ + This function limits the thread count in the context to 1. + We need to do so because the L-BFGS-B in SciPy v1.15 or newer uses OpenBLAS and it apparently + causes slowdown due to the unmatched thread setup. This context manager aims to solve this + issue. If the SciPy version is 1.14.1 or older, this issue does not happen because it uses + the Fortran implementation. + + Reference: + https://github.com/scipy/scipy/issues/22438 + + TODO(nabe): Watch the SciPy update and remove this context manager once it becomes unnecessary. + TODO(nabe): Benchmark the speed without this context manager for any SciPy updates. + NOTE(nabe): I don't know why, but `fmin_l_bfgs_b` in optim_mixed.py seems unaffected. + """ + if Version(scipy.__version__) < Version("1.15.0"): + # If SciPy is older than 1.15.0, the context manager is unnecessary. + yield + else: + old_val = os.environ.get("OPENBLAS_NUM_THREADS") + os.environ["OPENBLAS_NUM_THREADS"] = "1" + try: + yield + finally: + if old_val is None: + os.environ.pop("OPENBLAS_NUM_THREADS", None) + else: + os.environ["OPENBLAS_NUM_THREADS"] = old_val diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/search_space.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/search_space.py new file mode 100644 index 0000000000000000000000000000000000000000..32132ab16ffe2782d33da8e970a7e2f2ded165e8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_gp/search_space.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +from enum import IntEnum +import math +import threading +from typing import Any +from typing import TYPE_CHECKING + +import numpy as np + +from optuna.distributions import BaseDistribution +from optuna.distributions import CategoricalDistribution +from optuna.distributions import FloatDistribution +from optuna.distributions import IntDistribution + + +if TYPE_CHECKING: + import scipy.stats.qmc as qmc + + from optuna.trial import FrozenTrial +else: + from optuna._imports import _LazyImport + + qmc = _LazyImport("scipy.stats.qmc") + + +_threading_lock = threading.Lock() + + +class _ScaleType(IntEnum): + LINEAR = 0 + LOG = 1 + CATEGORICAL = 2 + + +class SearchSpace: + def __init__( + self, + optuna_search_space: dict[str, BaseDistribution], + ) -> None: + self._optuna_search_space = optuna_search_space + self._scale_types = np.empty(len(optuna_search_space), dtype=np.int64) + self._bounds = np.empty((len(optuna_search_space), 2), dtype=float) + self._steps = np.empty(len(optuna_search_space), dtype=float) + for i, distribution in enumerate(optuna_search_space.values()): + if isinstance(distribution, CategoricalDistribution): + self._scale_types[i] = _ScaleType.CATEGORICAL + self._bounds[i, :] = (0.0, len(distribution.choices)) + self._steps[i] = 1.0 + else: + assert isinstance(distribution, (FloatDistribution, IntDistribution)) + self._scale_types[i] = _ScaleType.LOG if distribution.log else _ScaleType.LINEAR + self._bounds[i, :] = (distribution.low, distribution.high) + self._steps[i] = distribution.step or 0.0 + self.dim = len(optuna_search_space) + # TODO: Make it an index array. + self.is_categorical = self._scale_types == _ScaleType.CATEGORICAL + # NOTE(nabenabe): MyPy Redefinition for NumPy v2.2.0. (Cast signed int to int) + self.discrete_indices = np.flatnonzero(self._steps > 0).astype(int) + self.continuous_indices = np.flatnonzero(self._steps == 0.0).astype(int) + + def get_normalized_params( + self, + trials: list[FrozenTrial], + ) -> np.ndarray: + values = np.empty((len(trials), len(self._optuna_search_space)), dtype=float) + for i, (param, distribution) in enumerate(self._optuna_search_space.items()): + if isinstance(distribution, CategoricalDistribution): + values[:, i] = [distribution.to_internal_repr(t.params[param]) for t in trials] + else: + values[:, i] = _normalize_one_param( + np.array([trial.params[param] for trial in trials]), + self._scale_types[i], + (self._bounds[i, 0], self._bounds[i, 1]), + self._steps[i], + ) + return values + + def get_unnormalized_param( + self, + normalized_param: np.ndarray, + ) -> dict[str, Any]: + # TODO(kAIto47802): Move the implementation of `_get_unnormalized_param` here + # instead of wrapping it. + return _get_unnormalized_param(self._optuna_search_space, normalized_param) + + def sample_normalized_params(self, n: int, rng: np.random.RandomState | None) -> np.ndarray: + # TODO(kAIto47802): Move the implementation of `_sample_normalized_params` here + # instead of wrapping it. + return _sample_normalized_params(n, self, rng) + + def get_choices_of_discrete_params(self) -> list[np.ndarray]: + return [ + ( + np.arange(self._bounds[i, 1]) + if self.is_categorical[i] + else _normalize_one_param( + param_value=np.arange( + self._bounds[i, 0], + self._bounds[i, 1] + 0.5 * self._steps[i], + self._steps[i], + ), + scale_type=_ScaleType(self._scale_types[i]), + bounds=(self._bounds[i, 0], self._bounds[i, 1]), + step=self._steps[i], + ) + ) + for i in self.discrete_indices + ] + + +def _unnormalize_one_param( + param_value: np.ndarray, scale_type: _ScaleType, bounds: tuple[float, float], step: float +) -> np.ndarray: + # param_value can be batched, or not. + if scale_type == _ScaleType.CATEGORICAL: + return param_value + low, high = (bounds[0] - 0.5 * step, bounds[1] + 0.5 * step) + if scale_type == _ScaleType.LOG: + low, high = (math.log(low), math.log(high)) + param_value = param_value * (high - low) + low + if scale_type == _ScaleType.LOG: + param_value = np.exp(param_value) + return param_value + + +def _normalize_one_param( + param_value: np.ndarray, scale_type: _ScaleType, bounds: tuple[float, float], step: float +) -> np.ndarray: + # param_value can be batched, or not. + if scale_type == _ScaleType.CATEGORICAL: + return param_value + low, high = (bounds[0] - 0.5 * step, bounds[1] + 0.5 * step) + if scale_type == _ScaleType.LOG: + low, high = (math.log(low), math.log(high)) + param_value = np.log(param_value) + if high == low: + return np.full_like(param_value, 0.5) + param_value = (param_value - low) / (high - low) + return param_value + + +def _round_one_normalized_param( + param_value: np.ndarray, scale_type: _ScaleType, bounds: tuple[float, float], step: float +) -> np.ndarray: + assert scale_type != _ScaleType.CATEGORICAL + if step == 0.0: + return param_value + + param_value = _unnormalize_one_param(param_value, scale_type, bounds, step) + param_value = np.clip( + (param_value - bounds[0] + 0.5 * step) // step * step + bounds[0], + bounds[0], + bounds[1], + ) + param_value = _normalize_one_param(param_value, scale_type, bounds, step) + return param_value + + +def _sample_normalized_params( + n: int, search_space: SearchSpace, rng: np.random.RandomState | None +) -> np.ndarray: + rng = rng or np.random.RandomState() + dim = search_space._scale_types.shape[0] + scale_types = search_space._scale_types + bounds = search_space._bounds + steps = search_space._steps + + # Sobol engine likely shares its internal state among threads. + # Without threading.Lock, ValueError exceptions are raised in Sobol engine as discussed in + # https://github.com/optuna/optunahub-registry/pull/168#pullrequestreview-2404054969 + with _threading_lock: + qmc_engine = qmc.Sobol(dim, scramble=True, seed=rng.randint(np.iinfo(np.int32).max)) + param_values = qmc_engine.random(n) + + for i in range(dim): + if scale_types[i] == _ScaleType.CATEGORICAL: + param_values[:, i] = np.floor(param_values[:, i] * bounds[i, 1]) + elif steps[i] != 0.0: + param_values[:, i] = _round_one_normalized_param( + param_values[:, i], scale_types[i], (bounds[i, 0], bounds[i, 1]), steps[i] + ) + return param_values + + +def _get_unnormalized_param( + optuna_search_space: dict[str, BaseDistribution], + normalized_param: np.ndarray, +) -> dict[str, Any]: + ret = {} + for i, (param, distribution) in enumerate(optuna_search_space.items()): + if isinstance(distribution, CategoricalDistribution): + ret[param] = distribution.to_external_repr(normalized_param[i]) + else: + assert isinstance( + distribution, + ( + FloatDistribution, + IntDistribution, + ), + ) + scale_type = _ScaleType.LOG if distribution.log else _ScaleType.LINEAR + step = 0.0 if distribution.step is None else distribution.step + bounds = (distribution.low, distribution.high) + param_value = float( + np.clip( + _unnormalize_one_param(normalized_param[i], scale_type, bounds, step), + distribution.low, + distribution.high, + ) + ) + if isinstance(distribution, IntDistribution): + param_value = round(param_value) + ret[param] = param_value + return ret diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_imports.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..572caf535cb5023427cc0d651ec9064386946225 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_imports.py @@ -0,0 +1,133 @@ +from __future__ import annotations + +import importlib +import types +from typing import Any +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from types import TracebackType + +_INTEGRATION_IMPORT_ERROR_TEMPLATE = ( + "\nCould not find `optuna-integration` for `{0}`.\n" + "Please run `pip install optuna-integration[{0}]`." +) + + +class _DeferredImportExceptionContextManager: + """Context manager to defer exceptions from imports. + + Catches :exc:`ImportError` and :exc:`SyntaxError`. + If any exception is caught, this class raises an :exc:`ImportError` when being checked. + + """ + + def __init__(self) -> None: + self._deferred: tuple[Exception, str] | None = None + + def __enter__(self) -> "_DeferredImportExceptionContextManager": + """Enter the context manager. + + Returns: + Itself. + + """ + return self + + def __exit__( + self, + exc_type: type[Exception] | None, + exc_value: Exception | None, + traceback: TracebackType | None, + ) -> bool | None: + """Exit the context manager. + + Args: + exc_type: + Raised exception type. :obj:`None` if nothing is raised. + exc_value: + Raised exception object. :obj:`None` if nothing is raised. + traceback: + Associated traceback. :obj:`None` if nothing is raised. + + Returns: + :obj:`None` if nothing is deferred, otherwise :obj:`True`. + :obj:`True` will suppress any exceptions avoiding them from propagating. + + """ + if isinstance(exc_value, (ImportError, SyntaxError)): + if isinstance(exc_value, ImportError): + message = ( + "Tried to import '{}' but failed. Please make sure that the package is " + "installed correctly to use this feature. Actual error: {}." + ).format(exc_value.name, exc_value) + elif isinstance(exc_value, SyntaxError): + message = ( + "Tried to import a package but failed due to a syntax error in {}. Please " + "make sure that the Python version is correct to use this feature. Actual " + "error: {}." + ).format(exc_value.filename, exc_value) + else: + assert False + + self._deferred = (exc_value, message) + return True + return None + + def is_successful(self) -> bool: + """Return whether the context manager has caught any exceptions. + + Returns: + :obj:`True` if no exceptions are caught, :obj:`False` otherwise. + + """ + return self._deferred is None + + def check(self) -> None: + """Check whether the context manager has caught any exceptions. + + Raises: + :exc:`ImportError`: + If any exception was caught from the caught exception. + + """ + if self._deferred is not None: + exc_value, message = self._deferred + raise ImportError(message) from exc_value + + +def try_import() -> _DeferredImportExceptionContextManager: + """Create a context manager that can wrap imports of optional packages to defer exceptions. + + Returns: + Deferred import context manager. + + """ + return _DeferredImportExceptionContextManager() + + +class _LazyImport(types.ModuleType): + """Module wrapper for lazy import. + + This class wraps the specified modules and lazily imports them only when accessed. + Otherwise, `import optuna` is slowed down by importing all submodules and + dependencies even if not required. + Within this project's usage, importlib override this module's attribute on the first + access and the imported submodule is directly accessed from the second access. + + Args: + name: Name of module to apply lazy import. + """ + + def __init__(self, name: str) -> None: + super().__init__(name) + self._name = name + + def _load(self) -> types.ModuleType: + module = importlib.import_module(self._name) + self.__dict__.update(module.__dict__) + return module + + def __getattr__(self, item: str) -> Any: + return getattr(self._load(), item) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_transform.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..cb9ce7047419c203118dbbe1fd1fc833521f300a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_transform.py @@ -0,0 +1,301 @@ +from __future__ import annotations + +import math +from typing import Any + +import numpy as np + +from optuna.distributions import BaseDistribution +from optuna.distributions import CategoricalDistribution +from optuna.distributions import FloatDistribution +from optuna.distributions import IntDistribution + + +class _SearchSpaceTransform: + """Transform a search space and parameter configurations to continuous space. + + The search space bounds and parameter configurations are represented as ``numpy.ndarray``s and + transformed into continuous space. Bounds and parameters associated with categorical + distributions are one-hot encoded. Parameter configurations in this space can additionally be + untransformed, or mapped back to the original space. This type of + transformation/untransformation is useful for e.g. implementing samplers without having to + condition on distribution types before sampling parameter values. + + Args: + search_space: + The search space. If any transformations are to be applied, parameter configurations + are assumed to hold parameter values for all of the distributions defined in this + search space. Otherwise, assertion failures will be raised. + transform_log: + If :obj:`True`, apply log/exp operations to the bounds and parameters with + corresponding distributions in log space during transformation/untransformation. + Should always be :obj:`True` if any parameters are going to be sampled from the + transformed space. + transform_step: + If :obj:`True`, offset the lower and higher bounds by a half step each, increasing the + space by one step. This allows fair sampling for values close to the bounds. + Should always be :obj:`True` if any parameters are going to be sampled from the + transformed space. + transform_0_1: + If :obj:`True`, apply a linear transformation to the bounds and parameters so that + they are in the unit cube. + + Attributes: + bounds: + Constructed bounds from the given search space. + column_to_encoded_columns: + Constructed mapping from original parameter column index to encoded column indices. + encoded_column_to_column: + Constructed mapping from encoded column index to original parameter column index. + + Note: + Parameter values are not scaled to the unit cube. + + Note: + ``transform_log`` and ``transform_step`` are useful for constructing bounds and parameters + without any actual transformations by setting those arguments to :obj:`False`. This is + needed for e.g. the hyperparameter importance assessments. + + """ + + def __init__( + self, + search_space: dict[str, BaseDistribution], + transform_log: bool = True, + transform_step: bool = True, + transform_0_1: bool = False, + ) -> None: + bounds, column_to_encoded_columns, encoded_column_to_column = _transform_search_space( + search_space, transform_log, transform_step + ) + self._raw_bounds = bounds + self._column_to_encoded_columns = column_to_encoded_columns + self._encoded_column_to_column = encoded_column_to_column + self._search_space = search_space + self._transform_log = transform_log + self._transform_0_1 = transform_0_1 + + @property + def bounds(self) -> np.ndarray: + if self._transform_0_1: + return np.array([[0.0, 1.0]] * self._raw_bounds.shape[0]) + else: + return self._raw_bounds + + @property + def column_to_encoded_columns(self) -> list[np.ndarray]: + return self._column_to_encoded_columns + + @property + def encoded_column_to_column(self) -> np.ndarray: + return self._encoded_column_to_column + + def transform(self, params: dict[str, Any]) -> np.ndarray: + """Transform a parameter configuration from actual values to continuous space. + + Args: + params: + A parameter configuration to transform. + + Returns: + A 1-dimensional ``numpy.ndarray`` holding the transformed parameters in the + configuration. + + """ + trans_params = np.zeros(self._raw_bounds.shape[0], dtype=np.float64) + + bound_idx = 0 + for name, distribution in self._search_space.items(): + assert name in params, "Parameter configuration must contain all distributions." + param = params[name] + + if isinstance(distribution, CategoricalDistribution): + choice_idx = int(distribution.to_internal_repr(param)) + trans_params[bound_idx + choice_idx] = 1 + bound_idx += len(distribution.choices) + else: + trans_params[bound_idx] = _transform_numerical_param( + param, distribution, self._transform_log + ) + bound_idx += 1 + + if self._transform_0_1: + single_mask = self._raw_bounds[:, 0] == self._raw_bounds[:, 1] + trans_params[single_mask] = 0.5 + trans_params[~single_mask] = ( + trans_params[~single_mask] - self._raw_bounds[~single_mask, 0] + ) / (self._raw_bounds[~single_mask, 1] - self._raw_bounds[~single_mask, 0]) + + return trans_params + + def untransform(self, trans_params: np.ndarray) -> dict[str, Any]: + """Untransform a parameter configuration from continuous space to actual values. + + Args: + trans_params: + A 1-dimensional ``numpy.ndarray`` in the transformed space corresponding to a + parameter configuration. + + Returns: + A dictionary of an untransformed parameter configuration. Keys are parameter names. + Values are untransformed parameter values. + + """ + assert trans_params.shape == (self._raw_bounds.shape[0],) + + if self._transform_0_1: + trans_params = self._raw_bounds[:, 0] + trans_params * ( + self._raw_bounds[:, 1] - self._raw_bounds[:, 0] + ) + + params = {} + + for (name, distribution), encoded_columns in zip( + self._search_space.items(), self.column_to_encoded_columns + ): + trans_param = trans_params[encoded_columns] + + if isinstance(distribution, CategoricalDistribution): + # Select the highest rated one-hot encoding. + param = distribution.to_external_repr(trans_param.argmax()) + else: + param = _untransform_numerical_param( + trans_param.item(), distribution, self._transform_log + ) + + params[name] = param + + return params + + +def _transform_search_space( + search_space: dict[str, BaseDistribution], transform_log: bool, transform_step: bool +) -> tuple[np.ndarray, list[np.ndarray], np.ndarray]: + assert len(search_space) > 0, "Cannot transform if no distributions are given." + + n_bounds = sum( + len(d.choices) if isinstance(d, CategoricalDistribution) else 1 + for d in search_space.values() + ) + + bounds = np.empty((n_bounds, 2), dtype=np.float64) + column_to_encoded_columns: list[np.ndarray] = [] + encoded_column_to_column = np.empty(n_bounds, dtype=np.int64) + + bound_idx = 0 + for distribution in search_space.values(): + d = distribution + if isinstance(d, CategoricalDistribution): + n_choices = len(d.choices) + bounds[bound_idx : bound_idx + n_choices] = (0, 1) # Broadcast across all choices. + encoded_columns = np.arange(bound_idx, bound_idx + n_choices) + encoded_column_to_column[encoded_columns] = len(column_to_encoded_columns) + column_to_encoded_columns.append(encoded_columns) + bound_idx += n_choices + elif isinstance( + d, + ( + FloatDistribution, + IntDistribution, + ), + ): + if isinstance(d, FloatDistribution): + if d.step is not None: + half_step = 0.5 * d.step if transform_step else 0.0 + bds = ( + _transform_numerical_param(d.low, d, transform_log) - half_step, + _transform_numerical_param(d.high, d, transform_log) + half_step, + ) + else: + bds = ( + _transform_numerical_param(d.low, d, transform_log), + _transform_numerical_param(d.high, d, transform_log), + ) + elif isinstance(d, IntDistribution): + half_step = 0.5 * d.step if transform_step else 0.0 + if d.log: + bds = ( + _transform_numerical_param(d.low - half_step, d, transform_log), + _transform_numerical_param(d.high + half_step, d, transform_log), + ) + else: + bds = ( + _transform_numerical_param(d.low, d, transform_log) - half_step, + _transform_numerical_param(d.high, d, transform_log) + half_step, + ) + else: + assert False, "Should not reach. Unexpected distribution." + + bounds[bound_idx] = bds + encoded_column = np.atleast_1d(bound_idx) + encoded_column_to_column[encoded_column] = len(column_to_encoded_columns) + column_to_encoded_columns.append(encoded_column) + bound_idx += 1 + else: + assert False, "Should not reach. Unexpected distribution." + + assert bound_idx == n_bounds + + return bounds, column_to_encoded_columns, encoded_column_to_column + + +def _transform_numerical_param( + param: int | float, distribution: BaseDistribution, transform_log: bool +) -> float: + d = distribution + + if isinstance(d, CategoricalDistribution): + assert False, "Should not reach. Should be one-hot encoded." + elif isinstance(d, FloatDistribution): + if d.log: + trans_param = math.log(param) if transform_log else float(param) + else: + trans_param = float(param) + elif isinstance(d, IntDistribution): + if d.log: + trans_param = math.log(param) if transform_log else float(param) + else: + trans_param = float(param) + else: + assert False, "Should not reach. Unexpected distribution." + + return trans_param + + +def _untransform_numerical_param( + trans_param: float, distribution: BaseDistribution, transform_log: bool +) -> int | float: + d = distribution + + if isinstance(d, CategoricalDistribution): + assert False, "Should not reach. Should be one-hot encoded." + elif isinstance(d, FloatDistribution): + if d.log: + param = math.exp(trans_param) if transform_log else trans_param + if d.single(): + pass + else: + param = min(param, np.nextafter(d.high, d.high - 1)) + elif d.step is not None: + param = float( + np.clip(np.round((trans_param - d.low) / d.step) * d.step + d.low, d.low, d.high) + ) + else: + if d.single(): + param = trans_param + else: + param = min(trans_param, np.nextafter(d.high, d.high - 1)) + elif isinstance(d, IntDistribution): + if d.log: + if transform_log: + param = int(np.clip(np.round(math.exp(trans_param)), d.low, d.high)) + else: + param = int(trans_param) + else: + param = int( + np.clip(np.round((trans_param - d.low) / d.step) * d.step + d.low, d.low, d.high) + ) + else: + assert False, "Should not reach. Unexpected distribution." + + return param diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_typing.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..fe8ebbb3642d685d88f4cd1d5a4490d8c7ea22ec --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/_typing.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from typing import Mapping +from typing import Sequence +from typing import Union + + +JSONSerializable = Union[ + Mapping[str, "JSONSerializable"], + Sequence["JSONSerializable"], + str, + int, + float, + bool, + None, +] + +__all__ = ["JSONSerializable"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/cli.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..3b87f210c22a6648a47ab5760cea915cf869b51d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/cli.py @@ -0,0 +1,1007 @@ +"""Optuna CLI module. +If you want to add a new command, you also need to update the constant `_COMMANDS` +""" + +from __future__ import annotations + +import argparse +from argparse import ArgumentParser +from argparse import Namespace +import datetime +from enum import Enum +import inspect +import json +import logging +import os +import sys +from typing import Any +import warnings + +import sqlalchemy.exc +import yaml + +import optuna +from optuna._imports import _LazyImport +from optuna.exceptions import CLIUsageError +from optuna.exceptions import ExperimentalWarning +from optuna.storages import BaseStorage +from optuna.storages import JournalFileStorage +from optuna.storages import JournalRedisStorage +from optuna.storages import JournalStorage +from optuna.storages import RDBStorage +from optuna.storages.journal import JournalFileBackend +from optuna.storages.journal import JournalRedisBackend +from optuna.trial import TrialState + + +_dataframe = _LazyImport("optuna.study._dataframe") + +_DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" + + +def _check_storage_url(storage_url: str | None) -> str: + if storage_url is not None: + return storage_url + + env_storage = os.environ.get("OPTUNA_STORAGE") + if env_storage is not None: + warnings.warn( + "Specifying the storage url via 'OPTUNA_STORAGE' environment variable" + " is an experimental feature. The interface can change in the future.", + ExperimentalWarning, + ) + return env_storage + raise CLIUsageError("Storage URL is not specified.") + + +def _get_storage(storage_url: str | None, storage_class: str | None) -> BaseStorage: + storage_url = _check_storage_url(storage_url) + if storage_class: + if storage_class == JournalRedisBackend.__name__: + return JournalStorage(JournalRedisBackend(storage_url)) + if storage_class == JournalRedisStorage.__name__: + return JournalStorage(JournalRedisStorage(storage_url)) + if storage_class == JournalFileBackend.__name__: + return JournalStorage(JournalFileBackend(storage_url)) + if storage_class == JournalFileStorage.__name__: + return JournalStorage(JournalFileStorage(storage_url)) + if storage_class == RDBStorage.__name__: + return RDBStorage(storage_url) + raise CLIUsageError("Unsupported storage class") + + if storage_url.startswith("redis"): + return JournalStorage(JournalRedisBackend(storage_url)) + if os.path.isfile(storage_url): + return JournalStorage(JournalFileBackend(storage_url)) + try: + return RDBStorage(storage_url) + except sqlalchemy.exc.ArgumentError: + raise CLIUsageError("Failed to guess storage class from storage_url") + + +def _format_value(value: Any) -> Any: + # Format value that can be serialized to JSON or YAML. + if value is None or isinstance(value, (int, float)): + return value + elif isinstance(value, datetime.datetime): + return value.strftime(_DATETIME_FORMAT) + elif isinstance(value, list): + return list(_format_value(v) for v in value) + elif isinstance(value, tuple): + return tuple(_format_value(v) for v in value) + elif isinstance(value, dict): + return {_format_value(k): _format_value(v) for k, v in value.items()} + else: + return str(value) + + +def _convert_to_dict( + records: list[dict[tuple[str, str], Any]], columns: list[tuple[str, str]], flatten: bool +) -> tuple[list[dict[str, Any]], list[str]]: + header = [] + ret = [] + if flatten: + for column in columns: + if column[1] != "": + header.append(f"{column[0]}_{column[1]}") + elif any(isinstance(record.get(column), (list, tuple)) for record in records): + max_length = 0 + for record in records: + if column in record: + max_length = max(max_length, len(record[column])) + for i in range(max_length): + header.append(f"{column[0]}_{i}") + else: + header.append(column[0]) + for record in records: + row = {} + for column in columns: + if column not in record: + continue + value = _format_value(record[column]) + if column[1] != "": + row[f"{column[0]}_{column[1]}"] = value + elif any(isinstance(record.get(column), (list, tuple)) for record in records): + for i, v in enumerate(value): + row[f"{column[0]}_{i}"] = v + else: + row[f"{column[0]}"] = value + ret.append(row) + else: + for column in columns: + if column[0] not in header: + header.append(column[0]) + for record in records: + attrs: dict[str, Any] = {column_name: {} for column_name in header} + for column in columns: + if column not in record: + continue + value = _format_value(record[column]) + if isinstance(column[1], int): + # Reconstruct list of values. `_dataframe._create_records_and_aggregate_column` + # returns indices of list as the second key of column. + if attrs[column[0]] == {}: + attrs[column[0]] = [] + attrs[column[0]] += [None] * max(column[1] + 1 - len(attrs[column[0]]), 0) + attrs[column[0]][column[1]] = value + elif column[1] != "": + attrs[column[0]][column[1]] = value + else: + attrs[column[0]] = value + ret.append(attrs) + + return ret, header + + +class ValueType(Enum): + NONE = 0 + NUMERIC = 1 + STRING = 2 + + +class CellValue: + def __init__(self, value: Any) -> None: + self.value = value + if value is None: + self.value_type = ValueType.NONE + elif isinstance(value, (int, float)): + self.value_type = ValueType.NUMERIC + else: + self.value_type = ValueType.STRING + + def __str__(self) -> str: + if isinstance(self.value, datetime.datetime): + return self.value.strftime(_DATETIME_FORMAT) + else: + return str(self.value) + + def width(self) -> int: + return len(str(self.value)) + + def get_string(self, value_type: ValueType, width: int) -> str: + value = str(self.value) + if self.value is None: + return " " * width + elif value_type == ValueType.NUMERIC: + return f"{value:>{width}}" + else: + return f"{value:<{width}}" + + +def _dump_value(records: list[dict[str, Any]], header: list[str]) -> str: + values = [] + for record in records: + row = [] + for column_name in header: + # Below follows the table formatting convention where record[column_name] is treated as + # an empty string if record[column_name] is None. e.g., {"a": None} is replaced with + # {"a": ""} + row.append(str(record[column_name]) if record.get(column_name) is not None else "") + values.append(" ".join(row)) + return "\n".join(values) + + +def _dump_table(records: list[dict[str, Any]], header: list[str]) -> str: + rows = [] + for record in records: + row = [] + for column_name in header: + row.append(CellValue(record.get(column_name))) + rows.append(row) + + separator = "+" + header_string = "|" + rows_string = ["|" for _ in rows] + for column in range(len(header)): + value_types = [row[column].value_type for row in rows] + value_type = ValueType.NUMERIC + for t in value_types: + if t == ValueType.STRING: + value_type = ValueType.STRING + if len(rows) == 0: + max_width = len(header[column]) + else: + max_width = max(len(header[column]), max(row[column].width() for row in rows)) + separator += "-" * (max_width + 2) + "+" + if value_type == ValueType.NUMERIC: + header_string += f" {header[column]:>{max_width}} |" + else: + header_string += f" {header[column]:<{max_width}} |" + for i, row in enumerate(rows): + rows_string[i] += " " + row[column].get_string(value_type, max_width) + " |" + + ret = "" + ret += separator + "\n" + ret += header_string + "\n" + ret += separator + "\n" + for row_string in rows_string: + ret += row_string + "\n" + ret += separator + "\n" + + return ret + + +def _format_output( + records: list[dict[tuple[str, str], Any]] | dict[tuple[str, str], Any], + columns: list[tuple[str, str]], + output_format: str, + flatten: bool, +) -> str: + if isinstance(records, list): + values, header = _convert_to_dict(records, columns, flatten) + else: + values, header = _convert_to_dict([records], columns, flatten) + + if output_format == "value": + return _dump_value(values, header).strip() + elif output_format == "table": + return _dump_table(values, header).strip() + elif output_format == "json": + if isinstance(records, list): + return json.dumps(values).strip() + else: + return json.dumps(values[0]).strip() + elif output_format == "yaml": + if isinstance(records, list): + return yaml.safe_dump(values).strip() + else: + return yaml.safe_dump(values[0]).strip() + else: + raise CLIUsageError(f"Optuna CLI does not supported the {output_format} format.") + + +class _BaseCommand: + """Base class for commands. + + Note that command classes are not intended to be called by library users. + They are exclusively used within this file to manage Optuna CLI commands. + """ + + def __init__(self) -> None: + self.logger = optuna.logging.get_logger(__name__) + + def add_arguments(self, parser: ArgumentParser) -> None: + """Add arguments required for each command. + + Args: + parser: + `ArgumentParser` object to add arguments + """ + pass + + def take_action(self, parsed_args: Namespace) -> int: + """Define action if the command is called. + + Args: + parsed_args: + `Namespace` object including arguments specified by user. + + Returns: + Running status of the action. + 0 if this method finishes normally, otherwise 1. + """ + + raise NotImplementedError + + +class _CreateStudy(_BaseCommand): + """Create a new study.""" + + def add_arguments(self, parser: ArgumentParser) -> None: + parser.add_argument( + "--study-name", + default=None, + help="A human-readable name of a study to distinguish it from others.", + ) + parser.add_argument( + "--direction", + default=None, + type=str, + choices=("minimize", "maximize"), + help="Set direction of optimization to a new study. Set 'minimize' " + "for minimization and 'maximize' for maximization.", + ) + parser.add_argument( + "--skip-if-exists", + default=False, + action="store_true", + help="If specified, the creation of the study is skipped " + "without any error when the study name is duplicated.", + ) + parser.add_argument( + "--directions", + type=str, + default=None, + choices=("minimize", "maximize"), + help="Set directions of optimization to a new study." + " Put whitespace between directions. Each direction should be" + ' either "minimize" or "maximize".', + nargs="+", + ) + + def take_action(self, parsed_args: Namespace) -> int: + storage = _get_storage(parsed_args.storage, parsed_args.storage_class) + study_name = optuna.create_study( + storage=storage, + study_name=parsed_args.study_name, + direction=parsed_args.direction, + directions=parsed_args.directions, + load_if_exists=parsed_args.skip_if_exists, + ).study_name + print(study_name) + return 0 + + +class _DeleteStudy(_BaseCommand): + """Delete a specified study.""" + + def add_arguments(self, parser: ArgumentParser) -> None: + parser.add_argument("--study-name", default=None, help="The name of the study to delete.") + + def take_action(self, parsed_args: Namespace) -> int: + storage = _get_storage(parsed_args.storage, parsed_args.storage_class) + study_id = storage.get_study_id_from_name(parsed_args.study_name) + storage.delete_study(study_id) + return 0 + + +class _StudySetUserAttribute(_BaseCommand): + """Set a user attribute to a study.""" + + def add_arguments(self, parser: ArgumentParser) -> None: + parser.add_argument( + "--study-name", + required=True, + help="The name of the study to set the user attribute to.", + ) + parser.add_argument("--key", "-k", required=True, help="Key of the user attribute.") + parser.add_argument("--value", required=True, help="Value to be set.") + + def take_action(self, parsed_args: Namespace) -> int: + storage = _get_storage(parsed_args.storage, parsed_args.storage_class) + + study = optuna.load_study(storage=storage, study_name=parsed_args.study_name) + + study.set_user_attr(parsed_args.key, parsed_args.value) + + self.logger.info("Attribute successfully written.") + return 0 + + +class _StudyNames(_BaseCommand): + """Get all study names stored in a specified storage""" + + def add_arguments(self, parser: ArgumentParser) -> None: + parser.add_argument( + "-f", + "--format", + type=str, + choices=("value", "json", "table", "yaml"), + default="value", + help="Output format.", + ) + + def take_action(self, parsed_args: Namespace) -> int: + storage = _get_storage(parsed_args.storage, parsed_args.storage_class) + all_study_names = optuna.get_all_study_names(storage) + records = [] + record_key = ("name", "") + for study_name in all_study_names: + records.append({record_key: study_name}) + print(_format_output(records, [record_key], parsed_args.format, flatten=False)) + return 0 + + +class _Studies(_BaseCommand): + """Show a list of studies.""" + + _study_list_header = [ + ("name", ""), + ("direction", ""), + ("n_trials", ""), + ("datetime_start", ""), + ] + + def add_arguments(self, parser: ArgumentParser) -> None: + parser.add_argument( + "-f", + "--format", + type=str, + choices=("value", "json", "table", "yaml"), + default="table", + help="Output format.", + ) + parser.add_argument( + "--flatten", + default=False, + action="store_true", + help="Flatten nested columns such as directions.", + ) + + def take_action(self, parsed_args: Namespace) -> int: + storage = _get_storage(parsed_args.storage, parsed_args.storage_class) + summaries = optuna.get_all_study_summaries(storage, include_best_trial=False) + + records = [] + for s in summaries: + start = ( + s.datetime_start.strftime(_DATETIME_FORMAT) + if s.datetime_start is not None + else None + ) + record: dict[tuple[str, str], Any] = {} + record[("name", "")] = s.study_name + record[("direction", "")] = tuple(d.name for d in s.directions) + record[("n_trials", "")] = s.n_trials + record[("datetime_start", "")] = start + record[("user_attrs", "")] = s.user_attrs + records.append(record) + + if any(r[("user_attrs", "")] != {} for r in records): + self._study_list_header.append(("user_attrs", "")) + print( + _format_output( + records, self._study_list_header, parsed_args.format, parsed_args.flatten + ) + ) + return 0 + + +class _Trials(_BaseCommand): + """Show a list of trials.""" + + def add_arguments(self, parser: ArgumentParser) -> None: + parser.add_argument( + "--study-name", + type=str, + required=True, + help="The name of the study which includes trials.", + ) + parser.add_argument( + "-f", + "--format", + type=str, + choices=("value", "json", "table", "yaml"), + default="table", + help="Output format.", + ) + parser.add_argument( + "--flatten", + default=False, + action="store_true", + help="Flatten nested columns such as params and user_attrs.", + ) + + def take_action(self, parsed_args: Namespace) -> int: + warnings.warn( + "'trials' is an experimental CLI command. The interface can change in the future.", + ExperimentalWarning, + ) + + storage = _get_storage(parsed_args.storage, parsed_args.storage_class) + study = optuna.load_study(storage=storage, study_name=parsed_args.study_name) + attrs = ( + "number", + "value" if not study._is_multi_objective() else "values", + "datetime_start", + "datetime_complete", + "duration", + "params", + "user_attrs", + "state", + ) + + records, columns = _dataframe._create_records_and_aggregate_column(study, attrs) + print(_format_output(records, columns, parsed_args.format, parsed_args.flatten)) + + return 0 + + +class _BestTrial(_BaseCommand): + """Show the best trial.""" + + def add_arguments(self, parser: ArgumentParser) -> None: + parser.add_argument( + "--study-name", + type=str, + required=True, + help="The name of the study to get the best trial.", + ) + parser.add_argument( + "-f", + "--format", + type=str, + choices=("value", "json", "table", "yaml"), + default="table", + help="Output format.", + ) + parser.add_argument( + "--flatten", + default=False, + action="store_true", + help="Flatten nested columns such as params and user_attrs.", + ) + + def take_action(self, parsed_args: Namespace) -> int: + warnings.warn( + "'best-trial' is an experimental CLI command. The interface can change in the future.", + ExperimentalWarning, + ) + + storage = _get_storage(parsed_args.storage, parsed_args.storage_class) + study = optuna.load_study(storage=storage, study_name=parsed_args.study_name) + attrs = ( + "number", + "value" if not study._is_multi_objective() else "values", + "datetime_start", + "datetime_complete", + "duration", + "params", + "user_attrs", + "state", + ) + + records, columns = _dataframe._create_records_and_aggregate_column(study, attrs) + print( + _format_output( + records[study.best_trial.number], columns, parsed_args.format, parsed_args.flatten + ) + ) + return 0 + + +class _BestTrials(_BaseCommand): + """Show a list of trials located at the Pareto front.""" + + def add_arguments(self, parser: ArgumentParser) -> None: + parser.add_argument( + "--study-name", + type=str, + required=True, + help="The name of the study to get the best trials (trials at the Pareto front).", + ) + parser.add_argument( + "-f", + "--format", + type=str, + choices=("value", "json", "table", "yaml"), + default="table", + help="Output format.", + ) + parser.add_argument( + "--flatten", + default=False, + action="store_true", + help="Flatten nested columns such as params and user_attrs.", + ) + + def take_action(self, parsed_args: Namespace) -> int: + warnings.warn( + "'best-trials' is an experimental CLI command. The interface can change in the " + "future.", + ExperimentalWarning, + ) + + storage = _get_storage(parsed_args.storage, parsed_args.storage_class) + study = optuna.load_study(storage=storage, study_name=parsed_args.study_name) + best_trials = [trial.number for trial in study.best_trials] + attrs = ( + "number", + "value" if not study._is_multi_objective() else "values", + "datetime_start", + "datetime_complete", + "duration", + "params", + "user_attrs", + "state", + ) + + records, columns = _dataframe._create_records_and_aggregate_column(study, attrs) + best_records = list(filter(lambda record: record[("number", "")] in best_trials, records)) + print(_format_output(best_records, columns, parsed_args.format, parsed_args.flatten)) + return 0 + + +class _StorageUpgrade(_BaseCommand): + """Upgrade the schema of an RDB storage.""" + + def take_action(self, parsed_args: Namespace) -> int: + storage_url = _check_storage_url(parsed_args.storage) + try: + storage = RDBStorage( + storage_url, skip_compatibility_check=True, skip_table_creation=True + ) + except sqlalchemy.exc.ArgumentError: + self.logger.error("Invalid RDBStorage URL.") + return 1 + current_version = storage.get_current_version() + head_version = storage.get_head_version() + known_versions = storage.get_all_versions() + if current_version == head_version: + self.logger.info("This storage is up-to-date.") + elif current_version in known_versions: + self.logger.info("Upgrading the storage schema to the latest version.") + storage.upgrade() + self.logger.info("Completed to upgrade the storage.") + else: + warnings.warn( + "Your optuna version seems outdated against the storage version. " + "Please try updating optuna to the latest version by " + "`$ pip install -U optuna`." + ) + return 0 + + +class _Ask(_BaseCommand): + """Create a new trial and suggest parameters.""" + + def add_arguments(self, parser: ArgumentParser) -> None: + parser.add_argument("--study-name", type=str, help="Name of study.") + parser.add_argument("--sampler", type=str, help="Class name of sampler object to create.") + parser.add_argument( + "--sampler-kwargs", + type=str, + help="Sampler object initialization keyword arguments as JSON.", + ) + parser.add_argument( + "--search-space", + type=str, + help=( + "Search space as JSON. Keys are names and values are outputs from " + ":func:`~optuna.distributions.distribution_to_json`." + ), + ) + parser.add_argument( + "-f", + "--format", + type=str, + choices=("value", "json", "table", "yaml"), + default="json", + help="Output format.", + ) + parser.add_argument( + "--flatten", + default=False, + action="store_true", + help="Flatten nested columns such as params.", + ) + + def take_action(self, parsed_args: Namespace) -> int: + warnings.warn( + "'ask' is an experimental CLI command. The interface can change in the future.", + ExperimentalWarning, + ) + + storage = _get_storage(parsed_args.storage, parsed_args.storage_class) + + create_study_kwargs = { + "storage": storage, + "study_name": parsed_args.study_name, + "load_if_exists": True, + } + + if parsed_args.sampler is not None: + if parsed_args.sampler_kwargs is not None: + sampler_kwargs = json.loads(parsed_args.sampler_kwargs) + else: + sampler_kwargs = {} + sampler_cls = getattr(optuna.samplers, parsed_args.sampler) + sampler = sampler_cls(**sampler_kwargs) + create_study_kwargs["sampler"] = sampler + else: + if parsed_args.sampler_kwargs is not None: + raise ValueError( + "`--sampler_kwargs` is set without `--sampler`. Please specify `--sampler` as" + " well or omit `--sampler-kwargs`." + ) + + if parsed_args.search_space is not None: + # The search space is expected to be a JSON serialized string, e.g. + # '{"x": {"name": "FloatDistribution", "attributes": {"low": 0.0, "high": 1.0}}, + # "y": ...}'. + search_space = { + name: optuna.distributions.json_to_distribution(json.dumps(dist)) + for name, dist in json.loads(parsed_args.search_space).items() + } + else: + search_space = {} + + try: + study = optuna.load_study( + study_name=create_study_kwargs["study_name"], + storage=create_study_kwargs["storage"], + sampler=create_study_kwargs.get("sampler"), + ) + + except KeyError: + raise KeyError( + "Implicit study creation within the 'ask' command was dropped in Optuna v4.0.0. " + "Please use the 'create-study' command beforehand." + ) + trial = study.ask(fixed_distributions=search_space) + + self.logger.info(f"Asked trial {trial.number} with parameters {trial.params}.") + + record: dict[tuple[str, str], Any] = {("number", ""): trial.number} + columns = [("number", "")] + + if len(trial.params) == 0 and not parsed_args.flatten: + record[("params", "")] = {} + columns.append(("params", "")) + else: + for param_name, param_value in trial.params.items(): + record[("params", param_name)] = param_value + columns.append(("params", param_name)) + + print(_format_output(record, columns, parsed_args.format, parsed_args.flatten)) + return 0 + + +class _Tell(_BaseCommand): + """Finish a trial, which was created by the ask command.""" + + def add_arguments(self, parser: ArgumentParser) -> None: + parser.add_argument("--study-name", type=str, help="Name of study.") + parser.add_argument("--trial-number", type=int, help="Trial number.") + parser.add_argument("--values", type=float, nargs="+", help="Objective values.") + parser.add_argument( + "--state", + type=str, + help="Trial state.", + choices=("complete", "pruned", "fail"), + ) + parser.add_argument( + "--skip-if-finished", + default=False, + action="store_true", + help="If specified, tell is skipped without any error when the trial is already " + "finished.", + ) + + def take_action(self, parsed_args: Namespace) -> int: + warnings.warn( + "'tell' is an experimental CLI command. The interface can change in the future.", + ExperimentalWarning, + ) + + storage = _get_storage(parsed_args.storage, parsed_args.storage_class) + + study = optuna.load_study( + storage=storage, + study_name=parsed_args.study_name, + ) + + if parsed_args.state is not None: + state: TrialState | None = TrialState[parsed_args.state.upper()] + else: + state = None + + trial_number = parsed_args.trial_number + values = parsed_args.values + + study.tell( + trial=trial_number, + values=values, + state=state, + skip_if_finished=parsed_args.skip_if_finished, + ) + + self.logger.info(f"Told trial {trial_number} with values {values} and state {state}.") + + return 0 + + +_COMMANDS: dict[str, type[_BaseCommand]] = { + "create-study": _CreateStudy, + "delete-study": _DeleteStudy, + "study set-user-attr": _StudySetUserAttribute, + "study-names": _StudyNames, + "studies": _Studies, + "trials": _Trials, + "best-trial": _BestTrial, + "best-trials": _BestTrials, + "storage upgrade": _StorageUpgrade, + "ask": _Ask, + "tell": _Tell, +} + + +def _parse_storage_class_without_suggesting_deprecated_choices(value: str) -> str: + choices = [ + RDBStorage.__name__, + JournalFileBackend.__name__, + JournalRedisBackend.__name__, + ] + deprecated_choices = [ + JournalFileStorage.__name__, + JournalRedisStorage.__name__, + ] + if value in choices + deprecated_choices: + return value + raise argparse.ArgumentTypeError( + f"Invalid choice: {value} (choose from {str(choices)[1:-1]})" + ) + + +def _add_common_arguments(parser: ArgumentParser) -> ArgumentParser: + parser.add_argument( + "--storage", + default=None, + help=( + "DB URL. (e.g. sqlite:///example.db) " + "Also can be specified via OPTUNA_STORAGE environment variable." + ), + ) + parser.add_argument( + "--storage-class", + help="Storage class hint (e.g. JournalFileBackend)", + default=None, + type=_parse_storage_class_without_suggesting_deprecated_choices, + ) + verbose_group = parser.add_mutually_exclusive_group() + verbose_group.add_argument( + "-v", + "--verbose", + action="count", + dest="verbose_level", + default=1, + help="Increase verbosity of output. Can be repeated.", + ) + verbose_group.add_argument( + "-q", + "--quiet", + action="store_const", + dest="verbose_level", + const=0, + help="Suppress output except warnings and errors.", + ) + parser.add_argument( + "--log-file", + action="store", + default=None, + help="Specify a file to log output. Disabled by default.", + ) + parser.add_argument( + "--debug", + default=False, + action="store_true", + help="Show tracebacks on errors.", + ) + return parser + + +def _add_commands( + main_parser: ArgumentParser, parent_parser: ArgumentParser +) -> dict[str, ArgumentParser]: + subparsers = main_parser.add_subparsers() + command_name_to_subparser = {} + + for command_name, command_type in _COMMANDS.items(): + command = command_type() + subparser = subparsers.add_parser( + command_name, parents=[parent_parser], help=inspect.getdoc(command_type) + ) + command.add_arguments(subparser) + subparser.set_defaults(handler=command.take_action) + command_name_to_subparser[command_name] = subparser + + def _print_help(args: Namespace) -> None: + main_parser.print_help() + + subparsers.add_parser("help", help="Show help message and exit.").set_defaults( + handler=_print_help + ) + return command_name_to_subparser + + +def _get_parser(description: str = "") -> tuple[ArgumentParser, dict[str, ArgumentParser]]: + # Use `parent_parser` is necessary to avoid namespace conflict for -h/--help + # between `main_parser` and `subparser`. + parent_parser = ArgumentParser(add_help=False) + parent_parser = _add_common_arguments(parent_parser) + + main_parser = ArgumentParser(description=description, parents=[parent_parser]) + main_parser.add_argument( + "--version", action="version", version="{0} {1}".format("optuna", optuna.__version__) + ) + command_name_to_subparser = _add_commands(main_parser, parent_parser) + return main_parser, command_name_to_subparser + + +def _preprocess_argv(argv: list[str]) -> list[str]: + # Some preprocess is necessary for argv because some subcommand includes space + # (e.g. optuna storage upgrade). + argv = argv[1:] if len(argv) > 1 else ["help"] + + for i in range(len(argv)): + for j in range(i, i + 2): # Commands consist of one or two words. + command_candidate = " ".join(argv[i : j + 1]) + if command_candidate in _COMMANDS: + options = argv[:i] + argv[j + 1 :] + return [command_candidate] + options + + # No subcommand is found. + return argv + + +def _set_verbosity(args: Namespace) -> None: + root_logger = logging.getLogger() + root_logger.setLevel(logging.DEBUG) + stream_handler = logging.StreamHandler(sys.stderr) + + logging_level = { + 0: logging.WARNING, + 1: logging.INFO, + 2: logging.DEBUG, + }.get(args.verbose_level, logging.DEBUG) + + stream_handler.setLevel(logging_level) + stream_handler.setFormatter(optuna.logging.create_default_formatter()) + root_logger.addHandler(stream_handler) + + optuna.logging.set_verbosity(logging_level) + + +def _set_log_file(args: Namespace) -> None: + if args.log_file is None: + return + + root_logger = logging.getLogger() + root_logger.setLevel(logging.DEBUG) + + file_handler = logging.FileHandler( + filename=args.log_file, + ) + file_handler.setFormatter(optuna.logging.create_default_formatter()) + root_logger.addHandler(file_handler) + + +def main() -> int: + main_parser, command_name_to_subparser = _get_parser() + + argv = sys.argv + preprocessed_argv = _preprocess_argv(argv) + args = main_parser.parse_args(preprocessed_argv) + + _set_verbosity(args) + _set_log_file(args) + + logger = logging.getLogger("optuna") + try: + return args.handler(args) + except CLIUsageError as e: + if args.debug: + logger.exception(e) + else: + logger.error(e) + # This code is required to show help for each subcommand. + # NOTE: the first element of `preprocessed_argv` is command name. + command_name_to_subparser[preprocessed_argv[0]].print_help() + return 1 + except AttributeError: + # Exception for the case -v/--verbose/-q/--quiet/--log-file/--debug + # without any subcommand. + argv_str = " ".join(argv[1:]) + logger.error(f"'{argv_str}' is not an optuna command. see 'optuna --help'") + main_parser.print_help() + return 1 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/distributions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..bf9984f20e61eec0fe63654a42745f71e535b118 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/distributions.py @@ -0,0 +1,792 @@ +from __future__ import annotations + +import abc +import copy +import decimal +import json +import math +from numbers import Real +from typing import Any +from typing import cast +from typing import TYPE_CHECKING +from typing import Union +import warnings + +from optuna._deprecated import deprecated_class + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +CategoricalChoiceType = Union[None, bool, int, float, str] + + +_float_distribution_deprecated_msg = ( + "Use :class:`~optuna.distributions.FloatDistribution` instead." +) +_int_distribution_deprecated_msg = "Use :class:`~optuna.distributions.IntDistribution` instead." + + +class BaseDistribution(abc.ABC): + """Base class for distributions. + + Note that distribution classes are not supposed to be called by library users. + They are used by :class:`~optuna.trial.Trial` and :class:`~optuna.samplers` internally. + """ + + def to_external_repr(self, param_value_in_internal_repr: float) -> Any: + """Convert internal representation of a parameter value into external representation. + + Args: + param_value_in_internal_repr: + Optuna's internal representation of a parameter value. + + Returns: + Optuna's external representation of a parameter value. + """ + + return param_value_in_internal_repr + + @abc.abstractmethod + def to_internal_repr(self, param_value_in_external_repr: Any) -> float: + """Convert external representation of a parameter value into internal representation. + + Args: + param_value_in_external_repr: + Optuna's external representation of a parameter value. + + Returns: + Optuna's internal representation of a parameter value. + """ + + raise NotImplementedError + + @abc.abstractmethod + def single(self) -> bool: + """Test whether the range of this distribution contains just a single value. + + Returns: + :obj:`True` if the range of this distribution contains just a single value, + otherwise :obj:`False`. + """ + + raise NotImplementedError + + @abc.abstractmethod + def _contains(self, param_value_in_internal_repr: float) -> bool: + """Test if a parameter value is contained in the range of this distribution. + + Args: + param_value_in_internal_repr: + Optuna's internal representation of a parameter value. + + Returns: + :obj:`True` if the parameter value is contained in the range of this distribution, + otherwise :obj:`False`. + """ + + raise NotImplementedError + + def _asdict(self) -> dict: + return self.__dict__ + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, BaseDistribution): + return NotImplemented + if type(self) is not type(other): + return False + return self.__dict__ == other.__dict__ + + def __hash__(self) -> int: + return hash((self.__class__,) + tuple(sorted(self.__dict__.items()))) + + def __repr__(self) -> str: + kwargs = ", ".join("{}={}".format(k, v) for k, v in sorted(self._asdict().items())) + return "{}({})".format(self.__class__.__name__, kwargs) + + +class FloatDistribution(BaseDistribution): + """A distribution on floats. + + This object is instantiated by :func:`~optuna.trial.Trial.suggest_float`, and passed to + :mod:`~optuna.samplers` in general. + + .. note:: + When ``step`` is not :obj:`None`, if the range :math:`[\\mathsf{low}, \\mathsf{high}]` + is not divisible by :math:`\\mathsf{step}`, :math:`\\mathsf{high}` will be replaced + with the maximum of :math:`k \\times \\mathsf{step} + \\mathsf{low} < \\mathsf{high}`, + where :math:`k` is an integer. + + Attributes: + low: + Lower endpoint of the range of the distribution. ``low`` is included in the range. + ``low`` must be less than or equal to ``high``. If ``log`` is :obj:`True`, + ``low`` must be larger than 0. + high: + Upper endpoint of the range of the distribution. ``high`` is included in the range. + ``high`` must be greater than or equal to ``low``. + log: + If ``log`` is :obj:`True`, this distribution is in log-scaled domain. + In this case, all parameters enqueued to the distribution must be positive values. + This parameter must be :obj:`False` when the parameter ``step`` is not :obj:`None`. + step: + A discretization step. ``step`` must be larger than 0. + This parameter must be :obj:`None` when the parameter ``log`` is :obj:`True`. + + """ + + def __init__( + self, low: float, high: float, log: bool = False, step: None | float = None + ) -> None: + if log and step is not None: + raise ValueError("The parameter `step` is not supported when `log` is true.") + + if low > high: + raise ValueError( + "The `low` value must be smaller than or equal to the `high` value " + "(low={}, high={}).".format(low, high) + ) + + if log and low <= 0.0: + raise ValueError( + "The `low` value must be larger than 0 for a log distribution " + "(low={}, high={}).".format(low, high) + ) + + if step is not None and step <= 0: + raise ValueError( + "The `step` value must be non-zero positive value, " "but step={}.".format(step) + ) + + self.step = None + if step is not None: + high = _adjust_discrete_uniform_high(low, high, step) + self.step = float(step) + + self.low = float(low) + self.high = float(high) + self.log = log + + def single(self) -> bool: + if self.step is None: + return self.low == self.high + else: + if self.low == self.high: + return True + high = decimal.Decimal(str(self.high)) + low = decimal.Decimal(str(self.low)) + step = decimal.Decimal(str(self.step)) + return (high - low) < step + + def _contains(self, param_value_in_internal_repr: float) -> bool: + value = param_value_in_internal_repr + if self.step is None: + return self.low <= value <= self.high + else: + k = (value - self.low) / self.step + return self.low <= value <= self.high and abs(k - round(k)) < 1.0e-8 + + def to_internal_repr(self, param_value_in_external_repr: float) -> float: + try: + internal_repr = float(param_value_in_external_repr) + except (ValueError, TypeError) as e: + raise ValueError( + f"'{param_value_in_external_repr}' is not a valid type. " + "float-castable value is expected." + ) from e + + if math.isnan(internal_repr): + raise ValueError(f"`{param_value_in_external_repr}` is invalid value.") + if self.log and internal_repr <= 0.0: + raise ValueError( + f"`{param_value_in_external_repr}` is invalid value for the case log=True." + ) + return internal_repr + + +@deprecated_class("3.0.0", "6.0.0", text=_float_distribution_deprecated_msg) +class UniformDistribution(FloatDistribution): + """A uniform distribution in the linear domain. + + This object is instantiated by :func:`~optuna.trial.Trial.suggest_float`, and passed to + :mod:`~optuna.samplers` in general. + + Attributes: + low: + Lower endpoint of the range of the distribution. ``low`` is included in the range. + ``low`` must be less than or equal to ``high``. + high: + Upper endpoint of the range of the distribution. ``high`` is included in the range. + ``high`` must be greater than or equal to ``low``. + + """ + + def __init__(self, low: float, high: float) -> None: + super().__init__(low=low, high=high, log=False, step=None) + + def _asdict(self) -> dict: + d = copy.deepcopy(self.__dict__) + d.pop("log") + d.pop("step") + return d + + +@deprecated_class("3.0.0", "6.0.0", text=_float_distribution_deprecated_msg) +class LogUniformDistribution(FloatDistribution): + """A uniform distribution in the log domain. + + This object is instantiated by :func:`~optuna.trial.Trial.suggest_float` with ``log=True``, + and passed to :mod:`~optuna.samplers` in general. + + Attributes: + low: + Lower endpoint of the range of the distribution. ``low`` is included in the range. + ``low`` must be larger than 0. ``low`` must be less than or equal to ``high``. + high: + Upper endpoint of the range of the distribution. ``high`` is included in the range. + ``high`` must be greater than or equal to ``low``. + + """ + + def __init__(self, low: float, high: float) -> None: + super().__init__(low=low, high=high, log=True, step=None) + + def _asdict(self) -> dict: + d = copy.deepcopy(self.__dict__) + d.pop("log") + d.pop("step") + return d + + +@deprecated_class("3.0.0", "6.0.0", text=_float_distribution_deprecated_msg) +class DiscreteUniformDistribution(FloatDistribution): + """A discretized uniform distribution in the linear domain. + + This object is instantiated by :func:`~optuna.trial.Trial.suggest_float` with ``step`` + argument, and passed to :mod:`~optuna.samplers` in general. + + .. note:: + If the range :math:`[\\mathsf{low}, \\mathsf{high}]` is not divisible by :math:`q`, + :math:`\\mathsf{high}` will be replaced with the maximum of :math:`k q + \\mathsf{low} + < \\mathsf{high}`, where :math:`k` is an integer. + + Args: + low: + Lower endpoint of the range of the distribution. ``low`` is included in the range. + ``low`` must be less than or equal to ``high``. + high: + Upper endpoint of the range of the distribution. ``high`` is included in the range. + ``high`` must be greater than or equal to ``low``. + q: + A discretization step. ``q`` must be larger than 0. + + Attributes: + low: + Lower endpoint of the range of the distribution. ``low`` is included in the range. + high: + Upper endpoint of the range of the distribution. ``high`` is included in the range. + + """ + + def __init__(self, low: float, high: float, q: float) -> None: + super().__init__(low=low, high=high, step=q) + + def _asdict(self) -> dict: + d = copy.deepcopy(self.__dict__) + d.pop("log") + + step = d.pop("step") + d["q"] = step + return d + + @property + def q(self) -> float: + """Discretization step. + + :class:`~optuna.distributions.DiscreteUniformDistribution` is a subtype of + :class:`~optuna.distributions.FloatDistribution`. + This property is a proxy for its ``step`` attribute. + """ + return cast("float", self.step) + + @q.setter + def q(self, v: float) -> None: + self.step = v + + +class IntDistribution(BaseDistribution): + """A distribution on integers. + + This object is instantiated by :func:`~optuna.trial.Trial.suggest_int`, and passed to + :mod:`~optuna.samplers` in general. + + .. note:: + When ``step`` is not :obj:`None`, if the range :math:`[\\mathsf{low}, \\mathsf{high}]` + is not divisible by :math:`\\mathsf{step}`, :math:`\\mathsf{high}` will be replaced + with the maximum of :math:`k \\times \\mathsf{step} + \\mathsf{low} < \\mathsf{high}`, + where :math:`k` is an integer. + + Attributes: + low: + Lower endpoint of the range of the distribution. ``low`` is included in the range. + ``low`` must be less than or equal to ``high``. If ``log`` is :obj:`True`, + ``low`` must be larger than or equal to 1. + high: + Upper endpoint of the range of the distribution. ``high`` is included in the range. + ``high`` must be greater than or equal to ``low``. + log: + If ``log`` is :obj:`True`, this distribution is in log-scaled domain. + In this case, all parameters enqueued to the distribution must be positive values. + This parameter must be :obj:`False` when the parameter ``step`` is not 1. + step: + A discretization step. ``step`` must be a positive integer. This parameter must be 1 + when the parameter ``log`` is :obj:`True`. + + """ + + def __init__(self, low: int, high: int, log: bool = False, step: int = 1) -> None: + if log and step != 1: + raise ValueError( + "Samplers and other components in Optuna only accept step is 1 " + "when `log` argument is True." + ) + + if low > high: + raise ValueError( + "The `low` value must be smaller than or equal to the `high` value " + "(low={}, high={}).".format(low, high) + ) + + if log and low < 1: + raise ValueError( + "The `low` value must be equal to or greater than 1 for a log distribution " + "(low={}, high={}).".format(low, high) + ) + + if step <= 0: + raise ValueError( + "The `step` value must be non-zero positive value, but step={}.".format(step) + ) + + self.log = log + self.step = int(step) + self.low = int(low) + high = int(high) + self.high = _adjust_int_uniform_high(self.low, high, self.step) + + def to_external_repr(self, param_value_in_internal_repr: float) -> int: + return int(param_value_in_internal_repr) + + def to_internal_repr(self, param_value_in_external_repr: int) -> float: + try: + internal_repr = float(param_value_in_external_repr) + except (ValueError, TypeError) as e: + raise ValueError( + f"'{param_value_in_external_repr}' is not a valid type. " + "float-castable value is expected." + ) from e + + if math.isnan(internal_repr): + raise ValueError(f"`{param_value_in_external_repr}` is invalid value.") + if self.log and internal_repr <= 0.0: + raise ValueError( + f"`{param_value_in_external_repr}` is invalid value for the case log=True." + ) + return internal_repr + + def single(self) -> bool: + if self.log: + return self.low == self.high + + if self.low == self.high: + return True + return (self.high - self.low) < self.step + + def _contains(self, param_value_in_internal_repr: float) -> bool: + value = param_value_in_internal_repr + return self.low <= value <= self.high and (value - self.low) % self.step == 0 + + +@deprecated_class("3.0.0", "6.0.0", text=_int_distribution_deprecated_msg) +class IntUniformDistribution(IntDistribution): + """A uniform distribution on integers. + + This object is instantiated by :func:`~optuna.trial.Trial.suggest_int`, and passed to + :mod:`~optuna.samplers` in general. + + .. note:: + If the range :math:`[\\mathsf{low}, \\mathsf{high}]` is not divisible by + :math:`\\mathsf{step}`, :math:`\\mathsf{high}` will be replaced with the maximum of + :math:`k \\times \\mathsf{step} + \\mathsf{low} < \\mathsf{high}`, where :math:`k` is + an integer. + + Attributes: + low: + Lower endpoint of the range of the distribution. ``low`` is included in the range. + ``low`` must be less than or equal to ``high``. + high: + Upper endpoint of the range of the distribution. ``high`` is included in the range. + ``high`` must be greater than or equal to ``low``. + step: + A discretization step. ``step`` must be a positive integer. + + """ + + def __init__(self, low: int, high: int, step: int = 1) -> None: + super().__init__(low=low, high=high, log=False, step=step) + + def _asdict(self) -> dict: + d = copy.deepcopy(self.__dict__) + d.pop("log") + return d + + +@deprecated_class("3.0.0", "6.0.0", text=_int_distribution_deprecated_msg) +class IntLogUniformDistribution(IntDistribution): + """A uniform distribution on integers in the log domain. + + This object is instantiated by :func:`~optuna.trial.Trial.suggest_int`, and passed to + :mod:`~optuna.samplers` in general. + + Attributes: + low: + Lower endpoint of the range of the distribution. ``low`` is included in the range + and must be larger than or equal to 1. ``low`` must be less than or equal to ``high``. + high: + Upper endpoint of the range of the distribution. ``high`` is included in the range. + ``high`` must be greater than or equal to ``low``. + step: + A discretization step. ``step`` must be a positive integer. + + """ + + def __init__(self, low: int, high: int, step: int = 1) -> None: + super().__init__(low=low, high=high, log=True, step=step) + + def _asdict(self) -> dict: + d = copy.deepcopy(self.__dict__) + d.pop("log") + return d + + +def _categorical_choice_equal( + value1: CategoricalChoiceType, value2: CategoricalChoiceType +) -> bool: + """A function to check two choices equal considering NaN. + + This function can handle NaNs like np.float32("nan") other than float. + """ + + value1_is_nan = isinstance(value1, Real) and math.isnan(float(value1)) + value2_is_nan = isinstance(value2, Real) and math.isnan(float(value2)) + return (value1 == value2) or (value1_is_nan and value2_is_nan) + + +class CategoricalDistribution(BaseDistribution): + """A categorical distribution. + + This object is instantiated by :func:`~optuna.trial.Trial.suggest_categorical`, and + passed to :mod:`~optuna.samplers` in general. + + Args: + choices: + Parameter value candidates. ``choices`` must have one element at least. + + .. note:: + + Not all types are guaranteed to be compatible with all storages. It is recommended to + restrict the types of the choices to :obj:`None`, :class:`bool`, :class:`int`, + :class:`float` and :class:`str`. + + Attributes: + choices: + Parameter value candidates. + + """ + + def __init__(self, choices: Sequence[CategoricalChoiceType]) -> None: + if len(choices) == 0: + raise ValueError("The `choices` must contain one or more elements.") + for choice in choices: + if choice is not None and not isinstance(choice, (bool, int, float, str)): + message = ( + "Choices for a categorical distribution should be a tuple of None, bool, " + "int, float and str for persistent storage but contains {} which is of type " + "{}.".format(choice, type(choice).__name__) + ) + warnings.warn(message) + + self.choices = tuple(choices) + + def to_external_repr(self, param_value_in_internal_repr: float) -> CategoricalChoiceType: + return self.choices[int(param_value_in_internal_repr)] + + def to_internal_repr(self, param_value_in_external_repr: CategoricalChoiceType) -> float: + try: + # NOTE(nabenabe): With this implementation, we cannot distinguish some values + # such as True and 1, or 1.0 and 1. For example, if choices=[True, 1] and external_repr + # is 1, this method wrongly returns 0 instead of 1. However, we decided to accept this + # bug for such exceptional choices for less complexity and faster processing. + return self.choices.index(param_value_in_external_repr) + except ValueError: # ValueError: param_value_in_external_repr is not in choices. + # ValueError also happens if external_repr is nan or includes precision error in float. + for index, choice in enumerate(self.choices): + if _categorical_choice_equal(param_value_in_external_repr, choice): + return index + + raise ValueError(f"'{param_value_in_external_repr}' not in {self.choices}.") + + def single(self) -> bool: + return len(self.choices) == 1 + + def _contains(self, param_value_in_internal_repr: float) -> bool: + index = int(param_value_in_internal_repr) + return 0 <= index < len(self.choices) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, BaseDistribution): + return NotImplemented + if not isinstance(other, self.__class__): + return False + if self.__dict__.keys() != other.__dict__.keys(): + return False + for key, value in self.__dict__.items(): + if key == "choices": + if len(value) != len(getattr(other, key)): + return False + for choice, other_choice in zip(value, getattr(other, key)): + if not _categorical_choice_equal(choice, other_choice): + return False + else: + if value != getattr(other, key): + return False + return True + + __hash__ = BaseDistribution.__hash__ + + +DISTRIBUTION_CLASSES = ( + IntDistribution, + IntLogUniformDistribution, + IntUniformDistribution, + FloatDistribution, + UniformDistribution, + LogUniformDistribution, + DiscreteUniformDistribution, + CategoricalDistribution, +) + + +def json_to_distribution(json_str: str) -> BaseDistribution: + """Deserialize a distribution in JSON format. + + Args: + json_str: A JSON-serialized distribution. + + Returns: + A deserialized distribution. + + """ + + json_dict = json.loads(json_str) + + if "name" in json_dict: + if json_dict["name"] == CategoricalDistribution.__name__: + json_dict["attributes"]["choices"] = tuple(json_dict["attributes"]["choices"]) + + for cls in DISTRIBUTION_CLASSES: + if json_dict["name"] == cls.__name__: + return cls(**json_dict["attributes"]) + + raise ValueError("Unknown distribution class: {}".format(json_dict["name"])) + + else: + # Deserialize a distribution from an abbreviated format. + if json_dict["type"] == "categorical": + return CategoricalDistribution(json_dict["choices"]) + elif json_dict["type"] in ("float", "int"): + low = json_dict["low"] + high = json_dict["high"] + step = json_dict.get("step") + log = json_dict.get("log", False) + + if json_dict["type"] == "float": + return FloatDistribution(low, high, log=log, step=step) + + else: + if step is None: + step = 1 + return IntDistribution(low=low, high=high, log=log, step=step) + + raise ValueError("Unknown distribution type: {}".format(json_dict["type"])) + + +def distribution_to_json(dist: BaseDistribution) -> str: + """Serialize a distribution to JSON format. + + Args: + dist: A distribution to be serialized. + + Returns: + A JSON string of a given distribution. + + """ + + return json.dumps({"name": dist.__class__.__name__, "attributes": dist._asdict()}) + + +def check_distribution_compatibility( + dist_old: BaseDistribution, dist_new: BaseDistribution +) -> None: + """A function to check compatibility of two distributions. + + It checks whether ``dist_old`` and ``dist_new`` are the same kind of distributions. + If ``dist_old`` is :class:`~optuna.distributions.CategoricalDistribution`, + it further checks ``choices`` are the same between ``dist_old`` and ``dist_new``. + Note that this method is not supposed to be called by library users. + + Args: + dist_old: + A distribution previously recorded in storage. + dist_new: + A distribution newly added to storage. + + """ + + if dist_old.__class__ != dist_new.__class__: + raise ValueError("Cannot set different distribution kind to the same parameter name.") + + if isinstance(dist_old, (FloatDistribution, IntDistribution)): + # For mypy. + assert isinstance(dist_new, (FloatDistribution, IntDistribution)) + + if dist_old.log != dist_new.log: + raise ValueError("Cannot set different log configuration to the same parameter name.") + + if not isinstance(dist_old, CategoricalDistribution): + return + if not isinstance(dist_new, CategoricalDistribution): + return + if dist_old != dist_new: + raise ValueError( + CategoricalDistribution.__name__ + " does not support dynamic value space." + ) + + +def _adjust_discrete_uniform_high(low: float, high: float, step: float) -> float: + d_high = decimal.Decimal(str(high)) + d_low = decimal.Decimal(str(low)) + d_step = decimal.Decimal(str(step)) + + d_r = d_high - d_low + + if d_r % d_step != decimal.Decimal("0"): + old_high = high + high = float((d_r // d_step) * d_step + d_low) + warnings.warn( + "The distribution is specified by [{low}, {old_high}] and step={step}, but the range " + "is not divisible by `step`. It will be replaced by [{low}, {high}].".format( + low=low, old_high=old_high, high=high, step=step + ) + ) + + return high + + +def _adjust_int_uniform_high(low: int, high: int, step: int) -> int: + r = high - low + if r % step != 0: + old_high = high + high = r // step * step + low + warnings.warn( + "The distribution is specified by [{low}, {old_high}] and step={step}, but the range " + "is not divisible by `step`. It will be replaced by [{low}, {high}].".format( + low=low, old_high=old_high, high=high, step=step + ) + ) + return high + + +def _get_single_value(distribution: BaseDistribution) -> int | float | CategoricalChoiceType: + assert distribution.single() + + if isinstance( + distribution, + ( + FloatDistribution, + IntDistribution, + ), + ): + return distribution.low + elif isinstance(distribution, CategoricalDistribution): + return distribution.choices[0] + assert False + + +# TODO(himkt): Remove this method with the deletion of deprecated distributions. +# https://github.com/optuna/optuna/issues/2941 +def _convert_old_distribution_to_new_distribution( + distribution: BaseDistribution, + suppress_warning: bool = False, +) -> BaseDistribution: + new_distribution: BaseDistribution + + # Float distributions. + if isinstance(distribution, UniformDistribution): + new_distribution = FloatDistribution( + low=distribution.low, + high=distribution.high, + log=False, + step=None, + ) + elif isinstance(distribution, LogUniformDistribution): + new_distribution = FloatDistribution( + low=distribution.low, + high=distribution.high, + log=True, + step=None, + ) + elif isinstance(distribution, DiscreteUniformDistribution): + new_distribution = FloatDistribution( + low=distribution.low, + high=distribution.high, + log=False, + step=distribution.q, + ) + + # Integer distributions. + elif isinstance(distribution, IntUniformDistribution): + new_distribution = IntDistribution( + low=distribution.low, + high=distribution.high, + log=False, + step=distribution.step, + ) + elif isinstance(distribution, IntLogUniformDistribution): + new_distribution = IntDistribution( + low=distribution.low, + high=distribution.high, + log=True, + step=distribution.step, + ) + + # Categorical distribution. + else: + new_distribution = distribution + + if new_distribution != distribution and not suppress_warning: + message = ( + f"{distribution} is deprecated and internally converted to" + f" {new_distribution}. See https://github.com/optuna/optuna/issues/2941." + ) + warnings.warn(message, FutureWarning) + + return new_distribution + + +def _is_distribution_log(distribution: BaseDistribution) -> bool: + if isinstance(distribution, (FloatDistribution, IntDistribution)): + return distribution.log + + return False diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/exceptions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..d21204157ae66f6a04987d480a72958ff861034a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/exceptions.py @@ -0,0 +1,101 @@ +class OptunaError(Exception): + """Base class for Optuna specific errors.""" + + pass + + +class TrialPruned(OptunaError): + """Exception for pruned trials. + + This error tells a trainer that the current :class:`~optuna.trial.Trial` was pruned. It is + supposed to be raised after :func:`optuna.trial.Trial.should_prune` as shown in the following + example. + + See also: + :class:`optuna.TrialPruned` is an alias of :class:`optuna.exceptions.TrialPruned`. + + Example: + + .. testcode:: + + import numpy as np + from sklearn.datasets import load_iris + from sklearn.linear_model import SGDClassifier + from sklearn.model_selection import train_test_split + + import optuna + + X, y = load_iris(return_X_y=True) + X_train, X_valid, y_train, y_valid = train_test_split(X, y) + classes = np.unique(y) + + + def objective(trial): + alpha = trial.suggest_float("alpha", 0.0, 1.0) + clf = SGDClassifier(alpha=alpha) + n_train_iter = 100 + + for step in range(n_train_iter): + clf.partial_fit(X_train, y_train, classes=classes) + + intermediate_value = clf.score(X_valid, y_valid) + trial.report(intermediate_value, step) + + if trial.should_prune(): + raise optuna.TrialPruned() + + return clf.score(X_valid, y_valid) + + + study = optuna.create_study(direction="maximize") + study.optimize(objective, n_trials=20) + """ + + pass + + +class CLIUsageError(OptunaError): + """Exception for CLI. + + CLI raises this exception when it receives invalid configuration. + """ + + pass + + +class StorageInternalError(OptunaError): + """Exception for storage operation. + + This error is raised when an operation failed in backend DB of storage. + """ + + pass + + +class DuplicatedStudyError(OptunaError): + """Exception for a duplicated study name. + + This error is raised when a specified study name already exists in the storage. + """ + + pass + + +class UpdateFinishedTrialError(OptunaError, RuntimeError): + """Exception for updating a finished trial. + + This error is raised when attempting to update a finished trial. + """ + + pass + + +class ExperimentalWarning(Warning): + """Experimental Warning class. + + This implementation exists here because the policy of `FutureWarning` has been changed + since Python 3.7 was released. See the details in + https://docs.python.org/3/library/warnings.html#warning-categories. + """ + + pass diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..29d74d848a4a731109f2d7ba7ffc2049cb9e952f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/__init__.py @@ -0,0 +1,136 @@ +import os +import sys +from types import ModuleType +from typing import Any +from typing import TYPE_CHECKING + +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +_import_structure = { + "allennlp": ["AllenNLPExecutor", "AllenNLPPruningCallback"], + "botorch": ["BoTorchSampler"], + "catboost": ["CatBoostPruningCallback"], + "chainer": ["ChainerPruningExtension"], + "chainermn": ["ChainerMNStudy"], + "cma": ["PyCmaSampler"], + "dask": ["DaskStorage"], + "mlflow": ["MLflowCallback"], + "wandb": ["WeightsAndBiasesCallback"], + "keras": ["KerasPruningCallback"], + "lightgbm": ["LightGBMPruningCallback", "LightGBMTuner", "LightGBMTunerCV"], + "pytorch_distributed": ["TorchDistributedTrial"], + "pytorch_ignite": ["PyTorchIgnitePruningHandler"], + "pytorch_lightning": ["PyTorchLightningPruningCallback"], + "sklearn": ["OptunaSearchCV"], + "shap": ["ShapleyImportanceEvaluator"], + "skorch": ["SkorchPruningCallback"], + "mxnet": ["MXNetPruningCallback"], + "tensorboard": ["TensorBoardCallback"], + "tensorflow": ["TensorFlowPruningHook"], + "tfkeras": ["TFKerasPruningCallback"], + "xgboost": ["XGBoostPruningCallback"], + "fastaiv2": ["FastAIV2PruningCallback", "FastAIPruningCallback"], +} + + +__all__ = [ + "AllenNLPExecutor", + "AllenNLPPruningCallback", + "BoTorchSampler", + "CatBoostPruningCallback", + "ChainerPruningExtension", + "ChainerMNStudy", + "PyCmaSampler", + "DaskStorage", + "MLflowCallback", + "WeightsAndBiasesCallback", + "KerasPruningCallback", + "LightGBMPruningCallback", + "LightGBMTuner", + "LightGBMTunerCV", + "TorchDistributedTrial", + "PyTorchIgnitePruningHandler", + "PyTorchLightningPruningCallback", + "OptunaSearchCV", + "ShapleyImportanceEvaluator", + "SkorchPruningCallback", + "MXNetPruningCallback", + "TensorBoardCallback", + "TensorFlowPruningHook", + "TFKerasPruningCallback", + "XGBoostPruningCallback", + "FastAIV2PruningCallback", + "FastAIPruningCallback", +] + + +if TYPE_CHECKING: + from optuna.integration.allennlp import AllenNLPExecutor + from optuna.integration.allennlp import AllenNLPPruningCallback + from optuna.integration.botorch import BoTorchSampler + from optuna.integration.catboost import CatBoostPruningCallback + from optuna.integration.chainer import ChainerPruningExtension + from optuna.integration.chainermn import ChainerMNStudy + from optuna.integration.cma import PyCmaSampler + from optuna.integration.dask import DaskStorage + from optuna.integration.fastaiv2 import FastAIPruningCallback + from optuna.integration.fastaiv2 import FastAIV2PruningCallback + from optuna.integration.keras import KerasPruningCallback + from optuna.integration.lightgbm import LightGBMPruningCallback + from optuna.integration.lightgbm import LightGBMTuner + from optuna.integration.lightgbm import LightGBMTunerCV + from optuna.integration.mlflow import MLflowCallback + from optuna.integration.mxnet import MXNetPruningCallback + from optuna.integration.pytorch_distributed import TorchDistributedTrial + from optuna.integration.pytorch_ignite import PyTorchIgnitePruningHandler + from optuna.integration.pytorch_lightning import PyTorchLightningPruningCallback + from optuna.integration.shap import ShapleyImportanceEvaluator + from optuna.integration.sklearn import OptunaSearchCV + from optuna.integration.skorch import SkorchPruningCallback + from optuna.integration.tensorboard import TensorBoardCallback + from optuna.integration.tensorflow import TensorFlowPruningHook + from optuna.integration.tfkeras import TFKerasPruningCallback + from optuna.integration.wandb import WeightsAndBiasesCallback + from optuna.integration.xgboost import XGBoostPruningCallback +else: + + class _IntegrationModule(ModuleType): + """Module class that implements `optuna.integration` package. + + This class applies lazy import under `optuna.integration`, where submodules are imported + when they are actually accessed. Otherwise, `import optuna` becomes much slower because it + imports all submodules and their dependencies (e.g., chainer, keras, lightgbm) all at once. + """ + + __all__ = __all__ + __file__ = globals()["__file__"] + __path__ = [os.path.dirname(__file__)] + + _modules = set(_import_structure.keys()) + _class_to_module = {} + for key, values in _import_structure.items(): + for value in values: + _class_to_module[value] = key + + def __getattr__(self, name: str) -> Any: + if name in self._modules: + value = self._get_module(name) + elif name in self._class_to_module.keys(): + module = self._get_module(self._class_to_module[name]) + value = getattr(module, name) + else: + raise AttributeError("module {} has no attribute {}".format(self.__name__, name)) + + setattr(self, name, value) + return value + + def _get_module(self, module_name: str) -> ModuleType: + import importlib + + try: + return importlib.import_module("." + module_name, self.__name__) + except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format(module_name)) + + sys.modules[__name__] = _IntegrationModule(__name__) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e51e94a528feb66c43fd5e2ebfff1df1c87f2d0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/allennlp/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/allennlp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ff7dee7092ce293e8e6d187663c1e6c1b9eba042 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/allennlp/__init__.py @@ -0,0 +1,12 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.allennlp._dump_best_config import dump_best_config + from optuna_integration.allennlp._executor import AllenNLPExecutor + from optuna_integration.allennlp._pruner import AllenNLPPruningCallback +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("allennlp")) + + +__all__ = ["dump_best_config", "AllenNLPExecutor", "AllenNLPPruningCallback"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/botorch.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/botorch.py new file mode 100644 index 0000000000000000000000000000000000000000..4cd4f035f8d38110bbdf96a325572eba5b5d8377 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/botorch.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration import BoTorchSampler +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("botorch")) + + +__all__ = ["BoTorchSampler"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/catboost.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/catboost.py new file mode 100644 index 0000000000000000000000000000000000000000..3d3e37a7b72a4ac27e425f46f4224f31f81cb453 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/catboost.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.catboost import CatBoostPruningCallback +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("catboost")) + + +__all__ = ["CatBoostPruningCallback"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/chainer.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/chainer.py new file mode 100644 index 0000000000000000000000000000000000000000..523363c7e59a8101630dd412c060dc3e24f9bb28 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/chainer.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.chainer import ChainerPruningExtension +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("chainer")) + + +__all__ = ["ChainerPruningExtension"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/chainermn.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/chainermn.py new file mode 100644 index 0000000000000000000000000000000000000000..42c61345b1ad4f6238b9748bb88f1a65dfbb6481 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/chainermn.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.chainermn import ChainerMNStudy +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("chainermn")) + + +__all__ = ["ChainerMNStudy"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/cma.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/cma.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a09c310e0ca2c110a9bbd0ee29ebd4e2d04509 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/cma.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.cma import PyCmaSampler +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("cma")) + + +__all__ = ["PyCmaSampler"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/dask.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/dask.py new file mode 100644 index 0000000000000000000000000000000000000000..d017547fe431a46aae8b1885ae4c90b04c5c0ff2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/dask.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.dask import DaskStorage +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("dask")) + + +__all__ = ["DaskStorage"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/fastaiv2.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/fastaiv2.py new file mode 100644 index 0000000000000000000000000000000000000000..2142db65242bca77a6be6ae0348ffc9d641dfc88 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/fastaiv2.py @@ -0,0 +1,11 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.fastaiv2 import FastAIPruningCallback + from optuna_integration.fastaiv2 import FastAIV2PruningCallback +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("fastaiv2")) + + +__all__ = ["FastAIV2PruningCallback", "FastAIPruningCallback"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/keras.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/keras.py new file mode 100644 index 0000000000000000000000000000000000000000..e6e93e9dad5284467ca074784693321ec07df0e9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/keras.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.keras import KerasPruningCallback +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("keras")) + + +__all__ = ["KerasPruningCallback"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/lightgbm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/lightgbm.py new file mode 100644 index 0000000000000000000000000000000000000000..7b2ed0764b9a078fc9c73940de403b0b66b8d3c2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/lightgbm.py @@ -0,0 +1,43 @@ +import os +import sys +from types import ModuleType +from typing import Any +from typing import TYPE_CHECKING + +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + import optuna_integration.lightgbm as lgb +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("lightgbm")) + + +if TYPE_CHECKING: + # These modules are from optuna-integration. + from optuna.integration.lightgbm_tuner import LightGBMPruningCallback + from optuna.integration.lightgbm_tuner import LightGBMTuner + from optuna.integration.lightgbm_tuner import LightGBMTunerCV + from optuna.integration.lightgbm_tuner import train + + +__all__ = [ + "LightGBMPruningCallback", + "LightGBMTuner", + "LightGBMTunerCV", + "train", +] + + +class _LightGBMModule(ModuleType): + """Module class that implements `optuna.integration.lightgbm` package.""" + + __all__ = __all__ + __file__ = globals()["__file__"] + __path__ = [os.path.dirname(__file__)] + + def __getattr__(self, name: str) -> Any: + return lgb.__dict__[name] + + +sys.modules[__name__] = _LightGBMModule(__name__) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/mlflow.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/mlflow.py new file mode 100644 index 0000000000000000000000000000000000000000..67b9505b6b286dfffbf189359867c30d03d50fcc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/mlflow.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.mlflow import MLflowCallback +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("mlflow")) + + +__all__ = ["MLflowCallback"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/mxnet.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/mxnet.py new file mode 100644 index 0000000000000000000000000000000000000000..14aa51aec782a4867d9496f320ac78c4ddba4a60 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/mxnet.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.mxnet import MXNetPruningCallback +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("mxnet")) + + +__all__ = ["MXNetPruningCallback"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/pytorch_distributed.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/pytorch_distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..1325a3250b719abd6eb1dc1d24c674d05926d257 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/pytorch_distributed.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.pytorch_distributed import TorchDistributedTrial +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("pytorch_distributed")) + + +__all__ = ["TorchDistributedTrial"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/pytorch_ignite.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/pytorch_ignite.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf38027b532f524fab2a5eab5413ebb54645f16 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/pytorch_ignite.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.pytorch_ignite import PyTorchIgnitePruningHandler +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("pytorch_ignite")) + + +__all__ = ["PyTorchIgnitePruningHandler"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/pytorch_lightning.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/pytorch_lightning.py new file mode 100644 index 0000000000000000000000000000000000000000..470146be9657b6de5da8b27afd1a2e97aad82f3c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/pytorch_lightning.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.pytorch_lightning import PyTorchLightningPruningCallback +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("pytorch_lightning")) + + +__all__ = ["PyTorchLightningPruningCallback"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/shap.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/shap.py new file mode 100644 index 0000000000000000000000000000000000000000..c9882233b50d875d769e81e873f4a1e7a0e7b80b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/shap.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.shap import ShapleyImportanceEvaluator +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("shap")) + + +__all__ = ["ShapleyImportanceEvaluator"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/sklearn.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/sklearn.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f30433b39334b5bb009871db89ced057581cc8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/sklearn.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.sklearn import OptunaSearchCV +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("sklearn")) + + +__all__ = ["OptunaSearchCV"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/skorch.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/skorch.py new file mode 100644 index 0000000000000000000000000000000000000000..f147960401247caf7d891284f9efea7635817f41 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/skorch.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.skorch import SkorchPruningCallback +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("skorch")) + + +__all__ = ["SkorchPruningCallback"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/tensorboard.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/tensorboard.py new file mode 100644 index 0000000000000000000000000000000000000000..ad360d48861660917fd2b04516b631767c9ba822 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/tensorboard.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.tensorboard import TensorBoardCallback +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("tensorboard")) + + +__all__ = ["TensorBoardCallback"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/tensorflow.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/tensorflow.py new file mode 100644 index 0000000000000000000000000000000000000000..4e04699b38b1dbd98b240818213c49f039d98f37 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/tensorflow.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.tensorflow import TensorFlowPruningHook +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("tensorflow")) + + +__all__ = ["TensorFlowPruningHook"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/tfkeras.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/tfkeras.py new file mode 100644 index 0000000000000000000000000000000000000000..622b5a599f3c57428e538dcd379c7f4f00cfadb4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/tfkeras.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.tfkeras import TFKerasPruningCallback +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("tfkeras")) + + +__all__ = ["TFKerasPruningCallback"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/wandb.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/wandb.py new file mode 100644 index 0000000000000000000000000000000000000000..19863e5da8eb3897b6e1c9004aa0571e5068c3a2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/wandb.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.wandb import WeightsAndBiasesCallback +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("wandb")) + + +__all__ = ["WeightsAndBiasesCallback"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/xgboost.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/xgboost.py new file mode 100644 index 0000000000000000000000000000000000000000..acd9b4a2fc0554cbcf760ea21473b9bb2943434c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/integration/xgboost.py @@ -0,0 +1,10 @@ +from optuna._imports import _INTEGRATION_IMPORT_ERROR_TEMPLATE + + +try: + from optuna_integration.xgboost import XGBoostPruningCallback +except ModuleNotFoundError: + raise ModuleNotFoundError(_INTEGRATION_IMPORT_ERROR_TEMPLATE.format("xgboost")) + + +__all__ = ["XGBoostPruningCallback"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/logging.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..b5a07d67e34212414b7c8f87ed8e140fb2524576 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/logging.py @@ -0,0 +1,357 @@ +from __future__ import annotations + +import logging +from logging import CRITICAL +from logging import DEBUG +from logging import ERROR +from logging import FATAL +from logging import INFO +from logging import WARN +from logging import WARNING +import os +import sys +import threading + +import colorlog + + +__all__ = [ + "CRITICAL", + "DEBUG", + "ERROR", + "FATAL", + "INFO", + "WARN", + "WARNING", +] + +_lock: threading.Lock = threading.Lock() +_default_handler: logging.Handler | None = None + + +def create_default_formatter() -> logging.Formatter: + """Create a default formatter of log messages. + + This function is not supposed to be directly accessed by library users. + """ + header = "[%(levelname)1.1s %(asctime)s]" + message = "%(message)s" + if _color_supported(): + return colorlog.ColoredFormatter( + f"%(log_color)s{header}%(reset)s {message}", + ) + return logging.Formatter(f"{header} {message}") + + +def _color_supported() -> bool: + """Detection of color support.""" + # NO_COLOR environment variable: + if os.environ.get("NO_COLOR", None): + return False + + if not hasattr(sys.stderr, "isatty") or not sys.stderr.isatty(): + return False + else: + return True + + +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. + _default_handler.setFormatter(create_default_formatter()) + + # Apply our default configuration to the library root logger. + library_root_logger: logging.Logger = _get_library_root_logger() + library_root_logger.addHandler(_default_handler) + library_root_logger.setLevel(logging.INFO) + library_root_logger.propagate = False + + +def _reset_library_root_logger() -> None: + global _default_handler + + with _lock: + if not _default_handler: + return + + library_root_logger: logging.Logger = _get_library_root_logger() + library_root_logger.removeHandler(_default_handler) + library_root_logger.setLevel(logging.NOTSET) + _default_handler = None + + +def get_logger(name: str) -> logging.Logger: + """Return a logger with the specified name. + + This function is not supposed to be directly accessed by library users. + """ + + _configure_library_root_logger() + return logging.getLogger(name) + + +def get_verbosity() -> int: + """Return the current level for the Optuna's root logger. + + Example: + + Get the default verbosity level. + + .. testsetup:: + + def objective(trial): + x = trial.suggest_float("x", -100, 100) + y = trial.suggest_categorical("y", [-1, 0, 1]) + return x**2 + y + + .. testcode:: + + import optuna + + # The default verbosity level of Optuna is `optuna.logging.INFO`. + print(optuna.logging.get_verbosity()) + # 20 + print(optuna.logging.INFO) + # 20 + + # There are logs of the INFO level. + study = optuna.create_study() + study.optimize(objective, n_trials=5) + # [I 2021-10-31 05:35:17,232] A new study created ... + # [I 2021-10-31 05:35:17,238] Trial 0 finished with value: ... + # [I 2021-10-31 05:35:17,245] Trial 1 finished with value: ... + # ... + + .. testoutput:: + :hide: + + 20 + 20 + Returns: + Logging level, e.g., ``optuna.logging.DEBUG`` and ``optuna.logging.INFO``. + + .. note:: + Optuna has following logging levels: + + - ``optuna.logging.CRITICAL``, ``optuna.logging.FATAL`` + - ``optuna.logging.ERROR`` + - ``optuna.logging.WARNING``, ``optuna.logging.WARN`` + - ``optuna.logging.INFO`` + - ``optuna.logging.DEBUG`` + """ + + _configure_library_root_logger() + return _get_library_root_logger().getEffectiveLevel() + + +def set_verbosity(verbosity: int) -> None: + """Set the level for the Optuna's root logger. + + Example: + + Set the logging level ``optuna.logging.WARNING``. + + .. testsetup:: + + def objective(trial): + x = trial.suggest_int("x", -10, 10) + return x**2 + + .. testcode:: + + import optuna + + # There are INFO level logs. + study = optuna.create_study() + study.optimize(objective, n_trials=10) + # [I 2021-10-31 02:59:35,088] Trial 0 finished with value: 16.0 ... + # [I 2021-10-31 02:59:35,091] Trial 1 finished with value: 1.0 ... + # [I 2021-10-31 02:59:35,096] Trial 2 finished with value: 1.0 ... + + # Setting the logging level WARNING, the INFO logs are suppressed. + optuna.logging.set_verbosity(optuna.logging.WARNING) + study.optimize(objective, n_trials=10) + + .. testcleanup:: + + optuna.logging.set_verbosity(optuna.logging.INFO) + + + Args: + verbosity: + Logging level, e.g., ``optuna.logging.DEBUG`` and ``optuna.logging.INFO``. + + .. note:: + Optuna has following logging levels: + + - ``optuna.logging.CRITICAL``, ``optuna.logging.FATAL`` + - ``optuna.logging.ERROR`` + - ``optuna.logging.WARNING``, ``optuna.logging.WARN`` + - ``optuna.logging.INFO`` + - ``optuna.logging.DEBUG`` + """ + + _configure_library_root_logger() + _get_library_root_logger().setLevel(verbosity) + + +def disable_default_handler() -> None: + """Disable the default handler of the Optuna's root logger. + + Example: + + Stop and then resume logging to :obj:`sys.stderr`. + + .. testsetup:: + + def objective(trial): + x = trial.suggest_float("x", -100, 100) + y = trial.suggest_categorical("y", [-1, 0, 1]) + return x**2 + y + + .. testcode:: + + import optuna + + study = optuna.create_study() + + # There are no logs in sys.stderr. + optuna.logging.disable_default_handler() + study.optimize(objective, n_trials=10) + + # There are logs in sys.stderr. + optuna.logging.enable_default_handler() + study.optimize(objective, n_trials=10) + # [I 2020-02-23 17:00:54,314] Trial 10 finished with value: ... + # [I 2020-02-23 17:00:54,356] Trial 11 finished with value: ... + # ... + + """ + + _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 Optuna's root logger. + + Please refer to the example shown in :func:`~optuna.logging.disable_default_handler()`. + """ + + _configure_library_root_logger() + + assert _default_handler is not None + _get_library_root_logger().addHandler(_default_handler) + + +def disable_propagation() -> None: + """Disable propagation of the library log outputs. + + Note that log propagation is disabled by default. You only need to use this function + to stop log propagation when you use :func:`~optuna.logging.enable_propagation()`. + + Example: + + Stop propagating logs to the root logger on the second optimize call. + + .. testsetup:: + + def objective(trial): + x = trial.suggest_float("x", -100, 100) + y = trial.suggest_categorical("y", [-1, 0, 1]) + return x**2 + y + + .. testcode:: + + import optuna + import logging + + optuna.logging.disable_default_handler() # Disable the default handler. + logger = logging.getLogger() + + logger.setLevel(logging.INFO) # Setup the root logger. + logger.addHandler(logging.FileHandler("foo.log", mode="w")) + + optuna.logging.enable_propagation() # Propagate logs to the root logger. + + study = optuna.create_study() + + logger.info("Logs from first optimize call") # The logs are saved in the logs file. + study.optimize(objective, n_trials=10) + + optuna.logging.disable_propagation() # Stop propogating logs to the root logger. + + logger.info("Logs from second optimize call") + # The new logs for second optimize call are not saved. + study.optimize(objective, n_trials=10) + + with open("foo.log") as f: + assert f.readline().startswith("A new study created") + assert f.readline() == "Logs from first optimize call\\n" + # Check for logs after second optimize call. + assert f.read().split("Logs from second optimize call\\n")[-1] == "" + + """ + + _configure_library_root_logger() + _get_library_root_logger().propagate = False + + +def enable_propagation() -> None: + """Enable propagation of the library log outputs. + + Please disable the Optuna's default handler to prevent double logging if the root logger has + been configured. + + Example: + + Propagate all log output to the root logger in order to save them to the file. + + .. testsetup:: + + def objective(trial): + x = trial.suggest_float("x", -100, 100) + y = trial.suggest_categorical("y", [-1, 0, 1]) + return x**2 + y + + .. testcode:: + + import optuna + import logging + + logger = logging.getLogger() + + logger.setLevel(logging.INFO) # Setup the root logger. + logger.addHandler(logging.FileHandler("foo.log", mode="w")) + + optuna.logging.enable_propagation() # Propagate logs to the root logger. + optuna.logging.disable_default_handler() # Stop showing logs in sys.stderr. + + study = optuna.create_study() + + logger.info("Start optimization.") + study.optimize(objective, n_trials=10) + + with open("foo.log") as f: + assert f.readline().startswith("A new study created") + assert f.readline() == "Start optimization.\\n" + + """ + + _configure_library_root_logger() + _get_library_root_logger().propagate = True diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/progress_bar.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/progress_bar.py new file mode 100644 index 0000000000000000000000000000000000000000..63e0e5b8147e6e5e24a854bbdd41ae2bf30053a6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/progress_bar.py @@ -0,0 +1,125 @@ +from __future__ import annotations + +import logging +from typing import Any +from typing import TYPE_CHECKING +import warnings + +from tqdm.auto import tqdm + +from optuna import logging as optuna_logging + + +if TYPE_CHECKING: + from optuna.study import Study + +_tqdm_handler: _TqdmLoggingHandler | None = None + + +# Reference: https://gist.github.com/hvy/8b80c2cedf02b15c24f85d1fa17ebe02 +class _TqdmLoggingHandler(logging.StreamHandler): + def emit(self, record: Any) -> None: + try: + msg = self.format(record) + tqdm.write(msg) + self.flush() + except (KeyboardInterrupt, SystemExit): + raise + except Exception: + self.handleError(record) + + +class _ProgressBar: + """Progress Bar implementation for :func:`~optuna.study.Study.optimize` on the top of `tqdm`. + + Args: + is_valid: + Whether to show progress bars in :func:`~optuna.study.Study.optimize`. + n_trials: + The number of trials. + timeout: + Stop study after the given number of second(s). + """ + + def __init__( + self, + is_valid: bool, + n_trials: int | None = None, + timeout: float | None = None, + ) -> None: + if is_valid and n_trials is None and timeout is None: + warnings.warn("Progress bar won't be displayed because n_trials and timeout are None.") + + self._is_valid = is_valid and (n_trials or timeout) is not None + self._n_trials = n_trials + self._timeout = timeout + self._last_elapsed_seconds = 0.0 + + if self._is_valid: + if self._n_trials is not None: + self._progress_bar = tqdm(total=self._n_trials) + elif self._timeout is not None: + total = tqdm.format_interval(self._timeout) + fmt = "{desc} {percentage:3.0f}%|{bar}| {elapsed}/" + total + self._progress_bar = tqdm(total=self._timeout, bar_format=fmt) + else: + assert False + + global _tqdm_handler + + _tqdm_handler = _TqdmLoggingHandler() + _tqdm_handler.setLevel(logging.INFO) + _tqdm_handler.setFormatter(optuna_logging.create_default_formatter()) + optuna_logging.disable_default_handler() + optuna_logging._get_library_root_logger().addHandler(_tqdm_handler) + + def update(self, elapsed_seconds: float, study: Study) -> None: + """Update the progress bars if ``is_valid`` is :obj:`True`. + + Args: + elapsed_seconds: + The time past since :func:`~optuna.study.Study.optimize` started. + study: + The current study object. + """ + + if self._is_valid: + if not study._is_multi_objective(): + # Not updating the progress bar when there are no complete trial. + try: + msg = ( + f"Best trial: {study.best_trial.number}. " + f"Best value: {study.best_value:.6g}" + ) + + self._progress_bar.set_description(msg) + except ValueError: + pass + + if self._n_trials is not None: + self._progress_bar.update(1) + if self._timeout is not None: + self._progress_bar.set_postfix_str( + "{:.02f}/{} seconds".format(elapsed_seconds, self._timeout) + ) + + elif self._timeout is not None: + time_diff = elapsed_seconds - self._last_elapsed_seconds + if elapsed_seconds > self._timeout: + # Clip elapsed time to avoid tqdm warnings. + time_diff -= elapsed_seconds - self._timeout + + self._progress_bar.update(time_diff) + self._last_elapsed_seconds = elapsed_seconds + + else: + assert False + + def close(self) -> None: + """Close progress bars.""" + + if self._is_valid: + self._progress_bar.close() + assert _tqdm_handler is not None + optuna_logging._get_library_root_logger().removeHandler(_tqdm_handler) + optuna_logging.enable_default_handler() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/py.typed b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7b63b844d0c23b639ca0c87e46e86e6e83a8c1ff --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__init__.py @@ -0,0 +1,24 @@ +from optuna._callbacks import MaxTrialsCallback +from optuna.study._study_direction import StudyDirection +from optuna.study._study_summary import StudySummary +from optuna.study.study import copy_study +from optuna.study.study import create_study +from optuna.study.study import delete_study +from optuna.study.study import get_all_study_names +from optuna.study.study import get_all_study_summaries +from optuna.study.study import load_study +from optuna.study.study import Study + + +__all__ = [ + "MaxTrialsCallback", + "StudyDirection", + "StudySummary", + "copy_study", + "create_study", + "delete_study", + "get_all_study_names", + "get_all_study_summaries", + "load_study", + "Study", +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7ac5ee2b49baf6f78837b8375e17609f538b518 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_constrained_optimization.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_constrained_optimization.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..952ed6fc794197d64cf72d570e1dfcea702f77a2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_constrained_optimization.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_dataframe.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_dataframe.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24cbec078899902680a9aca548497e6f75d83890 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_dataframe.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_frozen.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_frozen.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5565900d7f7defd931d3738d97bbb1df914ff8a3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_frozen.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_multi_objective.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_multi_objective.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e08bb7de4060eddbbbbf6262e137ddaf6e3707f7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_multi_objective.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_optimize.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_optimize.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c25eda5b5b97056131d682667f56328eae0a23ce Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_optimize.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_study_direction.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_study_direction.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..651704388c8c4da412a1432091455e2d99b96d61 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_study_direction.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_study_summary.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_study_summary.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c657a193411af7a4d1a49f2e9f2d8d6776bc1bb4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_study_summary.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_tell.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_tell.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b3762dfdad7a0363183223e74d5fb9d09509bf2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/_tell.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/study.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/study.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a75372f1a178a2be4acfcd3544483bf75703b5e4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/__pycache__/study.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_constrained_optimization.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_constrained_optimization.py new file mode 100644 index 0000000000000000000000000000000000000000..d289e13f55bb2b4459a082670a90211db18a3590 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_constrained_optimization.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +from collections.abc import Sequence + +from optuna.trial import FrozenTrial + + +_CONSTRAINTS_KEY = "constraints" + + +def _get_feasible_trials(trials: Sequence[FrozenTrial]) -> list[FrozenTrial]: + """Return feasible trials from given trials. + + This function assumes that the trials were created in constrained optimization. + Therefore, if there is no violation value in the trial, it is considered infeasible. + + + Returns: + A list of feasible trials. + """ + + feasible_trials = [] + for trial in trials: + constraints = trial.system_attrs.get(_CONSTRAINTS_KEY) + if constraints is not None and all(x <= 0.0 for x in constraints): + feasible_trials.append(trial) + return feasible_trials diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_dataframe.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_dataframe.py new file mode 100644 index 0000000000000000000000000000000000000000..e9f51858f9a0e0db96580af9f688417918314b7a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_dataframe.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +import collections +from typing import Any + +import optuna +from optuna._imports import try_import +from optuna.trial._state import TrialState + + +with try_import() as _imports: + # `Study.trials_dataframe` is disabled if pandas is not available. + import pandas as pd + +# Required for type annotation in `Study.trials_dataframe`. +if not _imports.is_successful(): + pd = object # NOQA + +__all__ = ["pd"] + + +def _create_records_and_aggregate_column( + study: "optuna.Study", attrs: tuple[str, ...] +) -> tuple[list[dict[tuple[str, str], Any]], list[tuple[str, str]]]: + attrs_to_df_columns: dict[str, str] = {} + for attr in attrs: + if attr.startswith("_"): + # Python conventional underscores are omitted in the dataframe. + df_column = attr[1:] + else: + df_column = attr + attrs_to_df_columns[attr] = df_column + + # column_agg is an aggregator of column names. + # Keys of column agg are attributes of `FrozenTrial` such as 'trial_id' and 'params'. + # Values are dataframe columns such as ('trial_id', '') and ('params', 'n_layers'). + column_agg: collections.defaultdict[str, set] = collections.defaultdict(set) + non_nested_attr = "" + + metric_names = study.metric_names + + records = [] + for trial in study.get_trials(deepcopy=False): + record = {} + for attr, df_column in attrs_to_df_columns.items(): + value = getattr(trial, attr) + if isinstance(value, TrialState): + value = value.name + if isinstance(value, dict): + for nested_attr, nested_value in value.items(): + record[(df_column, nested_attr)] = nested_value + column_agg[attr].add((df_column, nested_attr)) + elif attr == "values": + # Expand trial.values. + # trial.values should be None when the trial's state is FAIL or PRUNED. + trial_values = [None] * len(study.directions) if value is None else value + iterator = ( + enumerate(trial_values) + if metric_names is None + else zip(metric_names, trial_values) + ) + for nested_attr, nested_value in iterator: + record[(df_column, nested_attr)] = nested_value + column_agg[attr].add((df_column, nested_attr)) + elif isinstance(value, list): + for nested_attr, nested_value in enumerate(value): + record[(df_column, nested_attr)] = nested_value + column_agg[attr].add((df_column, nested_attr)) + elif attr == "value": + nested_attr = non_nested_attr if metric_names is None else metric_names[0] + record[(df_column, nested_attr)] = value + column_agg[attr].add((df_column, nested_attr)) + else: + record[(df_column, non_nested_attr)] = value + column_agg[attr].add((df_column, non_nested_attr)) + + records.append(record) + + columns: list[tuple[str, str]] = sum( + (sorted(column_agg[k]) for k in attrs if k in column_agg), [] + ) + + return records, columns + + +def _flatten_columns(columns: list[tuple[str, str]]) -> list[str]: + # Flatten the `MultiIndex` columns where names are concatenated with underscores. + # Filtering is required to omit non-nested columns avoiding unwanted trailing underscores. + return ["_".join(filter(lambda c: c, map(lambda c: str(c), col))) for col in columns] + + +def _trials_dataframe( + study: "optuna.Study", attrs: tuple[str, ...], multi_index: bool +) -> "pd.DataFrame": + _imports.check() + + # If no trials, return an empty dataframe. + if len(study.get_trials(deepcopy=False)) == 0: + return pd.DataFrame() + + if "value" in attrs and study._is_multi_objective(): + attrs = tuple("values" if attr == "value" else attr for attr in attrs) + + records, columns = _create_records_and_aggregate_column(study, attrs) + + df = pd.DataFrame(records, columns=pd.MultiIndex.from_tuples(columns)) + + if not multi_index: + df.columns = _flatten_columns(columns) + + return df diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_frozen.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_frozen.py new file mode 100644 index 0000000000000000000000000000000000000000..d74c4529f6d58043b425ba8bdb8f88c49b908626 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_frozen.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +from optuna import logging +from optuna.study._study_direction import StudyDirection + + +_logger = logging.get_logger(__name__) + + +class FrozenStudy: + """Basic attributes of a :class:`~optuna.study.Study`. + + This class is private and not referenced by Optuna users. + + Attributes: + study_name: + Name of the :class:`~optuna.study.Study`. + direction: + :class:`~optuna.study.StudyDirection` of the :class:`~optuna.study.Study`. + + .. note:: + This attribute is only available during single-objective optimization. + directions: + A list of :class:`~optuna.study.StudyDirection` objects. + user_attrs: + Dictionary that contains the attributes of the :class:`~optuna.study.Study` set with + :func:`optuna.study.Study.set_user_attr`. + system_attrs: + Dictionary that contains the attributes of the :class:`~optuna.study.Study` internally + set by Optuna. + + """ + + def __init__( + self, + study_name: str, + direction: StudyDirection | None, + user_attrs: dict[str, Any], + system_attrs: dict[str, Any], + study_id: int, + *, + directions: Sequence[StudyDirection] | None = None, + ): + self.study_name = study_name + if direction is None and directions is None: + raise ValueError("Specify one of `direction` and `directions`.") + elif directions is not None: + self._directions = list(directions) + elif direction is not None: + self._directions = [direction] + else: + raise ValueError("Specify only one of `direction` and `directions`.") + self.user_attrs = user_attrs + self.system_attrs = system_attrs + self._study_id = study_id + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, FrozenStudy): + return NotImplemented + + return other.__dict__ == self.__dict__ + + def __lt__(self, other: Any) -> bool: + if not isinstance(other, FrozenStudy): + return NotImplemented + + return self._study_id < other._study_id + + def __le__(self, other: Any) -> bool: + if not isinstance(other, FrozenStudy): + return NotImplemented + + return self._study_id <= other._study_id + + @property + def direction(self) -> StudyDirection: + if len(self._directions) > 1: + raise RuntimeError( + "This attribute is not available during multi-objective optimization." + ) + + return self._directions[0] + + @property + def directions(self) -> list[StudyDirection]: + return self._directions diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_multi_objective.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_multi_objective.py new file mode 100644 index 0000000000000000000000000000000000000000..7a3c03738cdffde6caecc294be86338ba30c0819 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_multi_objective.py @@ -0,0 +1,258 @@ +from __future__ import annotations + +from collections.abc import Sequence + +import numpy as np + +import optuna +from optuna.study._constrained_optimization import _get_feasible_trials +from optuna.study._study_direction import StudyDirection +from optuna.trial import FrozenTrial +from optuna.trial import TrialState + + +def _get_pareto_front_trials_by_trials( + trials: Sequence[FrozenTrial], + directions: Sequence[StudyDirection], + consider_constraint: bool = False, +) -> list[FrozenTrial]: + # NOTE(nabenabe0928): Vectorization relies on all the trials being complete. + trials = [t for t in trials if t.state == TrialState.COMPLETE] + if consider_constraint: + trials = _get_feasible_trials(trials) + if len(trials) == 0: + return [] + + if any(len(t.values) != len(directions) for t in trials): + raise ValueError( + "The number of the values and the number of the objectives must be identical." + ) + + loss_values = np.asarray( + [[_normalize_value(v, d) for v, d in zip(t.values, directions)] for t in trials] + ) + on_front = _is_pareto_front(loss_values, assume_unique_lexsorted=False) + return [t for t, is_pareto in zip(trials, on_front) if is_pareto] + + +def _get_pareto_front_trials( + study: "optuna.study.Study", consider_constraint: bool = False +) -> list[FrozenTrial]: + return _get_pareto_front_trials_by_trials(study.trials, study.directions, consider_constraint) + + +def _fast_non_domination_rank( + loss_values: np.ndarray, *, penalty: np.ndarray | None = None, n_below: int | None = None +) -> np.ndarray: + """Calculate non-domination rank based on the fast non-dominated sort algorithm. + + The fast non-dominated sort algorithm assigns a rank to each trial based on the dominance + relationship of the trials, determined by the objective values and the penalty values. The + algorithm is based on `the constrained NSGA-II algorithm + `__, but the handling of the case when penalty + values are None is different. The algorithm assigns the rank according to the following + rules: + + 1. Feasible trials: First, the algorithm assigns the rank to feasible trials, whose penalty + values are less than or equal to 0, according to unconstrained version of fast non- + dominated sort. + 2. Infeasible trials: Next, the algorithm assigns the rank from the minimum penalty value of to + the maximum penalty value. + 3. Trials with no penalty information (constraints value is None): Finally, The algorithm + assigns the rank to trials with no penalty information according to unconstrained version + of fast non-dominated sort. Note that only this step is different from the original + constrained NSGA-II algorithm. + Plus, the algorithm terminates whenever the number of sorted trials reaches n_below. + + Args: + loss_values: + Objective values, which is better when it is lower, of each trials. + penalty: + Constraints values of each trials. Defaults to None. + n_below: The minimum number of top trials required to be sorted. The algorithm will + terminate when the number of sorted trials reaches n_below. Defaults to None. + + Returns: + An ndarray in the shape of (n_trials,), where each element is the non-domination rank of + each trial. The rank is 0-indexed. This function guarantees the correctness of the ranks + only up to the top-``n_below`` solutions. If a solution's rank is worse than the + top-``n_below`` solution, its rank will be guaranteed to be greater than the rank of + the top-``n_below`` solution. + """ + if len(loss_values) == 0: + return np.array([], dtype=int) + + n_below = n_below or len(loss_values) + assert n_below > 0, "n_below must be a positive integer." + + if penalty is None: + return _calculate_nondomination_rank(loss_values, n_below=n_below) + + if len(penalty) != len(loss_values): + raise ValueError( + "The length of penalty and loss_values must be same, but got " + f"len(penalty)={len(penalty)} and len(loss_values)={len(loss_values)}." + ) + + ranks = np.full(len(loss_values), -1, dtype=int) + is_penalty_nan = np.isnan(penalty) + is_feasible = np.logical_and(~is_penalty_nan, penalty <= 0) + is_infeasible = np.logical_and(~is_penalty_nan, penalty > 0) + + # First, we calculate the domination rank for feasible trials. + ranks[is_feasible] = _calculate_nondomination_rank(loss_values[is_feasible], n_below=n_below) + n_below -= int(np.count_nonzero(is_feasible)) + + # Second, we calculate the domination rank for infeasible trials. + top_rank_infeasible = np.max(ranks[is_feasible], initial=-1) + 1 + ranks[is_infeasible] = top_rank_infeasible + _calculate_nondomination_rank( + penalty[is_infeasible][:, np.newaxis], n_below=n_below + ) + n_below -= int(np.count_nonzero(is_infeasible)) + + # Third, we calculate the domination rank for trials with no penalty information. + top_rank_penalty_nan = np.max(ranks[~is_penalty_nan], initial=-1) + 1 + ranks[is_penalty_nan] = top_rank_penalty_nan + _calculate_nondomination_rank( + loss_values[is_penalty_nan], n_below=n_below + ) + assert np.all(ranks != -1), "All the rank must be updated." + return ranks + + +def _is_pareto_front_nd(unique_lexsorted_loss_values: np.ndarray) -> np.ndarray: + # NOTE(nabenabe0928): I tried the Kung's algorithm below, but it was not really quick. + # https://github.com/optuna/optuna/pull/5302#issuecomment-1988665532 + # As unique_lexsorted_loss_values[:, 0] is sorted, we do not need it to judge dominance. + loss_values = unique_lexsorted_loss_values[:, 1:] + n_trials = loss_values.shape[0] + on_front = np.zeros(n_trials, dtype=bool) + # TODO(nabenabe): Replace with the following once Python 3.8 is dropped. + # remaining_indices: np.ndarray[tuple[int], np.dtype[np.signedinteger]] = ... + remaining_indices: np.ndarray[tuple[int, ...], np.dtype[np.signedinteger]] = np.arange( + n_trials + ) + while len(remaining_indices): + # NOTE: trials[j] cannot dominate trials[i] for i < j because of lexsort. + # Therefore, remaining_indices[0] is always non-dominated. + on_front[(new_nondominated_index := remaining_indices[0])] = True + nondominated_and_not_top = np.any( + loss_values[remaining_indices] < loss_values[new_nondominated_index], axis=1 + ) + # TODO(nabenabe): Replace with the following once Python 3.8 is dropped. + # ... = cast(np.ndarray[tuple[int], np.dtype[np.signedinteger]], ...) + remaining_indices = remaining_indices[nondominated_and_not_top] + + return on_front + + +def _is_pareto_front_2d(unique_lexsorted_loss_values: np.ndarray) -> np.ndarray: + n_trials = unique_lexsorted_loss_values.shape[0] + cummin_value1 = np.minimum.accumulate(unique_lexsorted_loss_values[:, 1]) + on_front = np.ones(n_trials, dtype=bool) + on_front[1:] = cummin_value1[1:] < cummin_value1[:-1] # True if cummin value1 is new minimum. + return on_front + + +def _is_pareto_front_for_unique_sorted(unique_lexsorted_loss_values: np.ndarray) -> np.ndarray: + (n_trials, n_objectives) = unique_lexsorted_loss_values.shape + if n_objectives == 1: + on_front = np.zeros(len(unique_lexsorted_loss_values), dtype=bool) + on_front[0] = True # Only the first element is Pareto optimal. + return on_front + elif n_objectives == 2: + return _is_pareto_front_2d(unique_lexsorted_loss_values) + else: + return _is_pareto_front_nd(unique_lexsorted_loss_values) + + +def _is_pareto_front(loss_values: np.ndarray, assume_unique_lexsorted: bool) -> np.ndarray: + # NOTE(nabenabe): If assume_unique_lexsorted=True, but loss_values is not a unique array, + # Duplicated Pareto solutions will be filtered out except for the earliest occurrences. + # If assume_unique_lexsorted=True and loss_values[:, 0] is not sorted, then the result will be + # incorrect. + if assume_unique_lexsorted: + return _is_pareto_front_for_unique_sorted(loss_values) + + unique_lexsorted_loss_values, order_inv = np.unique(loss_values, axis=0, return_inverse=True) + on_front = _is_pareto_front_for_unique_sorted(unique_lexsorted_loss_values) + # NOTE(nabenabe): We can remove `.reshape(-1)` if ``numpy==2.0.0`` is not used. + # https://github.com/numpy/numpy/issues/26738 + # TODO: Remove `.reshape(-1)` once `numpy==2.0.0` is obsolete. + return on_front[order_inv.reshape(-1)] + + +def _calculate_nondomination_rank( + loss_values: np.ndarray, *, n_below: int | None = None +) -> np.ndarray: + if len(loss_values) == 0 or (n_below is not None and n_below <= 0): + return np.zeros(len(loss_values), dtype=int) + + (n_trials, n_objectives) = loss_values.shape + if n_objectives == 1: + _, ranks = np.unique(loss_values[:, 0], return_inverse=True) + return ranks + + # It ensures that trials[j] will not dominate trials[i] for i < j. + # np.unique does lexsort. + unique_lexsorted_loss_values, order_inv = np.unique(loss_values, return_inverse=True, axis=0) + n_unique = unique_lexsorted_loss_values.shape[0] + # Clip n_below. + n_below = min(n_below or len(unique_lexsorted_loss_values), len(unique_lexsorted_loss_values)) + ranks = np.zeros(n_unique, dtype=int) + rank = 0 + indices = np.arange(n_unique) + while n_unique - indices.size < n_below: + on_front = _is_pareto_front(unique_lexsorted_loss_values, assume_unique_lexsorted=True) + ranks[indices[on_front]] = rank + # Remove the recent Pareto solutions. + indices = indices[~on_front] + unique_lexsorted_loss_values = unique_lexsorted_loss_values[~on_front] + rank += 1 + + ranks[indices] = rank # Rank worse than the top n_below is defined as the worst rank. + # NOTE(nabenabe): We can remove `.reshape(-1)` if ``numpy==2.0.0`` is not used. + # https://github.com/numpy/numpy/issues/26738 + # TODO: Remove `.reshape(-1)` once `numpy==2.0.0` is obsolete. + return ranks[order_inv.reshape(-1)] + + +def _dominates( + trial0: FrozenTrial, trial1: FrozenTrial, directions: Sequence[StudyDirection] +) -> bool: + values0 = trial0.values + values1 = trial1.values + + if trial0.state != TrialState.COMPLETE: + return False + + if trial1.state != TrialState.COMPLETE: + return True + + assert values0 is not None + assert values1 is not None + + if len(values0) != len(values1): + raise ValueError("Trials with different numbers of objectives cannot be compared.") + + if len(values0) != len(directions): + raise ValueError( + "The number of the values and the number of the objectives are mismatched." + ) + + normalized_values0 = [_normalize_value(v, d) for v, d in zip(values0, directions)] + normalized_values1 = [_normalize_value(v, d) for v, d in zip(values1, directions)] + + if normalized_values0 == normalized_values1: + return False + + return all(v0 <= v1 for v0, v1 in zip(normalized_values0, normalized_values1)) + + +def _normalize_value(value: float | None, direction: StudyDirection) -> float: + if value is None: + return float("inf") + + if direction is StudyDirection.MAXIMIZE: + value = -value + + return value diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_optimize.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_optimize.py new file mode 100644 index 0000000000000000000000000000000000000000..6ced4758135425e4a22e0271e93f423d8962da93 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_optimize.py @@ -0,0 +1,276 @@ +from __future__ import annotations + +from collections.abc import Callable +from collections.abc import Iterable +from collections.abc import Sequence +from concurrent.futures import FIRST_COMPLETED +from concurrent.futures import Future +from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import wait +import copy +import datetime +import gc +import itertools +import os +import sys +from typing import Any +import warnings + +import optuna +from optuna import exceptions +from optuna import logging +from optuna import progress_bar as pbar_module +from optuna.exceptions import ExperimentalWarning +from optuna.storages._heartbeat import get_heartbeat_thread +from optuna.storages._heartbeat import is_heartbeat_enabled +from optuna.study._tell import _tell_with_warning +from optuna.trial import FrozenTrial +from optuna.trial import TrialState + + +_logger = logging.get_logger(__name__) + + +def _optimize( + study: "optuna.Study", + func: "optuna.study.study.ObjectiveFuncType", + n_trials: int | None = None, + timeout: float | None = None, + n_jobs: int = 1, + catch: tuple[type[Exception], ...] = (), + callbacks: Iterable[Callable[["optuna.Study", FrozenTrial], None]] | None = None, + gc_after_trial: bool = False, + show_progress_bar: bool = False, +) -> None: + if not isinstance(catch, tuple): + raise TypeError( + "The catch argument is of type '{}' but must be a tuple.".format(type(catch).__name__) + ) + + if study._thread_local.in_optimize_loop: + raise RuntimeError("Nested invocation of `Study.optimize` method isn't allowed.") + + if show_progress_bar and n_trials is None and timeout is not None and n_jobs != 1: + warnings.warn("The timeout-based progress bar is not supported with n_jobs != 1.") + show_progress_bar = False + + progress_bar = pbar_module._ProgressBar(show_progress_bar, n_trials, timeout) + + study._stop_flag = False + + try: + if n_jobs == 1: + _optimize_sequential( + study, + func, + n_trials, + timeout, + catch, + callbacks, + gc_after_trial, + reseed_sampler_rng=False, + time_start=None, + progress_bar=progress_bar, + ) + else: + if n_jobs == -1: + n_jobs = os.cpu_count() or 1 + + time_start = datetime.datetime.now() + futures: set[Future] = set() + + with ThreadPoolExecutor(max_workers=n_jobs) as executor: + for n_submitted_trials in itertools.count(): + if study._stop_flag: + break + + if ( + timeout is not None + and (datetime.datetime.now() - time_start).total_seconds() > timeout + ): + break + + if n_trials is not None and n_submitted_trials >= n_trials: + break + + if len(futures) >= n_jobs: + completed, futures = wait(futures, return_when=FIRST_COMPLETED) + # Raise if exception occurred in executing the completed futures. + for f in completed: + f.result() + + futures.add( + executor.submit( + _optimize_sequential, + study, + func, + 1, + timeout, + catch, + callbacks, + gc_after_trial, + True, + time_start, + progress_bar, + ) + ) + finally: + study._thread_local.in_optimize_loop = False + progress_bar.close() + + +def _optimize_sequential( + study: "optuna.Study", + func: "optuna.study.study.ObjectiveFuncType", + n_trials: int | None, + timeout: float | None, + catch: tuple[type[Exception], ...], + callbacks: Iterable[Callable[["optuna.Study", FrozenTrial], None]] | None, + gc_after_trial: bool, + reseed_sampler_rng: bool, + time_start: datetime.datetime | None, + progress_bar: pbar_module._ProgressBar | None, +) -> None: + # Here we set `in_optimize_loop = True`, not at the beginning of the `_optimize()` function. + # Because it is a thread-local object and `n_jobs` option spawns new threads. + study._thread_local.in_optimize_loop = True + if reseed_sampler_rng: + study.sampler.reseed_rng() + + i_trial = 0 + + if time_start is None: + time_start = datetime.datetime.now() + + while True: + if study._stop_flag: + break + + if n_trials is not None: + if i_trial >= n_trials: + break + i_trial += 1 + + if timeout is not None: + elapsed_seconds = (datetime.datetime.now() - time_start).total_seconds() + if elapsed_seconds >= timeout: + break + + try: + frozen_trial_id = _run_trial(study, func, catch) + finally: + # The following line mitigates memory problems that can be occurred in some + # environments (e.g., services that use computing containers such as GitHub Actions). + # Please refer to the following PR for further details: + # https://github.com/optuna/optuna/pull/325. + if gc_after_trial: + gc.collect() + + if callbacks is not None: + frozen_trial = study._storage.get_trial(frozen_trial_id) + for callback in callbacks: + callback(study, copy.deepcopy(frozen_trial)) + + if progress_bar is not None: + elapsed_seconds = (datetime.datetime.now() - time_start).total_seconds() + progress_bar.update(elapsed_seconds, study) + + study._storage.remove_session() + + +def _run_trial( + study: "optuna.Study", + func: "optuna.study.study.ObjectiveFuncType", + catch: tuple[type[Exception], ...], +) -> int: + if is_heartbeat_enabled(study._storage): + with warnings.catch_warnings(): + # Ignore ExperimentalWarning when using fail_stale_trials internally. + warnings.simplefilter("ignore", ExperimentalWarning) + optuna.storages.fail_stale_trials(study) + + trial = study.ask() + + state: TrialState | None = None + value_or_values: float | Sequence[float] | None = None + func_err: Exception | KeyboardInterrupt | None = None + func_err_fail_exc_info: Any | None = None + + with get_heartbeat_thread(trial._trial_id, study._storage): + try: + value_or_values = func(trial) + except exceptions.TrialPruned as e: + # TODO(mamu): Handle multi-objective cases. + state = TrialState.PRUNED + func_err = e + except (Exception, KeyboardInterrupt) as e: + state = TrialState.FAIL + func_err = e + func_err_fail_exc_info = sys.exc_info() + + # `_tell_with_warning` may raise during trial post-processing. + try: + updated_state, values, warning_message = _tell_with_warning( + study=study, + trial=trial, + value_or_values=value_or_values, + state=state, + suppress_warning=True, + ) + except Exception: + frozen_trial = study._storage.get_trial(trial._trial_id) + updated_state = frozen_trial.state + values = frozen_trial.values + warning_message = None + raise + finally: + if updated_state == TrialState.COMPLETE: + assert values is not None + study._log_completed_trial(values, trial.number, trial.params) + elif updated_state == TrialState.PRUNED: + _logger.info("Trial {} pruned. {}".format(trial.number, str(func_err))) + elif updated_state == TrialState.FAIL: + if func_err is not None: + _log_failed_trial( + trial.number, + trial.params, + repr(func_err), + exc_info=func_err_fail_exc_info, + value_or_values=value_or_values, + ) + elif warning_message is not None: + _log_failed_trial( + trial.number, + trial.params, + warning_message, + value_or_values=value_or_values, + ) + else: + assert False, "Should not reach." + else: + assert False, "Should not reach." + + if ( + updated_state == TrialState.FAIL + and func_err is not None + and not isinstance(func_err, catch) + ): + raise func_err + return trial._trial_id + + +def _log_failed_trial( + trial_number: int, + trial_params: dict[str, Any], + message: str | Warning, + exc_info: Any = None, + value_or_values: Any = None, +) -> None: + _logger.warning( + "Trial {} failed with parameters: {} because of the following error: {}.".format( + trial_number, trial_params, message + ), + exc_info=exc_info, + ) + + _logger.warning("Trial {} failed with value {}.".format(trial_number, repr(value_or_values))) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_study_direction.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_study_direction.py new file mode 100644 index 0000000000000000000000000000000000000000..dd2d911953f6711c692f37017948d370200feb22 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_study_direction.py @@ -0,0 +1,18 @@ +import enum + + +class StudyDirection(enum.IntEnum): + """Direction of a :class:`~optuna.study.Study`. + + Attributes: + NOT_SET: + Direction has not been set. + MINIMIZE: + :class:`~optuna.study.Study` minimizes the objective function. + MAXIMIZE: + :class:`~optuna.study.Study` maximizes the objective function. + """ + + NOT_SET = 0 + MINIMIZE = 1 + MAXIMIZE = 2 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_study_summary.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_study_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..ad2a7af2a42e8a33d34c706c5a0f28e116cf4597 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_study_summary.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +from collections.abc import Sequence +import datetime +from typing import Any +import warnings + +from optuna import logging +from optuna import trial +from optuna.study._study_direction import StudyDirection + + +_logger = logging.get_logger(__name__) + + +class StudySummary: + """Basic attributes and aggregated results of a :class:`~optuna.study.Study`. + + See also :func:`optuna.study.get_all_study_summaries`. + + Attributes: + study_name: + Name of the :class:`~optuna.study.Study`. + direction: + :class:`~optuna.study.StudyDirection` of the :class:`~optuna.study.Study`. + + .. note:: + This attribute is only available during single-objective optimization. + directions: + A sequence of :class:`~optuna.study.StudyDirection` objects. + best_trial: + :class:`optuna.trial.FrozenTrial` with best objective value in the + :class:`~optuna.study.Study`. + user_attrs: + Dictionary that contains the attributes of the :class:`~optuna.study.Study` set with + :func:`optuna.study.Study.set_user_attr`. + system_attrs: + Dictionary that contains the attributes of the :class:`~optuna.study.Study` internally + set by Optuna. + + .. warning:: + Deprecated in v3.1.0. ``system_attrs`` argument will be removed in the future. + The removal of this feature is currently scheduled for v5.0.0, + but this schedule is subject to change. + See https://github.com/optuna/optuna/releases/tag/v3.1.0. + n_trials: + The number of trials ran in the :class:`~optuna.study.Study`. + datetime_start: + Datetime where the :class:`~optuna.study.Study` started. + + """ + + def __init__( + self, + study_name: str, + direction: StudyDirection | None, + best_trial: trial.FrozenTrial | None, + user_attrs: dict[str, Any], + system_attrs: dict[str, Any], + n_trials: int, + datetime_start: datetime.datetime | None, + study_id: int, + *, + directions: Sequence[StudyDirection] | None = None, + ): + self.study_name = study_name + if direction is None and directions is None: + raise ValueError("Specify one of `direction` and `directions`.") + elif directions is not None: + self._directions = list(directions) + elif direction is not None: + self._directions = [direction] + else: + raise ValueError("Specify only one of `direction` and `directions`.") + self.best_trial = best_trial + self.user_attrs = user_attrs + self._system_attrs = system_attrs + self.n_trials = n_trials + self.datetime_start = datetime_start + self._study_id = study_id + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, StudySummary): + return NotImplemented + + return other.__dict__ == self.__dict__ + + def __lt__(self, other: Any) -> bool: + if not isinstance(other, StudySummary): + return NotImplemented + + return self._study_id < other._study_id + + def __le__(self, other: Any) -> bool: + if not isinstance(other, StudySummary): + return NotImplemented + + return self._study_id <= other._study_id + + @property + def direction(self) -> StudyDirection: + if len(self._directions) > 1: + raise RuntimeError( + "This attribute is not available during multi-objective optimization." + ) + + return self._directions[0] + + @property + def directions(self) -> Sequence[StudyDirection]: + return self._directions + + @property + def system_attrs(self) -> dict[str, Any]: + warnings.warn( + "`system_attrs` has been deprecated in v3.1.0. " + "The removal of this feature is currently scheduled for v5.0.0, " + "but this schedule is subject to change. " + "See https://github.com/optuna/optuna/releases/tag/v3.1.0.", + FutureWarning, + ) + + return self._system_attrs diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_tell.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_tell.py new file mode 100644 index 0000000000000000000000000000000000000000..0e51d63e04fd8a8b20e52f90f4b779501c387367 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/_tell.py @@ -0,0 +1,177 @@ +from __future__ import annotations + +from collections.abc import Sequence +import math +from typing import TYPE_CHECKING +import warnings + +import optuna +from optuna import logging +from optuna import pruners +from optuna.trial import FrozenTrial +from optuna.trial import TrialState + + +if TYPE_CHECKING: + from optuna import Study + from optuna import Trial + + +_logger = logging.get_logger(__name__) + + +def _get_frozen_trial(study: Study, trial: Trial | int) -> FrozenTrial: + if isinstance(trial, optuna.Trial): + trial_id = trial._trial_id + elif isinstance(trial, int): + trial_number = trial + try: + trial_id = study._storage.get_trial_id_from_study_id_trial_number( + study._study_id, trial_number + ) + except KeyError as e: + raise ValueError( + f"Cannot tell for trial with number {trial_number} since it has not been " + "created." + ) from e + else: + raise TypeError("Trial must be a trial object or trial number.") + + return study._storage.get_trial(trial_id) + + +def _check_state_and_values( + state: TrialState | None, values: float | Sequence[float] | None +) -> None: + if state == TrialState.COMPLETE: + if values is None: + raise ValueError( + "No values were told. Values are required when state is TrialState.COMPLETE." + ) + elif state in (TrialState.PRUNED, TrialState.FAIL): + if values is not None: + raise ValueError( + "Values were told. Values cannot be specified when state is " + "TrialState.PRUNED or TrialState.FAIL." + ) + elif state is not None: + raise ValueError(f"Cannot tell with state {state}.") + + +def _check_values_are_feasible(study: Study, values: Sequence[float]) -> str | None: + for v in values: + # TODO(Imamura): Construct error message taking into account all values and do not early + # return `value` is assumed to be ignored on failure so we can set it to any value. + try: + float(v) + except (ValueError, TypeError): + return f"The value {repr(v)} could not be cast to float" + + if math.isnan(v): + return f"The value {v} is not acceptable" + + if len(study.directions) != len(values): + return ( + f"The number of the values {len(values)} did not match the number of the objectives " + f"{len(study.directions)}" + ) + + return None + + +def _tell_with_warning( + study: Study, + trial: Trial | int, + value_or_values: float | Sequence[float] | None = None, + state: TrialState | None = None, + skip_if_finished: bool = False, + suppress_warning: bool = False, +) -> tuple[TrialState, list[float] | None, str | None]: + """Internal method of :func:`~optuna.study.Study.tell`. + + Refer to the document for :func:`~optuna.study.Study.tell` for the reference. + This method has one additional parameter ``suppress_warning``. + + Args: + suppress_warning: + If :obj:`True`, tell will not show warnings when tell receives an invalid + values. This flag is expected to be :obj:`True` only when it is invoked by + Study.optimize. + """ + + # We must invalidate all trials cache here as it is only valid within a trial. + study._thread_local.cached_all_trials = None + + # Validate the trial argument. + frozen_trial = _get_frozen_trial(study, trial) + if frozen_trial.state.is_finished() and skip_if_finished: + _logger.info( + f"Skipped telling trial {frozen_trial.number} with values " + f"{value_or_values} and state {state} since trial was already finished. " + f"Finished trial has values {frozen_trial.values} and state {frozen_trial.state}." + ) + return frozen_trial.state, frozen_trial.values, None + elif frozen_trial.state != TrialState.RUNNING: + raise ValueError(f"Cannot tell a {frozen_trial.state.name} trial.") + + # Validate the state and values arguments. + values: Sequence[float] | None + if value_or_values is None: + values = None + elif isinstance(value_or_values, Sequence): + values = value_or_values + else: + values = [value_or_values] + + _check_state_and_values(state, values) + + values_conversion_failure_message = None + + if state == TrialState.COMPLETE: + assert values is not None + + values_conversion_failure_message = _check_values_are_feasible(study, values) + if values_conversion_failure_message is not None: + raise ValueError(values_conversion_failure_message) + elif state == TrialState.PRUNED: + # Register the last intermediate value if present as the value of the trial. + # TODO(hvy): Whether a pruned trials should have an actual value can be discussed. + assert values is None + + last_step = frozen_trial.last_step + if last_step is not None: + last_intermediate_value = frozen_trial.intermediate_values[last_step] + # intermediate_values can be unacceptable value, i.e., NaN. + if _check_values_are_feasible(study, [last_intermediate_value]) is None: + values = [last_intermediate_value] + elif state is None: + if values is None: + values_conversion_failure_message = "The value None could not be cast to float." + else: + values_conversion_failure_message = _check_values_are_feasible(study, values) + + if values_conversion_failure_message is None: + state = TrialState.COMPLETE + else: + state = TrialState.FAIL + values = None + if not suppress_warning: + warnings.warn(values_conversion_failure_message) + values_conversion_failure_message = None + + assert state is not None + + # Cast values to list of floats. + if values is not None: + # values have been checked to be castable to floats in _check_values_are_feasible. + values = [float(value) for value in values] + + # Post-processing and storing the trial. + try: + # Sampler defined trial post-processing. + study = pruners._filter_study(study, frozen_trial) + study.sampler.after_trial(study, frozen_trial, state, values) + finally: + study._storage.set_trial_state_values(frozen_trial._trial_id, state, values) + + return state, values, values_conversion_failure_message diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/study.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/study.py new file mode 100644 index 0000000000000000000000000000000000000000..c14de8561029fdc8cd394f3081d67563dccbf827 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/study/study.py @@ -0,0 +1,1728 @@ +from __future__ import annotations + +from collections.abc import Container +from collections.abc import Iterable +from collections.abc import Mapping +import copy +from numbers import Real +import threading +from typing import Any +from typing import Callable +from typing import cast +from typing import Sequence +from typing import TYPE_CHECKING +from typing import Union +import warnings + +import numpy as np + +import optuna +from optuna import exceptions +from optuna import logging +from optuna import pruners +from optuna import samplers +from optuna import storages +from optuna._convert_positional_args import convert_positional_args +from optuna._deprecated import deprecated_func +from optuna._experimental import experimental_func +from optuna._imports import _LazyImport +from optuna._typing import JSONSerializable +from optuna.distributions import _convert_old_distribution_to_new_distribution +from optuna.distributions import BaseDistribution +from optuna.storages._heartbeat import is_heartbeat_enabled +from optuna.study._constrained_optimization import _CONSTRAINTS_KEY +from optuna.study._constrained_optimization import _get_feasible_trials +from optuna.study._multi_objective import _get_pareto_front_trials +from optuna.study._optimize import _optimize +from optuna.study._study_direction import StudyDirection +from optuna.study._study_summary import StudySummary # NOQA +from optuna.study._tell import _get_frozen_trial +from optuna.study._tell import _tell_with_warning +from optuna.trial import create_trial +from optuna.trial import TrialState + + +_dataframe = _LazyImport("optuna.study._dataframe") + +if TYPE_CHECKING: + from optuna.study._dataframe import pd + from optuna.trial import FrozenTrial + from optuna.trial import Trial + + +ObjectiveFuncType = Callable[["Trial"], Union[float, Sequence[float]]] + + +_SYSTEM_ATTR_METRIC_NAMES = "study:metric_names" + + +_logger = logging.get_logger(__name__) + + +class _ThreadLocalStudyAttribute(threading.local): + in_optimize_loop: bool = False + cached_all_trials: list[FrozenTrial] | None = None + + +class Study: + """A study corresponds to an optimization task, i.e., a set of trials. + + This object provides interfaces to run a new :class:`~optuna.trial.Trial`, access trials' + history, set/get user-defined attributes of the study itself. + + Note that the direct use of this constructor is not recommended. + To create and load a study, please refer to the documentation of + :func:`~optuna.study.create_study` and :func:`~optuna.study.load_study` respectively. + + """ + + def __init__( + self, + study_name: str, + storage: str | storages.BaseStorage, + sampler: "samplers.BaseSampler" | None = None, + pruner: pruners.BasePruner | None = None, + ) -> None: + self.study_name = study_name + storage = storages.get_storage(storage) + study_id = storage.get_study_id_from_name(study_name) + self._study_id = study_id + self._storage = storage + self._directions = storage.get_study_directions(study_id) + + self.sampler = sampler or samplers.TPESampler() + self.pruner = pruner or pruners.MedianPruner() + + self._thread_local = _ThreadLocalStudyAttribute() + self._stop_flag = False + + def __getstate__(self) -> dict[Any, Any]: + state = self.__dict__.copy() + del state["_thread_local"] + return state + + def __setstate__(self, state: dict[Any, Any]) -> None: + self.__dict__.update(state) + self._thread_local = _ThreadLocalStudyAttribute() + + @property + def best_params(self) -> dict[str, Any]: + """Return parameters of the best trial in the study. + + .. note:: + This feature can only be used for single-objective optimization. + + Returns: + A dictionary containing parameters of the best trial. + + """ + + return self.best_trial.params + + @property + def best_value(self) -> float: + """Return the best objective value in the study. + + .. note:: + This feature can only be used for single-objective optimization. + + Returns: + A float representing the best objective value. + + """ + + best_value = self.best_trial.value + assert best_value is not None + + return best_value + + @property + def best_trial(self) -> FrozenTrial: + """Return the best trial in the study. + + .. note:: + This feature can only be used for single-objective optimization. + If your study is multi-objective, + use :attr:`~optuna.study.Study.best_trials` instead. + + Returns: + A :class:`~optuna.trial.FrozenTrial` object of the best trial. + + .. seealso:: + The :ref:`reuse_best_trial` tutorial provides a detailed example of how to use this + method. + + """ + return self._get_best_trial(deepcopy=True) + + @property + def best_trials(self) -> list[FrozenTrial]: + """Return trials located at the Pareto front in the study. + + A trial is located at the Pareto front if there are no trials that dominate the trial. + It's called that a trial ``t0`` dominates another trial ``t1`` if + ``all(v0 <= v1) for v0, v1 in zip(t0.values, t1.values)`` and + ``any(v0 < v1) for v0, v1 in zip(t0.values, t1.values)`` are held. + + Returns: + A list of :class:`~optuna.trial.FrozenTrial` objects. + """ + + # Check whether the study is constrained optimization. + trials = self.get_trials(deepcopy=False) + is_constrained = any((_CONSTRAINTS_KEY in trial.system_attrs) for trial in trials) + + return _get_pareto_front_trials(self, consider_constraint=is_constrained) + + @property + def direction(self) -> StudyDirection: + """Return the direction of the study. + + .. note:: + This feature can only be used for single-objective optimization. + If your study is multi-objective, + use :attr:`~optuna.study.Study.directions` instead. + + Returns: + A :class:`~optuna.study.StudyDirection` object. + + """ + + if self._is_multi_objective(): + raise RuntimeError( + "A single direction cannot be retrieved from a multi-objective study. Consider " + "using Study.directions to retrieve a list containing all directions." + ) + + return self.directions[0] + + @property + def directions(self) -> list[StudyDirection]: + """Return the directions of the study. + + Returns: + A list of :class:`~optuna.study.StudyDirection` objects. + """ + + return self._directions + + @property + def trials(self) -> list[FrozenTrial]: + """Return all trials in the study. + + The returned trials are ordered by trial number. + + This is a short form of ``self.get_trials(deepcopy=True, states=None)``. + + Returns: + A list of :class:`~optuna.trial.FrozenTrial` objects. + + .. seealso:: + See :func:`~optuna.study.Study.get_trials` for related method. + + """ + + return self.get_trials(deepcopy=True, states=None) + + def get_trials( + self, + deepcopy: bool = True, + states: Container[TrialState] | None = None, + ) -> list[FrozenTrial]: + """Return all trials in the study. + + The returned trials are ordered by trial number. + + .. seealso:: + See :attr:`~optuna.study.Study.trials` for related property. + + Example: + .. testcode:: + + import optuna + + + def objective(trial): + x = trial.suggest_float("x", -1, 1) + return x**2 + + + study = optuna.create_study() + study.optimize(objective, n_trials=3) + + trials = study.get_trials() + assert len(trials) == 3 + Args: + deepcopy: + Flag to control whether to apply ``copy.deepcopy()`` to the trials. + Note that if you set the flag to :obj:`False`, you shouldn't mutate + any fields of the returned trial. Otherwise the internal state of + the study may corrupt and unexpected behavior may happen. + states: + Trial states to filter on. If :obj:`None`, include all states. + + Returns: + A list of :class:`~optuna.trial.FrozenTrial` objects. + """ + return self._get_trials(deepcopy, states, use_cache=False) + + def _get_trials( + self, + deepcopy: bool = True, + states: Container[TrialState] | None = None, + use_cache: bool = False, + ) -> list[FrozenTrial]: + if use_cache: + if self._thread_local.cached_all_trials is None: + self._thread_local.cached_all_trials = self._storage.get_all_trials( + self._study_id, deepcopy=False + ) + trials = self._thread_local.cached_all_trials + if states is not None: + filtered_trials = [t for t in trials if t.state in states] + else: + filtered_trials = trials + return copy.deepcopy(filtered_trials) if deepcopy else filtered_trials + + return self._storage.get_all_trials(self._study_id, deepcopy=deepcopy, states=states) + + def _get_best_trial(self, deepcopy: bool) -> FrozenTrial: + """Return the best trial in the study. + + Args: + deepcopy: + Flag to control whether to apply ``copy.deepcopy()`` to the trial. + If :obj:`False`, returns the trial without deep copying for better performance. + Note that if you set this to :obj:`False`, you shouldn't mutate any fields + of the returned trial. + + Returns: + A :class:`~optuna.trial.FrozenTrial` object of the best trial. + """ + if self._is_multi_objective(): + raise RuntimeError( + "A single best trial cannot be retrieved from a multi-objective study. Consider " + "using Study.best_trials to retrieve a list containing the best trials." + ) + + best_trial = self._storage.get_best_trial(self._study_id) + + # If the trial with the best value is infeasible, select the best trial from all feasible + # trials. Note that the behavior is undefined when constrained optimization without the + # violation value in the best-valued trial. + constraints = best_trial.system_attrs.get(_CONSTRAINTS_KEY) + if constraints is not None and any([x > 0.0 for x in constraints]): + complete_trials = self.get_trials(deepcopy=False, states=[TrialState.COMPLETE]) + feasible_trials = _get_feasible_trials(complete_trials) + if len(feasible_trials) == 0: + raise ValueError("No feasible trials are completed yet.") + if self.direction == StudyDirection.MAXIMIZE: + best_trial = max(feasible_trials, key=lambda t: cast(float, t.value)) + else: + best_trial = min(feasible_trials, key=lambda t: cast(float, t.value)) + + return copy.deepcopy(best_trial) if deepcopy else best_trial + + @property + def user_attrs(self) -> dict[str, Any]: + """Return user attributes. + + .. seealso:: + + See :func:`~optuna.study.Study.set_user_attr` for related method. + + Example: + + .. testcode:: + + import optuna + + + def objective(trial): + x = trial.suggest_float("x", 0, 1) + y = trial.suggest_float("y", 0, 1) + return x**2 + y**2 + + + study = optuna.create_study() + + study.set_user_attr("objective function", "quadratic function") + study.set_user_attr("dimensions", 2) + study.set_user_attr("contributors", ["Akiba", "Sano"]) + + assert study.user_attrs == { + "objective function": "quadratic function", + "dimensions": 2, + "contributors": ["Akiba", "Sano"], + } + + Returns: + A dictionary containing all user attributes. + """ + + return copy.deepcopy(self._storage.get_study_user_attrs(self._study_id)) + + @property + @deprecated_func("3.1.0", "5.0.0") + def system_attrs(self) -> dict[str, Any]: + """Return system attributes. + + Returns: + A dictionary containing all system attributes. + """ + + return copy.deepcopy(self._storage.get_study_system_attrs(self._study_id)) + + @property + def metric_names(self) -> list[str] | None: + """Return metric names. + + .. note:: + Use :meth:`~optuna.study.Study.set_metric_names` to set the metric names first. + + Returns: + A list with names for each dimension of the returned values of the objective function. + """ + return self._storage.get_study_system_attrs(self._study_id).get(_SYSTEM_ATTR_METRIC_NAMES) + + def optimize( + self, + func: ObjectiveFuncType, + n_trials: int | None = None, + timeout: float | None = None, + n_jobs: int = 1, + catch: Iterable[type[Exception]] | type[Exception] = (), + callbacks: Iterable[Callable[[Study, FrozenTrial], None]] | None = None, + gc_after_trial: bool = False, + show_progress_bar: bool = False, + ) -> None: + """Optimize an objective function. + + Optimization is done by choosing a suitable set of hyperparameter values from a given + range. Uses a sampler which implements the task of value suggestion based on a specified + distribution. The sampler is specified in :func:`~optuna.study.create_study` and the + default choice for the sampler is TPE. + See also :class:`~optuna.samplers.TPESampler` for more details on 'TPE'. + + Optimization will be stopped when receiving a termination signal such as SIGINT and + SIGTERM. Unlike other signals, a trial is automatically and cleanly failed when receiving + SIGINT (Ctrl+C). If ``n_jobs`` is greater than one or if another signal than SIGINT + is used, the interrupted trial state won't be properly updated. + + Example: + + .. testcode:: + + import optuna + + + def objective(trial): + x = trial.suggest_float("x", -1, 1) + return x**2 + + + study = optuna.create_study() + study.optimize(objective, n_trials=3) + + Args: + func: + A callable that implements objective function. + n_trials: + The number of trials for each process. :obj:`None` represents no limit in terms of + the number of trials. The study continues to create trials until the number of + trials reaches ``n_trials``, ``timeout`` period elapses, + :func:`~optuna.study.Study.stop` is called, or a termination signal such as + SIGTERM or Ctrl+C is received. + + .. seealso:: + :class:`optuna.study.MaxTrialsCallback` can ensure how many times trials + will be performed across all processes. + timeout: + Stop study after the given number of second(s). :obj:`None` represents no limit in + terms of elapsed time. The study continues to create trials until the number of + trials reaches ``n_trials``, ``timeout`` period elapses, + :func:`~optuna.study.Study.stop` is called or, a termination signal such as + SIGTERM or Ctrl+C is received. + n_jobs: + The number of parallel jobs. If this argument is set to ``-1``, the number is + set to CPU count. + + .. note:: + ``n_jobs`` allows parallelization using :obj:`threading` and may suffer from + `Python's GIL `__. + It is recommended to use :ref:`process-based parallelization` + if ``func`` is CPU bound. + + catch: + A study continues to run even when a trial raises one of the exceptions specified + in this argument. Default is an empty tuple, i.e. the study will stop for any + exception except for :class:`~optuna.exceptions.TrialPruned`. + callbacks: + List of callback functions that are invoked at the end of each trial. Each function + must accept two parameters with the following types in this order: + :class:`~optuna.study.Study` and :class:`~optuna.trial.FrozenTrial`. + + .. seealso:: + + See the tutorial of :ref:`optuna_callback` for how to use and implement + callback functions. + + gc_after_trial: + Flag to determine whether to automatically run garbage collection after each trial. + Set to :obj:`True` to run the garbage collection, :obj:`False` otherwise. + When it runs, it runs a full collection by internally calling :func:`gc.collect`. + If you see an increase in memory consumption over several trials, try setting this + flag to :obj:`True`. + + .. seealso:: + + :ref:`out-of-memory-gc-collect` + + show_progress_bar: + Flag to show progress bars or not. To show progress bar, set this :obj:`True`. + Note that it is disabled when ``n_trials`` is :obj:`None`, + ``timeout`` is not :obj:`None`, and ``n_jobs`` :math:`\\ne 1`. + + Raises: + RuntimeError: + If nested invocation of this method occurs. + """ + _optimize( + study=self, + func=func, + n_trials=n_trials, + timeout=timeout, + n_jobs=n_jobs, + catch=tuple(catch) if isinstance(catch, Iterable) else (catch,), + callbacks=callbacks, + gc_after_trial=gc_after_trial, + show_progress_bar=show_progress_bar, + ) + + def ask(self, fixed_distributions: dict[str, BaseDistribution] | None = None) -> Trial: + """Create a new trial from which hyperparameters can be suggested. + + This method is part of an alternative to :func:`~optuna.study.Study.optimize` that allows + controlling the lifetime of a trial outside the scope of ``func``. Each call to this + method should be followed by a call to :func:`~optuna.study.Study.tell` to finish the + created trial. + + .. seealso:: + + The :ref:`ask_and_tell` tutorial provides use-cases with examples. + + Example: + + Getting the trial object with the :func:`~optuna.study.Study.ask` method. + + .. testcode:: + + import optuna + + + study = optuna.create_study() + + trial = study.ask() + + x = trial.suggest_float("x", -1, 1) + + study.tell(trial, x**2) + + Example: + + Passing previously defined distributions to the :func:`~optuna.study.Study.ask` + method. + + .. testcode:: + + import optuna + + + study = optuna.create_study() + + distributions = { + "optimizer": optuna.distributions.CategoricalDistribution(["adam", "sgd"]), + "lr": optuna.distributions.FloatDistribution(0.0001, 0.1, log=True), + } + + # You can pass the distributions previously defined. + trial = study.ask(fixed_distributions=distributions) + + # `optimizer` and `lr` are already suggested and accessible with `trial.params`. + assert "optimizer" in trial.params + assert "lr" in trial.params + + Args: + fixed_distributions: + A dictionary containing the parameter names and parameter's distributions. Each + parameter in this dictionary is automatically suggested for the returned trial, + even when the suggest method is not explicitly invoked by the user. If this + argument is set to :obj:`None`, no parameter is automatically suggested. + + Returns: + A :class:`~optuna.trial.Trial`. + """ + + if not self._thread_local.in_optimize_loop and is_heartbeat_enabled(self._storage): + warnings.warn("Heartbeat of storage is supposed to be used with Study.optimize.") + + fixed_distributions = fixed_distributions or {} + fixed_distributions = { + key: _convert_old_distribution_to_new_distribution(dist) + for key, dist in fixed_distributions.items() + } + + # Sync storage once every trial. + self._thread_local.cached_all_trials = None + + trial_id = self._pop_waiting_trial_id() + if trial_id is None: + trial_id = self._storage.create_new_trial(self._study_id) + trial = optuna.Trial(self, trial_id) + + for name, param in fixed_distributions.items(): + trial._suggest(name, param) + + return trial + + def tell( + self, + trial: Trial | int, + values: float | Sequence[float] | None = None, + state: TrialState | None = None, + skip_if_finished: bool = False, + ) -> FrozenTrial: + """Finish a trial created with :func:`~optuna.study.Study.ask`. + + .. seealso:: + + The :ref:`ask_and_tell` tutorial provides use-cases with examples. + + Example: + + .. testcode:: + + import optuna + from optuna.trial import TrialState + + + def f(x): + return (x - 2) ** 2 + + + def df(x): + return 2 * x - 4 + + + study = optuna.create_study() + + n_trials = 30 + + for _ in range(n_trials): + trial = study.ask() + + lr = trial.suggest_float("lr", 1e-5, 1e-1, log=True) + + # Iterative gradient descent objective function. + x = 3 # Initial value. + for step in range(128): + y = f(x) + + trial.report(y, step=step) + + if trial.should_prune(): + # Finish the trial with the pruned state. + study.tell(trial, state=TrialState.PRUNED) + break + + gy = df(x) + x -= gy * lr + else: + # Finish the trial with the final value after all iterations. + study.tell(trial, y) + + Args: + trial: + A :class:`~optuna.trial.Trial` object or a trial number. + values: + Optional objective value or a sequence of such values in case the study is used + for multi-objective optimization. Argument must be provided if ``state`` is + :class:`~optuna.trial.TrialState.COMPLETE` and should be :obj:`None` if ``state`` + is :class:`~optuna.trial.TrialState.FAIL` or + :class:`~optuna.trial.TrialState.PRUNED`. + state: + State to be reported. Must be :obj:`None`, + :class:`~optuna.trial.TrialState.COMPLETE`, + :class:`~optuna.trial.TrialState.FAIL` or + :class:`~optuna.trial.TrialState.PRUNED`. + If ``state`` is :obj:`None`, + it will be updated to :class:`~optuna.trial.TrialState.COMPLETE` + or :class:`~optuna.trial.TrialState.FAIL` depending on whether + validation for ``values`` reported succeed or not. + skip_if_finished: + Flag to control whether exception should be raised when values for already + finished trial are told. If :obj:`True`, tell is skipped without any error + when the trial is already finished. + + Returns: + A :class:`~optuna.trial.FrozenTrial` representing the resulting trial. + A returned trial is deep copied thus user can modify it as needed. + """ + + _tell_with_warning( + study=self, + trial=trial, + value_or_values=values, + state=state, + skip_if_finished=skip_if_finished, + ) + return copy.deepcopy(_get_frozen_trial(self, trial)) + + def set_user_attr(self, key: str, value: Any) -> None: + """Set a user attribute to the study. + + .. seealso:: + + See :attr:`~optuna.study.Study.user_attrs` for related attribute. + + .. seealso:: + + See the recipe on :ref:`attributes`. + + Example: + + .. testcode:: + + import optuna + + + def objective(trial): + x = trial.suggest_float("x", 0, 1) + y = trial.suggest_float("y", 0, 1) + return x**2 + y**2 + + + study = optuna.create_study() + + study.set_user_attr("objective function", "quadratic function") + study.set_user_attr("dimensions", 2) + study.set_user_attr("contributors", ["Akiba", "Sano"]) + + assert study.user_attrs == { + "objective function": "quadratic function", + "dimensions": 2, + "contributors": ["Akiba", "Sano"], + } + + Args: + key: A key string of the attribute. + value: A value of the attribute. The value should be JSON serializable. + + """ + + self._storage.set_study_user_attr(self._study_id, key, value) + + @deprecated_func("3.1.0", "5.0.0") + def set_system_attr(self, key: str, value: Any) -> None: + """Set a system attribute to the study. + + Note that Optuna internally uses this method to save system messages. Please use + :func:`~optuna.study.Study.set_user_attr` to set users' attributes. + + Args: + key: A key string of the attribute. + value: A value of the attribute. The value should be JSON serializable. + + """ + + self._storage.set_study_system_attr(self._study_id, key, value) + + def trials_dataframe( + self, + attrs: tuple[str, ...] = ( + "number", + "value", + "datetime_start", + "datetime_complete", + "duration", + "params", + "user_attrs", + "system_attrs", + "state", + ), + multi_index: bool = False, + ) -> "pd.DataFrame": + """Export trials as a pandas DataFrame_. + + The DataFrame_ provides various features to analyze studies. It is also useful to draw a + histogram of objective values and to export trials as a CSV file. + If there are no trials, an empty DataFrame_ is returned. + + Example: + + .. testcode:: + + import optuna + import pandas + + + def objective(trial): + x = trial.suggest_float("x", -1, 1) + return x**2 + + + study = optuna.create_study() + study.optimize(objective, n_trials=3) + + # Create a dataframe from the study. + df = study.trials_dataframe() + assert isinstance(df, pandas.DataFrame) + assert df.shape[0] == 3 # n_trials. + + Args: + attrs: + Specifies field names of :class:`~optuna.trial.FrozenTrial` to include them to a + DataFrame of trials. + multi_index: + Specifies whether the returned DataFrame_ employs MultiIndex_ or not. Columns that + are hierarchical by nature such as ``(params, x)`` will be flattened to + ``params_x`` when set to :obj:`False`. + + Returns: + A pandas DataFrame_ of trials in the :class:`~optuna.study.Study`. + + .. _DataFrame: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html + .. _MultiIndex: https://pandas.pydata.org/pandas-docs/stable/advanced.html + + Note: + If ``value`` is in ``attrs`` during multi-objective optimization, it is implicitly + replaced with ``values``. + + Note: + If :meth:`~optuna.study.Study.set_metric_names` is called, the ``value`` or ``values`` + is implicitly replaced with the dictionary with the objective name as key and the + objective value as value. + """ + return _dataframe._trials_dataframe(self, attrs, multi_index) + + def stop(self) -> None: + """Exit from the current optimization loop after the running trials finish. + + This method lets the running :meth:`~optuna.study.Study.optimize` method return + immediately after all trials which the :meth:`~optuna.study.Study.optimize` method + spawned finishes. + This method does not affect any behaviors of parallel or successive study processes. + This method only works when it is called inside an objective function or callback. + + Example: + + .. testcode:: + + import optuna + + + def objective(trial): + if trial.number == 4: + trial.study.stop() + x = trial.suggest_float("x", 0, 10) + return x**2 + + + study = optuna.create_study() + study.optimize(objective, n_trials=10) + assert len(study.trials) == 5 + + """ + + if not self._thread_local.in_optimize_loop: + raise RuntimeError( + "`Study.stop` is supposed to be invoked inside an objective function or a " + "callback." + ) + + self._stop_flag = True + + def enqueue_trial( + self, + params: dict[str, Any], + user_attrs: dict[str, Any] | None = None, + skip_if_exists: bool = False, + ) -> None: + """Enqueue a trial with given parameter values. + + You can fix the next sampling parameters which will be evaluated in your + objective function. + + Example: + + .. testcode:: + + import optuna + + + def objective(trial): + x = trial.suggest_float("x", 0, 10) + return x**2 + + + study = optuna.create_study() + study.enqueue_trial({"x": 5}) + study.enqueue_trial({"x": 0}, user_attrs={"memo": "optimal"}) + study.optimize(objective, n_trials=2) + + assert study.trials[0].params == {"x": 5} + assert study.trials[1].params == {"x": 0} + assert study.trials[1].user_attrs == {"memo": "optimal"} + + Args: + params: + Parameter values to pass your objective function. + user_attrs: + A dictionary of user-specific attributes other than ``params``. + skip_if_exists: + When :obj:`True`, prevents duplicate trials from being enqueued again. + + .. note:: + This method might produce duplicated trials if called simultaneously + by multiple processes at the same time with same ``params`` dict. + + .. seealso:: + + Please refer to :ref:`enqueue_trial_tutorial` for the tutorial of specifying + hyperparameters manually. + """ + + if not isinstance(params, dict): + raise TypeError("params must be a dictionary.") + + if skip_if_exists and self._should_skip_enqueue(params): + _logger.info(f"Trial with params {params} already exists. Skipping enqueue.") + return + + self.add_trial( + create_trial( + state=TrialState.WAITING, + system_attrs={"fixed_params": params}, + user_attrs=user_attrs, + ) + ) + + def add_trial(self, trial: FrozenTrial) -> None: + """Add trial to study. + + The trial is validated before being added. + + Example: + + .. testcode:: + + import optuna + from optuna.distributions import FloatDistribution + + + def objective(trial): + x = trial.suggest_float("x", 0, 10) + return x**2 + + + study = optuna.create_study() + assert len(study.trials) == 0 + + trial = optuna.trial.create_trial( + params={"x": 2.0}, + distributions={"x": FloatDistribution(0, 10)}, + value=4.0, + ) + + study.add_trial(trial) + assert len(study.trials) == 1 + + study.optimize(objective, n_trials=3) + assert len(study.trials) == 4 + + other_study = optuna.create_study() + + for trial in study.trials: + other_study.add_trial(trial) + assert len(other_study.trials) == len(study.trials) + + other_study.optimize(objective, n_trials=2) + assert len(other_study.trials) == len(study.trials) + 2 + + .. seealso:: + + This method should in general be used to add already evaluated trials + (``trial.state.is_finished() == True``). To queue trials for evaluation, + please refer to :func:`~optuna.study.Study.enqueue_trial`. + + .. seealso:: + + See :func:`~optuna.trial.create_trial` for how to create trials. + + .. seealso:: + Please refer to :ref:`add_trial_tutorial` for the tutorial of specifying + hyperparameters with the evaluated value manually. + + Args: + trial: Trial to add. + + """ + + trial._validate() + + if trial.values is not None and len(self.directions) != len(trial.values): + raise ValueError( + f"The added trial has {len(trial.values)} values, which is different from the " + f"number of objectives {len(self.directions)} in the study (determined by " + "Study.directions)." + ) + + self._storage.create_new_trial(self._study_id, template_trial=trial) + + def add_trials(self, trials: Iterable[FrozenTrial]) -> None: + """Add trials to study. + + The trials are validated before being added. + + Example: + + .. testcode:: + + import optuna + + + def objective(trial): + x = trial.suggest_float("x", 0, 10) + return x**2 + + + study = optuna.create_study() + study.optimize(objective, n_trials=3) + assert len(study.trials) == 3 + + other_study = optuna.create_study() + other_study.add_trials(study.trials) + assert len(other_study.trials) == len(study.trials) + + other_study.optimize(objective, n_trials=2) + assert len(other_study.trials) == len(study.trials) + 2 + + .. seealso:: + + See :func:`~optuna.study.Study.add_trial` for addition of each trial. + + Args: + trials: Trials to add. + + """ + + for trial in trials: + self.add_trial(trial) + + @experimental_func("3.2.0") + def set_metric_names(self, metric_names: list[str]) -> None: + """Set metric names. + + This method names each dimension of the returned values of the objective function. + It is particularly useful in multi-objective optimization. The metric names are + mainly referenced by the visualization functions. + + Example: + + .. testcode:: + + import optuna + import pandas + + + def objective(trial): + x = trial.suggest_float("x", 0, 10) + return x**2, x + 1 + + + study = optuna.create_study(directions=["minimize", "minimize"]) + study.set_metric_names(["x**2", "x+1"]) + study.optimize(objective, n_trials=3) + + df = study.trials_dataframe(multi_index=True) + assert isinstance(df, pandas.DataFrame) + assert list(df.get("values").keys()) == ["x**2", "x+1"] + + .. seealso:: + The names set by this method are used in :meth:`~optuna.study.Study.trials_dataframe` + and :func:`~optuna.visualization.plot_pareto_front`. + + Args: + metric_names: A list of metric names for the objective function. + """ + if len(self.directions) != len(metric_names): + raise ValueError("The number of objectives must match the length of the metric names.") + + self._storage.set_study_system_attr( + self._study_id, _SYSTEM_ATTR_METRIC_NAMES, metric_names + ) + + def _is_multi_objective(self) -> bool: + """Return :obj:`True` if the study has multiple objectives. + + Returns: + A boolean value indicates if `self.directions` has more than 1 element or not. + """ + + return len(self.directions) > 1 + + def _pop_waiting_trial_id(self) -> int | None: + for trial in self._storage.get_all_trials( + self._study_id, deepcopy=False, states=(TrialState.WAITING,) + ): + # Attempt to set the state to RUNNING. + # - If another process or thread has already changed the state to RUNNING, + # set_trial_state_values returns False. + # - If another process or thread has already finished the trial, + # an UpdateFinishedTrialError is raised. + try: + if not self._storage.set_trial_state_values( + trial._trial_id, + state=TrialState.RUNNING, + ): + continue + except exceptions.UpdateFinishedTrialError: + continue + + _logger.debug("Trial {} popped from the trial queue.".format(trial.number)) + return trial._trial_id + + return None + + def _should_skip_enqueue(self, params: Mapping[str, JSONSerializable]) -> bool: + for trial in self.get_trials(deepcopy=False): + trial_params = trial.system_attrs.get("fixed_params", trial.params) + if trial_params.keys() != params.keys(): + # Can't have repeated trials if different params are suggested. + continue + + repeated_params: list[bool] = [] + for param_name, param_value in params.items(): + existing_param = trial_params[param_name] + if not isinstance(param_value, type(existing_param)): + # Enqueued param has distribution that does not match existing param + # (e.g. trying to enqueue categorical to float param). + # We are not doing anything about it here, since sanitization should + # be handled regardless if `skip_if_exists` is `True`. + repeated_params.append(False) + continue + + is_repeated = ( + np.isnan(float(param_value)) + or np.isclose(float(param_value), float(existing_param), atol=0.0) + if isinstance(param_value, Real) + else param_value == existing_param + ) + repeated_params.append(bool(is_repeated)) + + if all(repeated_params): + return True + + return False + + def _log_completed_trial( + self, values: list[float], number: int, params: dict[str, Any] + ) -> None: + if not _logger.isEnabledFor(logging.INFO): + return + + metric_names = self.metric_names + + if len(values) > 1: + trial_values: list[float] | dict[str, float] + if metric_names is None: + trial_values = values + else: + trial_values = {name: value for name, value in zip(metric_names, values)} + _logger.info( + "Trial {} finished with values: {} and parameters: {}.".format( + number, trial_values, params + ) + ) + elif len(values) == 1: + trial_value: float | dict[str, float] + if metric_names is None: + trial_value = values[0] + else: + trial_value = {metric_names[0]: values[0]} + + message = ( + f"Trial {number} finished with value: {trial_value} and parameters: " f"{params}." + ) + try: + best_trial = self._get_best_trial(deepcopy=False) + message += f" Best is trial {best_trial.number} with value: {best_trial.value}." + except ValueError: + # If no feasible trials are completed yet, study.best_trial raises ValueError. + pass + _logger.info(message) + else: + assert False, "Should not reach." + + +@convert_positional_args( + previous_positional_arg_names=[ + "storage", + "sampler", + "pruner", + "study_name", + "direction", + "load_if_exists", + ], + deprecated_version="3.0.0", + removed_version="5.0.0", +) +def create_study( + *, + storage: str | storages.BaseStorage | None = None, + sampler: "samplers.BaseSampler" | None = None, + pruner: pruners.BasePruner | None = None, + study_name: str | None = None, + direction: str | StudyDirection | None = None, + load_if_exists: bool = False, + directions: Sequence[str | StudyDirection] | None = None, +) -> Study: + """Create a new :class:`~optuna.study.Study`. + + Example: + + .. testcode:: + + import optuna + + + def objective(trial): + x = trial.suggest_float("x", 0, 10) + return x**2 + + + study = optuna.create_study() + study.optimize(objective, n_trials=3) + + Args: + storage: + Database URL. If this argument is set to None, + :class:`~optuna.storages.InMemoryStorage` is used, and the + :class:`~optuna.study.Study` will not be persistent. + + .. note:: + When a database URL is passed, Optuna internally uses `SQLAlchemy`_ to handle + the database. Please refer to `SQLAlchemy's document`_ for further details. + If you want to specify non-default options to `SQLAlchemy Engine`_, you can + instantiate :class:`~optuna.storages.RDBStorage` with your desired options and + pass it to the ``storage`` argument instead of a URL. + + .. _SQLAlchemy: https://www.sqlalchemy.org/ + .. _SQLAlchemy's document: + https://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls + .. _SQLAlchemy Engine: https://docs.sqlalchemy.org/en/latest/core/engines.html + + sampler: + A sampler object that implements background algorithm for value suggestion. + If :obj:`None` is specified, :class:`~optuna.samplers.TPESampler` is used during + single-objective optimization and :class:`~optuna.samplers.NSGAIISampler` during + multi-objective optimization. See also :class:`~optuna.samplers`. + pruner: + A pruner object that decides early stopping of unpromising trials. If :obj:`None` + is specified, :class:`~optuna.pruners.MedianPruner` is used as the default. See + also :class:`~optuna.pruners`. + study_name: + Study's name. If this argument is set to None, a unique name is generated + automatically. + direction: + Direction of optimization. Set ``minimize`` for minimization and ``maximize`` for + maximization. You can also pass the corresponding :class:`~optuna.study.StudyDirection` + object. ``direction`` and ``directions`` must not be specified at the same time. + + .. note:: + If none of `direction` and `directions` are specified, the direction of the study + is set to "minimize". + load_if_exists: + Flag to control the behavior to handle a conflict of study names. + In the case where a study named ``study_name`` already exists in the ``storage``, + a :class:`~optuna.exceptions.DuplicatedStudyError` is raised if ``load_if_exists`` is + set to :obj:`False`. + Otherwise, the creation of the study is skipped, and the existing one is returned. + directions: + A sequence of directions during multi-objective optimization. + ``direction`` and ``directions`` must not be specified at the same time. + + Returns: + A :class:`~optuna.study.Study` object. + + See also: + :func:`optuna.create_study` is an alias of :func:`optuna.study.create_study`. + + See also: + The :ref:`rdb` tutorial provides concrete examples to save and resume optimization using + RDB. + + """ + + if direction is None and directions is None: + directions = ["minimize"] + elif direction is not None and directions is not None: + raise ValueError("Specify only one of `direction` and `directions`.") + elif direction is not None: + if isinstance(direction, Sequence) and not isinstance(direction, str): + raise ValueError( + "Use `directions` instead of `direction` for multi-objective optimization." + ) + directions = [direction] + elif directions is not None: + directions = list(directions) + else: + assert False + + if len(directions) < 1: + raise ValueError("The number of objectives must be greater than 0.") + elif any( + d not in ["minimize", "maximize", StudyDirection.MINIMIZE, StudyDirection.MAXIMIZE] + for d in directions + ): + raise ValueError( + f"`directions` must be a list of `minimize` or `maximize`, but got {directions}. " + "For single-objective optimization, please use `direction` instead of `directions`." + ) + + direction_objects = [ + d if isinstance(d, StudyDirection) else StudyDirection[d.upper()] for d in directions + ] + + storage = storages.get_storage(storage) + try: + study_id = storage.create_new_study(direction_objects, study_name) + except exceptions.DuplicatedStudyError: + if load_if_exists: + assert study_name is not None + + _logger.info( + "Using an existing study with name '{}' instead of " + "creating a new one.".format(study_name) + ) + study_id = storage.get_study_id_from_name(study_name) + else: + raise + + if sampler is None and len(direction_objects) > 1: + sampler = samplers.NSGAIISampler() + + study_name = storage.get_study_name_from_id(study_id) + study = Study(study_name=study_name, storage=storage, sampler=sampler, pruner=pruner) + + return study + + +@convert_positional_args( + previous_positional_arg_names=[ + "study_name", + "storage", + "sampler", + "pruner", + ], + deprecated_version="3.0.0", + removed_version="5.0.0", +) +def load_study( + *, + study_name: str | None, + storage: str | storages.BaseStorage, + sampler: "samplers.BaseSampler" | None = None, + pruner: pruners.BasePruner | None = None, +) -> Study: + """Load the existing :class:`~optuna.study.Study` that has the specified name. + + Example: + + .. testsetup:: + + import os + + if os.path.exists("example.db"): + raise RuntimeError("'example.db' already exists. Please remove it.") + + .. testcode:: + + import optuna + + + def objective(trial): + x = trial.suggest_float("x", 0, 10) + return x**2 + + + study = optuna.create_study(storage="sqlite:///example.db", study_name="my_study") + study.optimize(objective, n_trials=3) + + loaded_study = optuna.load_study(study_name="my_study", storage="sqlite:///example.db") + assert len(loaded_study.trials) == len(study.trials) + + .. testcleanup:: + + os.remove("example.db") + + Args: + study_name: + Study's name. Each study has a unique name as an identifier. If :obj:`None`, checks + whether the storage contains a single study, and if so loads that study. + ``study_name`` is required if there are multiple studies in the storage. + storage: + Database URL such as ``sqlite:///example.db``. Please see also the documentation of + :func:`~optuna.study.create_study` for further details. + sampler: + A sampler object that implements background algorithm for value suggestion. + If :obj:`None` is specified, :class:`~optuna.samplers.TPESampler` is used + as the default. See also :class:`~optuna.samplers`. + pruner: + A pruner object that decides early stopping of unpromising trials. + If :obj:`None` is specified, :class:`~optuna.pruners.MedianPruner` is used + as the default. See also :class:`~optuna.pruners`. + + Returns: + A :class:`~optuna.study.Study` object. + + See also: + :func:`optuna.load_study` is an alias of :func:`optuna.study.load_study`. + + """ + if study_name is None: + study_names = get_all_study_names(storage) + if len(study_names) != 1: + raise ValueError( + f"Could not determine the study name since the storage {storage} does not " + "contain exactly 1 study. Specify `study_name`." + ) + study_name = study_names[0] + _logger.info( + f"Study name was omitted but trying to load '{study_name}' because that was the only " + "study found in the storage." + ) + + study = Study(study_name=study_name, storage=storage, sampler=sampler, pruner=pruner) + if sampler is None and len(study.directions) > 1: + study.sampler = samplers.NSGAIISampler() + return study + + +@convert_positional_args( + previous_positional_arg_names=[ + "study_name", + "storage", + ], + deprecated_version="3.0.0", + removed_version="5.0.0", +) +def delete_study( + *, + study_name: str, + storage: str | storages.BaseStorage, +) -> None: + """Delete a :class:`~optuna.study.Study` object. + + Example: + + .. testsetup:: + + import os + + if os.path.exists("example.db"): + raise RuntimeError("'example.db' already exists. Please remove it.") + + .. testcode:: + + import optuna + + + def objective(trial): + x = trial.suggest_float("x", -10, 10) + return (x - 2) ** 2 + + + study = optuna.create_study(study_name="example-study", storage="sqlite:///example.db") + study.optimize(objective, n_trials=3) + + optuna.delete_study(study_name="example-study", storage="sqlite:///example.db") + + .. testcleanup:: + + os.remove("example.db") + + Args: + study_name: + Study's name. + storage: + Database URL such as ``sqlite:///example.db``. Please see also the documentation of + :func:`~optuna.study.create_study` for further details. + + See also: + :func:`optuna.delete_study` is an alias of :func:`optuna.study.delete_study`. + + """ + + storage = storages.get_storage(storage) + study_id = storage.get_study_id_from_name(study_name) + storage.delete_study(study_id) + + +@convert_positional_args( + previous_positional_arg_names=[ + "from_study_name", + "from_storage", + "to_storage", + "to_study_name", + ], + warning_stacklevel=3, + deprecated_version="3.0.0", + removed_version="5.0.0", +) +def copy_study( + *, + from_study_name: str, + from_storage: str | storages.BaseStorage, + to_storage: str | storages.BaseStorage, + to_study_name: str | None = None, +) -> None: + """Copy study from one storage to another. + + The direction(s) of the objective(s) in the study, trials, user attributes and system + attributes are copied. + + .. note:: + :func:`~optuna.copy_study` copies a study even if the optimization is working on. + It means users will get a copied study that contains a trial that is not finished. + + Example: + + .. testsetup:: + + import os + + if os.path.exists("example.db"): + raise RuntimeError("'example.db' already exists. Please remove it.") + if os.path.exists("example_copy.db"): + raise RuntimeError("'example_copy.db' already exists. Please remove it.") + + .. testcode:: + + import optuna + + + def objective(trial): + x = trial.suggest_float("x", -10, 10) + return (x - 2) ** 2 + + + study = optuna.create_study( + study_name="example-study", + storage="sqlite:///example.db", + ) + study.optimize(objective, n_trials=3) + + optuna.copy_study( + from_study_name="example-study", + from_storage="sqlite:///example.db", + to_storage="sqlite:///example_copy.db", + ) + + study = optuna.load_study( + study_name=None, + storage="sqlite:///example_copy.db", + ) + + .. testcleanup:: + + os.remove("example.db") + os.remove("example_copy.db") + + Args: + from_study_name: + Name of study. + from_storage: + Source database URL such as ``sqlite:///example.db``. Please see also the + documentation of :func:`~optuna.study.create_study` for further details. + to_storage: + Destination database URL. + to_study_name: + Name of the created study. If omitted, ``from_study_name`` is used. + + Raises: + :class:`~optuna.exceptions.DuplicatedStudyError`: + If a study with a conflicting name already exists in the destination storage. + + """ + + from_study = load_study(study_name=from_study_name, storage=from_storage) + to_study = create_study( + study_name=to_study_name or from_study_name, + storage=to_storage, + directions=from_study.directions, + load_if_exists=False, + ) + + for key, value in from_study._storage.get_study_system_attrs(from_study._study_id).items(): + to_study._storage.set_study_system_attr(to_study._study_id, key, value) + + for key, value in from_study.user_attrs.items(): + to_study.set_user_attr(key, value) + + # Trials are deep copied on `add_trials`. + to_study.add_trials(from_study.get_trials(deepcopy=False)) + + +def get_all_study_summaries( + storage: str | storages.BaseStorage, include_best_trial: bool = True +) -> list[StudySummary]: + """Get all history of studies stored in a specified storage. + + Example: + + .. testsetup:: + + import os + + if os.path.exists("example.db"): + raise RuntimeError("'example.db' already exists. Please remove it.") + + .. testcode:: + + import optuna + + + def objective(trial): + x = trial.suggest_float("x", -10, 10) + return (x - 2) ** 2 + + + study = optuna.create_study(study_name="example-study", storage="sqlite:///example.db") + study.optimize(objective, n_trials=3) + + study_summaries = optuna.study.get_all_study_summaries(storage="sqlite:///example.db") + assert len(study_summaries) == 1 + + study_summary = study_summaries[0] + assert study_summary.study_name == "example-study" + + .. testcleanup:: + + os.remove("example.db") + + Args: + storage: + Database URL such as ``sqlite:///example.db``. Please see also the documentation of + :func:`~optuna.study.create_study` for further details. + include_best_trial: + Include the best trials if exist. It potentially increases the number of queries and + may take longer to fetch summaries depending on the storage. + + Returns: + List of study history summarized as :class:`~optuna.study.StudySummary` objects. + + See also: + :func:`optuna.get_all_study_summaries` is an alias of + :func:`optuna.study.get_all_study_summaries`. + + """ + + storage = storages.get_storage(storage) + frozen_studies = storage.get_all_studies() + study_summaries = [] + + for s in frozen_studies: + all_trials = storage.get_all_trials(s._study_id) + completed_trials = [t for t in all_trials if t.state == TrialState.COMPLETE] + + n_trials = len(all_trials) + + if len(s.directions) == 1: + direction = s.direction + directions = None + if include_best_trial and len(completed_trials) != 0: + if direction == StudyDirection.MAXIMIZE: + best_trial = max(completed_trials, key=lambda t: cast(float, t.value)) + else: + best_trial = min(completed_trials, key=lambda t: cast(float, t.value)) + else: + best_trial = None + else: + direction = None + directions = s.directions + best_trial = None + + datetime_start = min( + [t.datetime_start for t in all_trials if t.datetime_start is not None], default=None + ) + + study_summaries.append( + StudySummary( + study_name=s.study_name, + direction=direction, + best_trial=best_trial, + user_attrs=s.user_attrs, + system_attrs=s.system_attrs, + n_trials=n_trials, + datetime_start=datetime_start, + study_id=s._study_id, + directions=directions, + ) + ) + + return study_summaries + + +def get_all_study_names(storage: str | storages.BaseStorage) -> list[str]: + """Get all study names stored in a specified storage. + + Example: + + .. testsetup:: + + import os + + if os.path.exists("example.db"): + raise RuntimeError("'example.db' already exists. Please remove it.") + + .. testcode:: + + import optuna + + + def objective(trial): + x = trial.suggest_float("x", -10, 10) + return (x - 2) ** 2 + + + study = optuna.create_study(study_name="example-study", storage="sqlite:///example.db") + study.optimize(objective, n_trials=3) + + study_names = optuna.study.get_all_study_names(storage="sqlite:///example.db") + assert len(study_names) == 1 + + assert study_names[0] == "example-study" + + .. testcleanup:: + + os.remove("example.db") + + Args: + storage: + Database URL such as ``sqlite:///example.db``. Please see also the documentation of + :func:`~optuna.study.create_study` for further details. + + Returns: + List of all study names in the storage. + + See also: + :func:`optuna.get_all_study_names` is an alias of + :func:`optuna.study.get_all_study_names`. + + """ + + storage = storages.get_storage(storage) + study_names = [study.study_name for study in storage.get_all_studies()] + + return study_names diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/terminator/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/terminator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..825d43afaf5b8d90459eebcc3e6528fb8c437e19 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/terminator/__init__.py @@ -0,0 +1,28 @@ +from optuna.terminator.callback import TerminatorCallback +from optuna.terminator.erroreval import BaseErrorEvaluator +from optuna.terminator.erroreval import CrossValidationErrorEvaluator +from optuna.terminator.erroreval import report_cross_validation_scores +from optuna.terminator.erroreval import StaticErrorEvaluator +from optuna.terminator.improvement.emmr import EMMREvaluator +from optuna.terminator.improvement.evaluator import BaseImprovementEvaluator +from optuna.terminator.improvement.evaluator import BestValueStagnationEvaluator +from optuna.terminator.improvement.evaluator import RegretBoundEvaluator +from optuna.terminator.median_erroreval import MedianErrorEvaluator +from optuna.terminator.terminator import BaseTerminator +from optuna.terminator.terminator import Terminator + + +__all__ = [ + "TerminatorCallback", + "BaseErrorEvaluator", + "CrossValidationErrorEvaluator", + "report_cross_validation_scores", + "StaticErrorEvaluator", + "MedianErrorEvaluator", + "BaseImprovementEvaluator", + "BestValueStagnationEvaluator", + "RegretBoundEvaluator", + "EMMREvaluator", + "BaseTerminator", + "Terminator", +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/terminator/callback.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/terminator/callback.py new file mode 100644 index 0000000000000000000000000000000000000000..ae9ec2ab64f6558df9ab827e2475329eb63ff4a7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/terminator/callback.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from optuna._experimental import experimental_class +from optuna.logging import get_logger +from optuna.study.study import Study +from optuna.terminator.terminator import BaseTerminator +from optuna.terminator.terminator import Terminator +from optuna.trial import FrozenTrial + + +_logger = get_logger(__name__) + + +@experimental_class("3.2.0") +class TerminatorCallback: + """A callback that terminates the optimization using Terminator. + + This class implements a callback which wraps :class:`~optuna.terminator.Terminator` + so that it can be used with the :func:`~optuna.study.Study.optimize` method. + + Args: + terminator: + A terminator object which determines whether to terminate the optimization by + assessing the room for optimization and statistical error. Defaults to a + :class:`~optuna.terminator.Terminator` object with default + ``improvement_evaluator`` and ``error_evaluator``. + + Example: + + .. testcode:: + + from sklearn.datasets import load_wine + from sklearn.ensemble import RandomForestClassifier + from sklearn.model_selection import cross_val_score + from sklearn.model_selection import KFold + + import optuna + from optuna.terminator import TerminatorCallback + from optuna.terminator import report_cross_validation_scores + + + def objective(trial): + X, y = load_wine(return_X_y=True) + + clf = RandomForestClassifier( + max_depth=trial.suggest_int("max_depth", 2, 32), + min_samples_split=trial.suggest_float("min_samples_split", 0, 1), + criterion=trial.suggest_categorical("criterion", ("gini", "entropy")), + ) + + scores = cross_val_score(clf, X, y, cv=KFold(n_splits=5, shuffle=True)) + report_cross_validation_scores(trial, scores) + return scores.mean() + + + study = optuna.create_study(direction="maximize") + terminator = TerminatorCallback() + study.optimize(objective, n_trials=50, callbacks=[terminator]) + + .. seealso:: + Please refer to :class:`~optuna.terminator.Terminator` for the details of + the terminator mechanism. + """ + + def __init__(self, terminator: BaseTerminator | None = None) -> None: + self._terminator = terminator or Terminator() + + def __call__(self, study: Study, trial: FrozenTrial) -> None: + should_terminate = self._terminator.should_terminate(study=study) + + if should_terminate: + _logger.info("The study has been stopped by the terminator.") + study.stop() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/terminator/median_erroreval.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/terminator/median_erroreval.py new file mode 100644 index 0000000000000000000000000000000000000000..d956945fe0129f047e38d5c9441ab393558b0434 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/terminator/median_erroreval.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +import sys + +import numpy as np + +from optuna._experimental import experimental_class +from optuna.study import StudyDirection +from optuna.terminator.erroreval import BaseErrorEvaluator +from optuna.terminator.improvement.evaluator import BaseImprovementEvaluator +from optuna.trial import FrozenTrial +from optuna.trial._state import TrialState + + +@experimental_class("4.0.0") +class MedianErrorEvaluator(BaseErrorEvaluator): + """An error evaluator that returns the ratio to initial median. + + This error evaluator is introduced as a heuristics in the following paper: + + - `A stopping criterion for Bayesian optimization by the gap of expected minimum simple + regrets `__ + + Args: + paired_improvement_evaluator: + The ``improvement_evaluator`` instance which is set with this ``error_evaluator``. + warm_up_trials: + A parameter specifies the number of initial trials to be discarded before + the calculation of median. Default to 10. + In optuna, the first 10 trials are often random sampling. + The ``warm_up_trials`` can exclude them from the calculation. + n_initial_trials: + A parameter specifies the number of initial trials considered in the calculation of + median after ``warm_up_trials``. Default to 20. + threshold_ratio: + A parameter specifies the ratio between the threshold and initial median. + Default to 0.01. + """ + + def __init__( + self, + paired_improvement_evaluator: BaseImprovementEvaluator, + warm_up_trials: int = 10, + n_initial_trials: int = 20, + threshold_ratio: float = 0.01, + ) -> None: + if warm_up_trials < 0: + raise ValueError("`warm_up_trials` is expected to be a non-negative integer.") + if n_initial_trials <= 0: + raise ValueError("`n_initial_trials` is expected to be a positive integer.") + if threshold_ratio <= 0.0 or not np.isfinite(threshold_ratio): + raise ValueError("`threshold_ratio_to_initial_median` is expected to be a positive.") + + self._paired_improvement_evaluator = paired_improvement_evaluator + self._warm_up_trials = warm_up_trials + self._n_initial_trials = n_initial_trials + self._threshold_ratio = threshold_ratio + self._threshold: float | None = None + + def evaluate( + self, + trials: list[FrozenTrial], + study_direction: StudyDirection, + ) -> float: + + if self._threshold is not None: + return self._threshold + + trials = [trial for trial in trials if trial.state == TrialState.COMPLETE] + if len(trials) < (self._warm_up_trials + self._n_initial_trials): + return ( + -sys.float_info.min + ) # Do not terminate. It assumes that improvement must non-negative. + trials.sort(key=lambda trial: trial.number) + criteria = [] + for i in range(1, self._n_initial_trials + 1): + criteria.append( + self._paired_improvement_evaluator.evaluate( + trials[self._warm_up_trials : self._warm_up_trials + i], study_direction + ) + ) + criteria.sort() + self._threshold = criteria[len(criteria) // 2] + assert self._threshold is not None + self._threshold = min(sys.float_info.max, self._threshold * self._threshold_ratio) + return self._threshold diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/version.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/version.py new file mode 100644 index 0000000000000000000000000000000000000000..9faa2c2dd5cf37635297bd0798312a0fa756f462 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/optuna/version.py @@ -0,0 +1 @@ +__version__ = "4.5.0" diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/INSTALLER b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/METADATA b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..a11c62a144114db57d320ba8fc560dea181b5cad --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/METADATA @@ -0,0 +1,243 @@ +Metadata-Version: 2.4 +Name: SQLAlchemy +Version: 2.0.44 +Summary: Database Abstraction Library +Home-page: https://www.sqlalchemy.org +Author: Mike Bayer +Author-email: mike_mp@zzzcomputing.com +License: MIT +Project-URL: Documentation, https://docs.sqlalchemy.org +Project-URL: Issue Tracker, https://github.com/sqlalchemy/sqlalchemy/ +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +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 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Database :: Front-Ends +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: importlib-metadata; python_version < "3.8" +Requires-Dist: greenlet>=1; platform_machine == "aarch64" or (platform_machine == "ppc64le" or (platform_machine == "x86_64" or (platform_machine == "amd64" or (platform_machine == "AMD64" or (platform_machine == "win32" or platform_machine == "WIN32"))))) +Requires-Dist: typing-extensions>=4.6.0 +Provides-Extra: asyncio +Requires-Dist: greenlet>=1; extra == "asyncio" +Provides-Extra: mypy +Requires-Dist: mypy>=0.910; extra == "mypy" +Provides-Extra: mssql +Requires-Dist: pyodbc; extra == "mssql" +Provides-Extra: mssql-pymssql +Requires-Dist: pymssql; extra == "mssql-pymssql" +Provides-Extra: mssql-pyodbc +Requires-Dist: pyodbc; extra == "mssql-pyodbc" +Provides-Extra: mysql +Requires-Dist: mysqlclient>=1.4.0; extra == "mysql" +Provides-Extra: mysql-connector +Requires-Dist: mysql-connector-python; extra == "mysql-connector" +Provides-Extra: mariadb-connector +Requires-Dist: mariadb!=1.1.10,!=1.1.2,!=1.1.5,>=1.0.1; extra == "mariadb-connector" +Provides-Extra: oracle +Requires-Dist: cx_oracle>=8; extra == "oracle" +Provides-Extra: oracle-oracledb +Requires-Dist: oracledb>=1.0.1; extra == "oracle-oracledb" +Provides-Extra: postgresql +Requires-Dist: psycopg2>=2.7; extra == "postgresql" +Provides-Extra: postgresql-pg8000 +Requires-Dist: pg8000>=1.29.1; extra == "postgresql-pg8000" +Provides-Extra: postgresql-asyncpg +Requires-Dist: greenlet>=1; extra == "postgresql-asyncpg" +Requires-Dist: asyncpg; extra == "postgresql-asyncpg" +Provides-Extra: postgresql-psycopg2binary +Requires-Dist: psycopg2-binary; extra == "postgresql-psycopg2binary" +Provides-Extra: postgresql-psycopg2cffi +Requires-Dist: psycopg2cffi; extra == "postgresql-psycopg2cffi" +Provides-Extra: postgresql-psycopg +Requires-Dist: psycopg>=3.0.7; extra == "postgresql-psycopg" +Provides-Extra: postgresql-psycopgbinary +Requires-Dist: psycopg[binary]>=3.0.7; extra == "postgresql-psycopgbinary" +Provides-Extra: pymysql +Requires-Dist: pymysql; extra == "pymysql" +Provides-Extra: aiomysql +Requires-Dist: greenlet>=1; extra == "aiomysql" +Requires-Dist: aiomysql>=0.2.0; extra == "aiomysql" +Provides-Extra: aioodbc +Requires-Dist: greenlet>=1; extra == "aioodbc" +Requires-Dist: aioodbc; extra == "aioodbc" +Provides-Extra: asyncmy +Requires-Dist: greenlet>=1; extra == "asyncmy" +Requires-Dist: asyncmy!=0.2.4,!=0.2.6,>=0.2.3; extra == "asyncmy" +Provides-Extra: aiosqlite +Requires-Dist: greenlet>=1; extra == "aiosqlite" +Requires-Dist: aiosqlite; extra == "aiosqlite" +Requires-Dist: typing_extensions!=3.10.0.1; extra == "aiosqlite" +Provides-Extra: sqlcipher +Requires-Dist: sqlcipher3_binary; extra == "sqlcipher" +Dynamic: license-file + +SQLAlchemy +========== + +|PyPI| |Python| |Downloads| + +.. |PyPI| image:: https://img.shields.io/pypi/v/sqlalchemy + :target: https://pypi.org/project/sqlalchemy + :alt: PyPI + +.. |Python| image:: https://img.shields.io/pypi/pyversions/sqlalchemy + :target: https://pypi.org/project/sqlalchemy + :alt: PyPI - Python Version + +.. |Downloads| image:: https://static.pepy.tech/badge/sqlalchemy/month + :target: https://pepy.tech/project/sqlalchemy + :alt: PyPI - Downloads + + +The Python SQL Toolkit and Object Relational Mapper + +Introduction +------------- + +SQLAlchemy is the Python SQL toolkit and Object Relational Mapper +that gives application developers the full power and +flexibility of SQL. SQLAlchemy provides a full suite +of well known enterprise-level persistence patterns, +designed for efficient and high-performing database +access, adapted into a simple and Pythonic domain +language. + +Major SQLAlchemy features include: + +* An industrial strength ORM, built + from the core on the identity map, unit of work, + and data mapper patterns. These patterns + allow transparent persistence of objects + using a declarative configuration system. + Domain models + can be constructed and manipulated naturally, + and changes are synchronized with the + current transaction automatically. +* A relationally-oriented query system, exposing + the full range of SQL's capabilities + explicitly, including joins, subqueries, + correlation, and most everything else, + in terms of the object model. + Writing queries with the ORM uses the same + techniques of relational composition you use + when writing SQL. While you can drop into + literal SQL at any time, it's virtually never + needed. +* A comprehensive and flexible system + of eager loading for related collections and objects. + Collections are cached within a session, + and can be loaded on individual access, all + at once using joins, or by query per collection + across the full result set. +* A Core SQL construction system and DBAPI + interaction layer. The SQLAlchemy Core is + separate from the ORM and is a full database + abstraction layer in its own right, and includes + an extensible Python-based SQL expression + language, schema metadata, connection pooling, + type coercion, and custom types. +* All primary and foreign key constraints are + assumed to be composite and natural. Surrogate + integer primary keys are of course still the + norm, but SQLAlchemy never assumes or hardcodes + to this model. +* Database introspection and generation. Database + schemas can be "reflected" in one step into + Python structures representing database metadata; + those same structures can then generate + CREATE statements right back out - all within + the Core, independent of the ORM. + +SQLAlchemy's philosophy: + +* SQL databases behave less and less like object + collections the more size and performance start to + matter; object collections behave less and less like + tables and rows the more abstraction starts to matter. + SQLAlchemy aims to accommodate both of these + principles. +* An ORM doesn't need to hide the "R". A relational + database provides rich, set-based functionality + that should be fully exposed. SQLAlchemy's + ORM provides an open-ended set of patterns + that allow a developer to construct a custom + mediation layer between a domain model and + a relational schema, turning the so-called + "object relational impedance" issue into + a distant memory. +* The developer, in all cases, makes all decisions + regarding the design, structure, and naming conventions + of both the object model as well as the relational + schema. SQLAlchemy only provides the means + to automate the execution of these decisions. +* With SQLAlchemy, there's no such thing as + "the ORM generated a bad query" - you + retain full control over the structure of + queries, including how joins are organized, + how subqueries and correlation is used, what + columns are requested. Everything SQLAlchemy + does is ultimately the result of a developer-initiated + decision. +* Don't use an ORM if the problem doesn't need one. + SQLAlchemy consists of a Core and separate ORM + component. The Core offers a full SQL expression + language that allows Pythonic construction + of SQL constructs that render directly to SQL + strings for a target database, returning + result sets that are essentially enhanced DBAPI + cursors. +* Transactions should be the norm. With SQLAlchemy's + ORM, nothing goes to permanent storage until + commit() is called. SQLAlchemy encourages applications + to create a consistent means of delineating + the start and end of a series of operations. +* Never render a literal value in a SQL statement. + Bound parameters are used to the greatest degree + possible, allowing query optimizers to cache + query plans effectively and making SQL injection + attacks a non-issue. + +Documentation +------------- + +Latest documentation is at: + +https://www.sqlalchemy.org/docs/ + +Installation / Requirements +--------------------------- + +Full documentation for installation is at +`Installation `_. + +Getting Help / Development / Bug reporting +------------------------------------------ + +Please refer to the `SQLAlchemy Community Guide `_. + +Code of Conduct +--------------- + +Above all, SQLAlchemy places great emphasis on polite, thoughtful, and +constructive communication between users and developers. +Please see our current Code of Conduct at +`Code of Conduct `_. + +License +------- + +SQLAlchemy is distributed under the `MIT license +`_. + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/RECORD b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f25cce24afa6b5d2bad936e2f89b22d043b2fe42 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/RECORD @@ -0,0 +1,276 @@ +sqlalchemy-2.0.44.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +sqlalchemy-2.0.44.dist-info/METADATA,sha256=5i0Vw08ZPOOu7xrG_G4uSM62FgSenaiV3JAn1J2_lR8,9547 +sqlalchemy-2.0.44.dist-info/RECORD,, +sqlalchemy-2.0.44.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sqlalchemy-2.0.44.dist-info/WHEEL,sha256=DTnKjM5OInJxWADod3iQyWxWcdG-eRwxzGww236swpY,151 +sqlalchemy-2.0.44.dist-info/licenses/LICENSE,sha256=mCFyC1jUpWW2EyEAeorUOraZGjlZ5mzV203Z6uacffw,1100 +sqlalchemy-2.0.44.dist-info/top_level.txt,sha256=rp-ZgB7D8G11ivXON5VGPjupT1voYmWqkciDt5Uaw_Q,11 +sqlalchemy/__init__.py,sha256=wmYjlHig7rjeBp7HFRCxNNBOkHIbeM_wZWQUdfB66Z0,12659 +sqlalchemy/connectors/__init__.py,sha256=YeSHsOB0YhdM6jZUvHFQFwKqNXO02MlklmGW0yCywjI,476 +sqlalchemy/connectors/aioodbc.py,sha256=-OKbnvR-kLCKHyrOIBkAZwTASAbQZ5qmrozm0dwbtNE,5577 +sqlalchemy/connectors/asyncio.py,sha256=tcjJ-azCTrizebEzSsEQK7Qm_OpUHyGw94k9Vin7Yy0,13058 +sqlalchemy/connectors/pyodbc.py,sha256=ZGWBmYYYVgqUHjex3d_lYHZyAhQJGowp9cWGYnj1200,8618 +sqlalchemy/cyextension/__init__.py,sha256=4npVIjitKfUs0NQ6f3UdQBDq4ipJ0_ZNB2mpKqtc5ik,244 +sqlalchemy/cyextension/collections.cpython-310-x86_64-linux-gnu.so,sha256=Rduem6jYybrXSI4iuR5GhEfkX3s3g4gI2OHyQJrgiO0,1998144 +sqlalchemy/cyextension/collections.pyx,sha256=L7DZ3DGKpgw2MT2ZZRRxCnrcyE5pU1NAFowWgAzQPEc,12571 +sqlalchemy/cyextension/immutabledict.cpython-310-x86_64-linux-gnu.so,sha256=_qr_V2B0bmG8p3_mZQ57g3N_tCuuZbNqVIVrxWu3x0k,678392 +sqlalchemy/cyextension/immutabledict.pxd,sha256=3x3-rXG5eRQ7bBnktZ-OJ9-6ft8zToPmTDOd92iXpB0,291 +sqlalchemy/cyextension/immutabledict.pyx,sha256=KfDTYbTfebstE8xuqAtuXsHNAK0_b5q_ymUiinUe_xs,3535 +sqlalchemy/cyextension/processors.cpython-310-x86_64-linux-gnu.so,sha256=4mb4RLxVEImMHWn0uBu_GZxqo47u8xX4XNpfCwawCcE,543408 +sqlalchemy/cyextension/processors.pyx,sha256=R1rHsGLEaGeBq5VeCydjClzYlivERIJ9B-XLOJlf2MQ,1792 +sqlalchemy/cyextension/resultproxy.cpython-310-x86_64-linux-gnu.so,sha256=DuiZiOuYhebl8uz8y91OioRjvkW_26zuINTr96_RVc8,547320 +sqlalchemy/cyextension/resultproxy.pyx,sha256=eWLdyBXiBy_CLQrF5ScfWJm7X0NeelscSXedtj1zv9Q,2725 +sqlalchemy/cyextension/util.cpython-310-x86_64-linux-gnu.so,sha256=mXibbYJYAGVWV4DuaDYKY4wsA3gn8SeIzW5u913cNoc,822792 +sqlalchemy/cyextension/util.pyx,sha256=Tt5VwTUtO3YKQK2PHfYOLhV2Jr5GMRJcp2DzH4fjGOs,2569 +sqlalchemy/dialects/__init__.py,sha256=oOkVOr98g-6jxaUXld8szIgxkXMBae5IPfAzBrcpLaw,1798 +sqlalchemy/dialects/_typing.py,sha256=8YwrkOa8IvmBojwwegbL5mL_0UAuzdqYiKHKANpvHMw,971 +sqlalchemy/dialects/mssql/__init__.py,sha256=6t_aNpgbMLdPE9gpHYTf9o6QfVavncztRLbr21l2NaY,1880 +sqlalchemy/dialects/mssql/aioodbc.py,sha256=4CmhwIkZrabpG-r7_ogRVajD-nhRZSFJ0Swz2d0jIHM,2021 +sqlalchemy/dialects/mssql/base.py,sha256=u0auYPbr60eRK3ZWdo2whp4XWNOMV5HWcKmh2bHX2WQ,134119 +sqlalchemy/dialects/mssql/information_schema.py,sha256=CDNPC1ZDjj-DumMgzZdm1oNY6FiO-_Fn2DWJuPVnni0,8963 +sqlalchemy/dialects/mssql/json.py,sha256=F53pibuOVRzgDtjoclOI7LnkKXNVsaVfJyBH1XAhyDo,4756 +sqlalchemy/dialects/mssql/provision.py,sha256=P1tqxZ4f6Oeqn2gNi7dXl82LRLCg1-OB4eWiZc6CHek,5593 +sqlalchemy/dialects/mssql/pymssql.py,sha256=C7yAs3Pw81W1KTVNc6_0sHQuYlJ5iH82vKByY4TkB1g,4097 +sqlalchemy/dialects/mssql/pyodbc.py,sha256=CnO7KDWxbxb7AoZhp_PMDBvVSMuzwq1h4Cav2IWFWDo,27173 +sqlalchemy/dialects/mysql/__init__.py,sha256=ropOMUWrAcL-Q7h-9jQ_tb3ISAFIsNRQ8YVXvn0URl0,2206 +sqlalchemy/dialects/mysql/aiomysql.py,sha256=b33sq1MLkxt7PX2v_6grpYXGchfFlbkfeOL7JmFTe5k,7927 +sqlalchemy/dialects/mysql/asyncmy.py,sha256=y_4RpvbVitLOAKgEkdnLUcRP1NjWNA0G7dwlawLCwbw,7292 +sqlalchemy/dialects/mysql/base.py,sha256=V2CE2XB6eiFG3doNdzH3NZPhgXgt3OL7QN8F3dg_9Pg,137763 +sqlalchemy/dialects/mysql/cymysql.py,sha256=ihH4kZ273nvf0R0p8keD71ZIaTXRHyZePXMlobwgbpI,3215 +sqlalchemy/dialects/mysql/dml.py,sha256=VjnTobe_SBNF2RN6tvqa5LOn-9x4teVUyzUedZkOmdc,7768 +sqlalchemy/dialects/mysql/enumerated.py,sha256=si2hGv5jMNGS78n_JDgswIhbBZuTqjwbxjiWg5ZUdy4,10292 +sqlalchemy/dialects/mysql/expression.py,sha256=C8LhU-CM6agqKCS1tl1_ChSqwZbqt3zP_dSGBqgBgLg,4241 +sqlalchemy/dialects/mysql/json.py,sha256=ckYT_lihvqr28iHJTUUwvPPUIoYVLL_wUXWFDTCna_M,2806 +sqlalchemy/dialects/mysql/mariadb.py,sha256=yaiZnnbjfrBqHm1ykaRSFYKrrYUqu-GBYvt97EGYSzs,1886 +sqlalchemy/dialects/mysql/mariadbconnector.py,sha256=lJuS3euMlVBbJDJ10ntqe3TnrjzneLEUlE8sLZl6Qoc,10385 +sqlalchemy/dialects/mysql/mysqlconnector.py,sha256=aaAiF32rQVoLNVIdgGKHMsnMei--0ig3OqmhWq45MrA,10097 +sqlalchemy/dialects/mysql/mysqldb.py,sha256=8wIxcxQxT-X6nywLJkjg9_JdIKGYOhlrtVL8lP_WFcM,9943 +sqlalchemy/dialects/mysql/provision.py,sha256=MaQ9eeHnRL4EXAebIInwarCIiDbYcz_sMCss3wyV12Q,3717 +sqlalchemy/dialects/mysql/pymysql.py,sha256=Qlc9XToIqAfHz0c_ODs97uk1TlV1ZrEl_TidTjoeByU,4886 +sqlalchemy/dialects/mysql/pyodbc.py,sha256=v-Zo4M7blxdff--KJiIantCwbPO6H-GBkNCTN4nBgU4,5111 +sqlalchemy/dialects/mysql/reflection.py,sha256=CBxBiv1mCLLNHz-I8hgJKACTF3K0eYEpWd0ndCBCq5I,24690 +sqlalchemy/dialects/mysql/reserved_words.py,sha256=iG6zb78sn-RdqWQRk2F_Tuufk5tUodkcoHbxTdgZYkw,9236 +sqlalchemy/dialects/mysql/types.py,sha256=lAkkNRVPBHP8H7AQQ7NykfJ8YxgdUDAHkfd7qD-Lwvo,26459 +sqlalchemy/dialects/oracle/__init__.py,sha256=5qrJcFTF3vgB9B4PkwBJj3iXE7P57LdaHNkxMa1NXug,1898 +sqlalchemy/dialects/oracle/base.py,sha256=zEl885-lRs07FGdWFuSzBfa1FqrUPT7l2wpcBr9joIs,139156 +sqlalchemy/dialects/oracle/cx_oracle.py,sha256=mYrXD0nJzuTY1h878b50fNXIUBgjc9Q1LJjjY1VHx3w,56717 +sqlalchemy/dialects/oracle/dictionary.py,sha256=J7tGVE0KyUPZKpPLOary3HdDq1DWd29arF5udLgv8_o,19519 +sqlalchemy/dialects/oracle/oracledb.py,sha256=Akoz130NxGzIrxGAsuuRl8QnmvIineoytHvTXDE2vP0,33736 +sqlalchemy/dialects/oracle/provision.py,sha256=ga1gNQZlXZKk7DYuYegllUejJxZXRKDGa7dbi_S_poc,8313 +sqlalchemy/dialects/oracle/types.py,sha256=axN6Yidx9tGRIUAbDpBrhMWXE-C8jSllFpTghpGOOzU,9058 +sqlalchemy/dialects/oracle/vector.py,sha256=YtN7E5TbDIQR2FCICaSeeaOnvzHP_O0mXNq1gk02S4Q,10874 +sqlalchemy/dialects/postgresql/__init__.py,sha256=kD8W-SV5e2CesvWg2MQAtncXuZFwGPfR_UODvmRXE08,3892 +sqlalchemy/dialects/postgresql/_psycopg_common.py,sha256=h4JmkHWxy_Nspn6Bi9YKpa9l0OkwInwQzYKue-fJnVA,5783 +sqlalchemy/dialects/postgresql/array.py,sha256=l2_KCBnf7ZALwEGsMfhhVUYVe1FlIufc0optdv97pO0,17279 +sqlalchemy/dialects/postgresql/asyncpg.py,sha256=SEalnEBX2gpqTWOuHZ0VABuW9kCiNwPo7mJdJxlLH1E,40977 +sqlalchemy/dialects/postgresql/base.py,sha256=RDuehOZL3hLPhq4_7G-91BgAM9LeToHiiIU-RjFGVmU,186421 +sqlalchemy/dialects/postgresql/dml.py,sha256=2SmyMeYveAgm7OnT_CJvwad2nh8BP37yT6gFs8dBYN8,12126 +sqlalchemy/dialects/postgresql/ext.py,sha256=voxpAz-zoCOO-fjpCzrw7UASzNIvdz2u4kFSuGcshlI,17347 +sqlalchemy/dialects/postgresql/hstore.py,sha256=wR4gmvfQWPssHwYTXEsPJTb4LkBS6x4e4XXE6smtDH4,11934 +sqlalchemy/dialects/postgresql/json.py,sha256=PtDqxFkMleCnm5zVxsQKBvR2J7stPUpf7reirtU2O0s,14315 +sqlalchemy/dialects/postgresql/named_types.py,sha256=D1WFTcxE-PKYRaB75gWvnAvpgGJRTcFkW9nSGpC4WCo,17812 +sqlalchemy/dialects/postgresql/operators.py,sha256=ay3ckNsWtqDjxDseTdKMGGqYVzST6lmfhbbYHG_bxCw,2808 +sqlalchemy/dialects/postgresql/pg8000.py,sha256=r6Lg5tgwuf4FE_RA_kHcfHPW5GXUdNWWr3E846Z4aI0,18743 +sqlalchemy/dialects/postgresql/pg_catalog.py,sha256=wnzFm9S0JFag1TBdySDJH3VOFSkJWmwAjVcIAQ25jHg,9999 +sqlalchemy/dialects/postgresql/provision.py,sha256=7pg9-nOnaK5XBzqByXNPuvi3rxtnRa3dJxdSPVq4eeA,5770 +sqlalchemy/dialects/postgresql/psycopg.py,sha256=XHE6sA_neg-PLZqXWSnlAEQ1mrX8y909Cb0YS3ZOxzw,23389 +sqlalchemy/dialects/postgresql/psycopg2.py,sha256=1KXw9RzsQEAXJazCBywdP5CwLu-HsCSDAD_Khc_rPTM,32032 +sqlalchemy/dialects/postgresql/psycopg2cffi.py,sha256=nKilJfvO9mJwk5NRw5iZDekKY5vi379tvdUJ2vn5eyQ,1756 +sqlalchemy/dialects/postgresql/ranges.py,sha256=rsvhfZ63OVtHHeBDXb_6hULg0HkVx18hkChfoznlhcg,32946 +sqlalchemy/dialects/postgresql/types.py,sha256=oKhDsFiITKbZcCP66L3dhif54pmsFvVfv-MZQWA3sYo,7629 +sqlalchemy/dialects/sqlite/__init__.py,sha256=6Xcz3nPsl8lqCcZ4-VzPRmkMrkKgAp2buKsClZelU7c,1182 +sqlalchemy/dialects/sqlite/aiosqlite.py,sha256=vvpx1KsFEcygAMi6esNxTp5VVqaKKeY4rIo1lM_EqKU,14682 +sqlalchemy/dialects/sqlite/base.py,sha256=OLpQu2q77KsOLXu7msnVc4TzwGsn2OczjZ9PEvMedFA,103795 +sqlalchemy/dialects/sqlite/dml.py,sha256=4N8qh06RuMphLoQgWw7wv5nXIrka57jIFvK2x9xTZqg,9138 +sqlalchemy/dialects/sqlite/json.py,sha256=A62xPyLRZxl2hvgTMM92jd_7jlw9UE_4Y6Udqt-8g04,2777 +sqlalchemy/dialects/sqlite/provision.py,sha256=VhqDjDALqxKQY_3Z3hjzkmPQJ-vtk2Dkk1A4qLTs-G8,5596 +sqlalchemy/dialects/sqlite/pysqlcipher.py,sha256=di8rYryfL0KAn3pRGepmunHyIRGy-4Hhr-2q_ehPzss,5371 +sqlalchemy/dialects/sqlite/pysqlite.py,sha256=AJl9z7zCoz59FxQm2_a3PANNlW4fen9gmnogNB77XKc,27792 +sqlalchemy/dialects/type_migration_guidelines.txt,sha256=-uHNdmYFGB7bzUNT6i8M5nb4j6j9YUKAtW4lcBZqsMg,8239 +sqlalchemy/engine/__init__.py,sha256=EF4haWCPu95WtWx1GzcHRJ_bBmtJMznno3I2TQ-ZIHE,2818 +sqlalchemy/engine/_py_processors.py,sha256=7QxgkVOd5h1Qd22qFh-pPZdM7RBRzNjj8lWAMWrilcI,3744 +sqlalchemy/engine/_py_row.py,sha256=yNdrZe36yw6mO7x0OEbG0dGojH7CQkNReIwn9LMUPUs,3787 +sqlalchemy/engine/_py_util.py,sha256=Nvd4pVdXRs89khRevK-Ux4Y9p2f2vnALboNrSwhqS1U,2465 +sqlalchemy/engine/base.py,sha256=aNp2tGNBWlBz2pHiOveJ3PeaJRDJlLknekUQ50MJDjU,123090 +sqlalchemy/engine/characteristics.py,sha256=PepmGApo1sL01dS1qtSbmHplu9ZCdtuSegiGI7L7NZY,4765 +sqlalchemy/engine/create.py,sha256=uIAiU-ANj7fk_6A3dbJw_SEU8Qfd0_YF8yEHGxD0r1g,33847 +sqlalchemy/engine/cursor.py,sha256=63KLS-IKKAYh2uADJytpT1i9-qpG9E0iVBIcKTtKkwI,76567 +sqlalchemy/engine/default.py,sha256=PpySUqbAliGjw80ZxhDdZwyiFEMCpNPcC1XmyJynyEE,85721 +sqlalchemy/engine/events.py,sha256=4_e6Ip32ar2Eb27R4ipamiKC-7Tpg4lVz3txabhT5Rc,37400 +sqlalchemy/engine/interfaces.py,sha256=fNGMov1byIOkPxh7dJervp-UUNyHHm3jpIB0HrCMucc,115119 +sqlalchemy/engine/mock.py,sha256=L07bSIkgEbIkih-pYvFWh7k7adHVp5tBFBekKlD7GHs,4156 +sqlalchemy/engine/processors.py,sha256=XK32bULBkuVVRa703u4-SrTCDi_a18Dxq1M09QFBEPw,2379 +sqlalchemy/engine/reflection.py,sha256=QNOAXvKtdzVddpbkMOyM380y3olKdJKQkmF0Bfwia-Q,75565 +sqlalchemy/engine/result.py,sha256=46J3rP0ZwDwsqU-4CAaEHXTpx8OqCEP9Dy4LQwtHUEg,77805 +sqlalchemy/engine/row.py,sha256=BPtAwsceiRxB9ANpDNM24uQ1M_Zs0xFkSXoKR_I8xyY,12031 +sqlalchemy/engine/strategies.py,sha256=3DixBdeTa824XjuID2o7UxIyg7GyNwdBI8hOOT0SQnc,439 +sqlalchemy/engine/url.py,sha256=GJfZo0KtbMtkOIHBPI_KcKASsyrI5UYkX-UoN62FQxc,31067 +sqlalchemy/engine/util.py,sha256=4OmXwFlmnq6_vBlfUBHnz5LrI_8bT3TwgynX4wcJfnw,5682 +sqlalchemy/event/__init__.py,sha256=WpEdt3ZLP23p1ufl0TyV0GN9TP9w9thIEWBpBZbBTNQ,1066 +sqlalchemy/event/api.py,sha256=x-VlMFJXzubD6fuB4VRTTeAJeeQNUZ5jHZXD1aL0Qkg,8109 +sqlalchemy/event/attr.py,sha256=WeGlNUKsCuEPbxq8cPMbLGnwzHhaILIsL9hy55ErW6g,21589 +sqlalchemy/event/base.py,sha256=g5eRGX4e949srBK2gUxLYM0RrDUdtUEPS2FT_9IKZeI,15254 +sqlalchemy/event/legacy.py,sha256=mAOrlQ7PrGZhdbj1Im9xRBAepFe5IzscbRCwD27ld_Q,8457 +sqlalchemy/event/registry.py,sha256=MNEMyR8HZhzQFgxk4Jk_Em6nXTihmGXiSIwPdUnalPM,11144 +sqlalchemy/events.py,sha256=VBRvtckn9JS3tfUfi6UstqUrvQ15J2xamcDByFysIrI,525 +sqlalchemy/exc.py,sha256=AjFBCrOl_V4vQdGegn72Y951RSRMPL6T5qjxnFTGFbM,23978 +sqlalchemy/ext/__init__.py,sha256=BkTNuOg454MpCY9QA3FLK8td7KQhD1W74fOEXxnWibE,322 +sqlalchemy/ext/associationproxy.py,sha256=QAo0GssILBua9wRNT3gajwZMEct3KCCu-gWVtAG-MA0,66442 +sqlalchemy/ext/asyncio/__init__.py,sha256=kTIfpwsHWhqZ-VMOBZFBq66kt1XeF0hNuwOToEDe4_Y,1317 +sqlalchemy/ext/asyncio/base.py,sha256=40VvRDZqVW_WQ1o-CRaB4c8Zx37rmiLGfQm4PNXWwdQ,9033 +sqlalchemy/ext/asyncio/engine.py,sha256=694-TJEy6jwGUOd7GFIvHfmlihvVvC_Ah3_k2o1BTiw,48481 +sqlalchemy/ext/asyncio/exc.py,sha256=npijuILDXH2p4Q5RzhHzutKwZ5CjtqTcP-U0h9TZUmk,639 +sqlalchemy/ext/asyncio/result.py,sha256=SOK74V-CEUA6ahn-zUCYsLLCYaGZaJiSvO4R2gz0_S8,30659 +sqlalchemy/ext/asyncio/scoping.py,sha256=wcOE6tUNKDIdHZb3INwke2L4OJvilcUft0q-2M4Bag8,52086 +sqlalchemy/ext/asyncio/session.py,sha256=Ge0rzdSK9V9RddRQc2bSjAhuxX8T2zv0GUdbURgMpRo,63259 +sqlalchemy/ext/automap.py,sha256=n88mktqvExwjqfsDu3yLIA4wbOIWUpQ1S35Uw3X6ffQ,61675 +sqlalchemy/ext/baked.py,sha256=w3SeRoqnPkIhPL2nRAxfVhyir2ypsiW4kmtmUGKs8qo,17753 +sqlalchemy/ext/compiler.py,sha256=f7o4qhUUldpsx4F1sQoUvdVaT2BhiemqNBCF4r_uQUo,20889 +sqlalchemy/ext/declarative/__init__.py,sha256=SuVflXOGDxx2sB2QSTqNEvqS0fyhOkh3-sy2lRsSOLA,1818 +sqlalchemy/ext/declarative/extensions.py,sha256=yHUPcztU-5E1JrNyELDFWKchAnaYK6Y9-dLcqyc1nUI,19531 +sqlalchemy/ext/horizontal_shard.py,sha256=vouIehpQAuwT0HXyWyynTL3m_gcBuLcB-X8lDB0uQ8U,16691 +sqlalchemy/ext/hybrid.py,sha256=CB96yxx1deII38FSsLczwq6Q9e0dKb51iyGVm9Xr6hI,52608 +sqlalchemy/ext/indexable.py,sha256=M12hFg8_OT8-Xt7vEskAJZqAgRA-VLl3cEYw8pHtHpA,11762 +sqlalchemy/ext/instrumentation.py,sha256=iCp89rvfK7buW0jJyzKTBDKyMsd06oTRJDItOk4OVSw,15707 +sqlalchemy/ext/mutable.py,sha256=MFpPDag1EL3iytawmawBJ8tBnXcnfR_wGlsduA61d9k,37164 +sqlalchemy/ext/mypy/__init__.py,sha256=yVNtoBDNeTl1sqRoA_fSY3o1g6M8NxqUVvAHPRLmFTw,241 +sqlalchemy/ext/mypy/apply.py,sha256=v_Svc1WiBz9yBXqBVBKoCuPGN286TfVmuuCVZPlbyzo,10591 +sqlalchemy/ext/mypy/decl_class.py,sha256=Nuca4ofHkASAkdqEQlULYB7iLm_KID7Mp384seDhVGg,17384 +sqlalchemy/ext/mypy/infer.py,sha256=29vgn22Hi8E8oIZL6UJCBl6oipiPSAQjxccCEkVb410,19367 +sqlalchemy/ext/mypy/names.py,sha256=_Q7J_F8KBSMHcVRw746fsosSJ3RAdDL6RpGAuGa-XJA,10480 +sqlalchemy/ext/mypy/plugin.py,sha256=9YHBp0Bwo92DbDZIUWwIr0hwXPcE4XvHs0-xshvSwUw,9750 +sqlalchemy/ext/mypy/util.py,sha256=CuW2fJ-g9YtkjcypzmrPRaFc-rAvQTzW5A2-w5VTANg,9960 +sqlalchemy/ext/orderinglist.py,sha256=LDHIRpMbl8w0mjDuz6phjnWhApmLRU0PrqouVUDTu-I,15163 +sqlalchemy/ext/serializer.py,sha256=_z95wZMTn3G3sCGN52gwzD4CuKjrhGMr5Eu8g9MxQNg,6169 +sqlalchemy/future/__init__.py,sha256=R1h8VBwMiIUdP3QHv_tFNby557425FJOAGhUoXGvCmc,512 +sqlalchemy/future/engine.py,sha256=2nJFBQAXAE8pqe1cs-D3JjC6wUX2ya2h2e_tniuaBq0,495 +sqlalchemy/inspection.py,sha256=qKEKG37N1OjxpQeVzob1q9VwWjBbjI1x0movJG7fYJ4,5063 +sqlalchemy/log.py,sha256=e_ztNUfZM08FmTWeXN9-doD5YKW44nXxgKCUxxNs6Ow,8607 +sqlalchemy/orm/__init__.py,sha256=Ahl2jG0r90eYkZ12lKYlcD84kUVam3lGN7SpRDGlEG4,8528 +sqlalchemy/orm/_orm_constructors.py,sha256=0pVhF06N8RHm3P418xpkZOBwKtrUsY7sQI2xz0f8zT4,105600 +sqlalchemy/orm/_typing.py,sha256=vaYRl4_K3n-sjc9u0Rb4eWWpBOoOi92--OHqaGogRvA,4973 +sqlalchemy/orm/attributes.py,sha256=oh9lKob8z-wChCQuAnW6MokQcaah6x9mNQI9_jbAX7Q,93117 +sqlalchemy/orm/base.py,sha256=J8rTiYm2xTyjTCJdSzaZRh8zasOiIK9FVXtFUits8AU,27501 +sqlalchemy/orm/bulk_persistence.py,sha256=evxOQKnfLRaByNXkudFyH8uFPmtVlCjP80CiIT4Lyb8,72984 +sqlalchemy/orm/clsregistry.py,sha256=-ZD3iO6qXropVH3gSf1nouKWG_xwMl_z5SE6sqOaYOA,17952 +sqlalchemy/orm/collections.py,sha256=cIoXIagPBv4B-TQN7BJssGwQcU0SgEhnKa6wLWsitys,52281 +sqlalchemy/orm/context.py,sha256=9OOJxvXJ_01Sd5-wny-WqVGtak4IA78TyLG_zMOHYmA,115082 +sqlalchemy/orm/decl_api.py,sha256=sSnBuMLYRntCYUnW4AEt61bQ22ZhWo6tMFBOFtCmdyQ,67842 +sqlalchemy/orm/decl_base.py,sha256=N13zJJ0Yejcwu0yOWz8WI38ab56WTeHioYr2PlRCal0,83486 +sqlalchemy/orm/dependency.py,sha256=eiYTsSnW94uGXEFQWj6-KFn25ivz_a2dPN3P6_nMou4,47619 +sqlalchemy/orm/descriptor_props.py,sha256=dh97zKu5-OHDNEhHA3H2YHwdpT8wVT06faeHDzED4pk,37795 +sqlalchemy/orm/dynamic.py,sha256=Z4GpcVL8rM8gi0bytQOZXw-_kKi-sExbRWGjU30dK3g,9816 +sqlalchemy/orm/evaluator.py,sha256=PKrUW1zEOvmv1XEgc_hBdYqNcyk4zjWr_rJhCEQBFIc,12353 +sqlalchemy/orm/events.py,sha256=lj0e8i9BD_xBJzkSMaJy7X3xAWSmTUpm8YEak13usBY,127231 +sqlalchemy/orm/exc.py,sha256=V7cUPl9Kw4qZHLyjOvU1C5WMJ-0MKpNN10qM0C0YG5Y,7636 +sqlalchemy/orm/identity.py,sha256=5NFtF9ZPZWAOmtOqCPyVX2-_pQq9A5XeN2ns3Wirpv8,9249 +sqlalchemy/orm/instrumentation.py,sha256=WhElvvOWOn3Fuc-Asc5HmcKDX6EzFtBleLJKPZEc5A0,24321 +sqlalchemy/orm/interfaces.py,sha256=C0RL0aOVB7E14EVp7MD9C55F2yrOfuOMZ0X-oZg3FCg,49072 +sqlalchemy/orm/loading.py,sha256=SMv9Q5bC-kdvsBpOqBNGqNWlL3I75fxByUeEpLC3qtg,58488 +sqlalchemy/orm/mapped_collection.py,sha256=FAqaTlOUCYqdws2KR_fW0T8mMWIrLuAxJGU5f4W1aGs,19682 +sqlalchemy/orm/mapper.py,sha256=-7q3rHqj3x_acv6prq3sDEXZmHx7kGSV9G-gW_JwaX4,171834 +sqlalchemy/orm/path_registry.py,sha256=tRk3osC5BmU7kkcKJCeeibpg2witjyVzO0rX0pu8vmc,25914 +sqlalchemy/orm/persistence.py,sha256=laKaHW7XsVDYhXfDLnxqAJ5lPB8vhUZ0lEhLvtx-fb4,61812 +sqlalchemy/orm/properties.py,sha256=V3Ega0yY-ypw-n5nbKxXN2KF6xtsixV4wFuUk4LKACU,31233 +sqlalchemy/orm/query.py,sha256=6WjzKAmAcmM8Wmk4NMM-tL25xikDvkNJZ9V8PHfFmYo,118858 +sqlalchemy/orm/relationships.py,sha256=t3yqixZ41chMVOnmelNaps7jwj5vwN9dZFSB0gKK9Pw,128763 +sqlalchemy/orm/scoping.py,sha256=67ww7tkd-GGrv42kzDXSJjPhkQr9nnNWM4t5igs1DyY,78124 +sqlalchemy/orm/session.py,sha256=pTa6xTK5cMTy0XBPJu4zmv4CK7MtUERXkCM9PA5XCxI,195401 +sqlalchemy/orm/state.py,sha256=1vtlz674sGFmwZ8Ih9TdrslA-0nhU2G52WgV-FoG2j0,37670 +sqlalchemy/orm/state_changes.py,sha256=al74Ymt3vqqtWfzZUHQhIKmBZXbT1ovLxgfDurW6XRc,6813 +sqlalchemy/orm/strategies.py,sha256=zk2sg-5D05dBJlzEzpLD5Sfnd5WcCH6dDm4-bxZdMKI,119803 +sqlalchemy/orm/strategy_options.py,sha256=6QFEsOoOsyP2yNJHiJ4j9urfwQxfHFuSVJpoD9TxHcA,85627 +sqlalchemy/orm/sync.py,sha256=RdoxnhvgNjn3Lhtoq4QjvXpj8qfOz__wyibh0FMON0A,5779 +sqlalchemy/orm/unitofwork.py,sha256=hkSIcVonoSt0WWHk019bCDEw0g2o2fg4m4yqoTGyAoo,27033 +sqlalchemy/orm/util.py,sha256=t7lHq0-2FdSpPT558v674-6j9j4DTCmWTOI9xbDy3nY,80889 +sqlalchemy/orm/writeonly.py,sha256=x-eX7QcXUVpadeLldxzNGwDGCOIZHtYBvwP-4kFjZ_I,22297 +sqlalchemy/pool/__init__.py,sha256=niqzCv2uOZT07DOiV2inlmjrW3lZyqDXGCjnOl1IqJ4,1804 +sqlalchemy/pool/base.py,sha256=_UnrUVppwH0gBkiqPWPcxh1FgU4rjEsCDuCBBw73uAg,52383 +sqlalchemy/pool/events.py,sha256=wdFfvat0fSrVF84Zzsz5E3HnVY0bhL7MPsGME-b2qa8,13149 +sqlalchemy/pool/impl.py,sha256=2cg6RVfaXHOH-JPvJx0ITN-xDvjNP-eokhmqpDjsBgE,18899 +sqlalchemy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sqlalchemy/schema.py,sha256=huwl6-8J9j8ZkMiV3ISminNA7BPa8GrYmdX-q4Lvy9M,3251 +sqlalchemy/sql/__init__.py,sha256=Y-bZ25Zf-bxqsF2zUkpRGTjFuozNNVQHxUJV3Qmaq2M,5820 +sqlalchemy/sql/_dml_constructors.py,sha256=JF_XucNTfAk6Vz9fYiPWOgpIGtUkDj6VPILysLcrVhk,3795 +sqlalchemy/sql/_elements_constructors.py,sha256=0fOsjr_UVUnpJJyP7FL0dd1-tqcqIU5uc0vsNfPNApo,63096 +sqlalchemy/sql/_orm_types.py,sha256=0zeMit-V4rYZe-bB9X3xugnjFnPXH0gmeqkJou9Fows,625 +sqlalchemy/sql/_py_util.py,sha256=4KFXNvBq3hhfrr-A1J1uBml3b3CGguIf1dat9gsEHqE,2173 +sqlalchemy/sql/_selectable_constructors.py,sha256=2xSSQEkjhsOim8nvuzQgSN_jpfKdJM9_jVNR91n-wuM,22171 +sqlalchemy/sql/_typing.py,sha256=lV12dX4kWMC1IIEyD3fgOJo_plMq0-qfE5h_oiQzTuQ,13029 +sqlalchemy/sql/annotation.py,sha256=qHUEwbdmMD3Ybr0ez-Dyiw9l9UB_RUMHWAUIeO_r3gE,18245 +sqlalchemy/sql/base.py,sha256=lwxhzQumtS7GA0Hb7v3TgUT9pbwELEkGoyj9XqRcS2Y,75859 +sqlalchemy/sql/cache_key.py,sha256=hnOYFbU_vmtpqorW-dE1Z9h_CK_Yi_3YXZpOAp30ZbM,33653 +sqlalchemy/sql/coercions.py,sha256=8jZUTu7NqukXTVvz9jqJ7Pr3u762qrP2AUVgmOgoUTc,40705 +sqlalchemy/sql/compiler.py,sha256=63-a8RYtgbU-UKDLerrMidaZvRUqmsT7H_4fS0PZ4qc,283319 +sqlalchemy/sql/crud.py,sha256=zfJdQsRZgAwxcxmo4-WjhgxJKpJ7FRoAAuZ7NgNNUx0,59455 +sqlalchemy/sql/ddl.py,sha256=6Za5sdcpC2D0rJ7_tPSnyp6XR-B0zaDR6MCn032g0eE,47993 +sqlalchemy/sql/default_comparator.py,sha256=YL0lb3TGlmfoUfcMWEo5FkvBQVPa1ZnDcYxoUq97f_4,16706 +sqlalchemy/sql/dml.py,sha256=Z2htAxiHuQ57gW1XXDjcJNvwiUru_Y0-PTQndkZPbXg,66573 +sqlalchemy/sql/elements.py,sha256=1CLfFLnDITZzc5aqUn4XOc9Gi23InafpgYt7qf8MlY0,179606 +sqlalchemy/sql/events.py,sha256=iWjc_nm1vClDBLg4ZhDnY75CkBdnlDPSPe0MGBSmbiM,18312 +sqlalchemy/sql/expression.py,sha256=CsOkmAQgaB-Rnwe7eK60FdBC5R9kY5pczCGrVw2BwGs,7583 +sqlalchemy/sql/functions.py,sha256=Q3PEokUPHy4oai3XxvOvPoC84Sby5-D3YbeC_3eeuU8,64870 +sqlalchemy/sql/lambdas.py,sha256=W5b75ojie3EOm7poR27qsnQHQYdz-NxfSrgb5ATT2H0,49401 +sqlalchemy/sql/naming.py,sha256=5Tk6nm4xqy8d9gzXzDvdiqqS7IptUaf1d7IuVdslplU,6855 +sqlalchemy/sql/operators.py,sha256=h5bgu31gukGdsYsN_0-1C7IGAdSCFpBxuRjOUnu1Two,76792 +sqlalchemy/sql/roles.py,sha256=drAeWbevjgFAKNcMrH_EuJ-9sSvcq4aeXwAqMXXZGYw,7662 +sqlalchemy/sql/schema.py,sha256=f8Ebxr3sd7Iuxk0vnE8Os3icrQOdCgo72NMGTOzSrwo,230555 +sqlalchemy/sql/selectable.py,sha256=vuKf1dn9jv3q5CESxPFu6uHeVFjUA-dYuZbJYHPuJWU,243231 +sqlalchemy/sql/sqltypes.py,sha256=RvB6ytf6vSXxZdEY2zh0a3G4LXD9IoFSIZQPyZV6RrU,132159 +sqlalchemy/sql/traversals.py,sha256=7GALHt5mFceUv2SMUikIdAb9SUcSbACqhwoei5rPkxc,33664 +sqlalchemy/sql/type_api.py,sha256=ZaRtirCvkY2-LOv2TeRFX8r8aVOl5fZhplLWBqexctE,85425 +sqlalchemy/sql/util.py,sha256=NSyop8VMFspSPhnUeTc6-ffWEnBgS12FasZKSo-e1-w,48110 +sqlalchemy/sql/visitors.py,sha256=nMK_ddPg4NvEhEgKorD0rGoy-jqs-dT-uou-S8HAEyY,36316 +sqlalchemy/testing/__init__.py,sha256=GgUEqxUNCxg-92_GgBDnljUHsdCxaGPMG1TWy5tjwgk,3160 +sqlalchemy/testing/assertions.py,sha256=9FLeP4Q5nPCP-NAVutOse9ej0SD1uEGtW5YKIy8s5dA,31564 +sqlalchemy/testing/assertsql.py,sha256=cmhtZrgPBjrqIfzFz3VBWxVNvxWoRllvmoWcUCoqsio,16817 +sqlalchemy/testing/asyncio.py,sha256=QsMzDWARFRrpLoWhuYqzYQPTUZ80fymlKrqOoDkmCmQ,3830 +sqlalchemy/testing/config.py,sha256=HySdB5_FgCW1iHAJVxYo-4wq5gUAEi0N8E93IC6M86Q,12058 +sqlalchemy/testing/engines.py,sha256=c1gFXfpo5S1dvNjGIL03mbW2eVYtUD_9M_ZEfQO2ArM,13414 +sqlalchemy/testing/entities.py,sha256=KdgTVPSALhi9KkAXj2giOYl62ld-1yZziIDBSV8E3vw,3354 +sqlalchemy/testing/exclusions.py,sha256=0Byf3DIMQXN0-HOS6M2MPJ-fOm_n5MzE1yIfHgE0nLs,12473 +sqlalchemy/testing/fixtures/__init__.py,sha256=e5YtfSlkKDRuyIZhEKBCycMX5BOO4MZ-0d97l1JDhJE,1198 +sqlalchemy/testing/fixtures/base.py,sha256=n1wws2ziMfP5CcmKx1R-1bFitUDvIAjJH0atWKMI5Oc,12385 +sqlalchemy/testing/fixtures/mypy.py,sha256=tzCaKeO6SX_6uhdBFrKo6iBB7abdZxhyj7SFUlRQINc,12755 +sqlalchemy/testing/fixtures/orm.py,sha256=3JJoYdI2tj5-LL7AN8bVa79NV3Guo4d9p6IgheHkWGc,6095 +sqlalchemy/testing/fixtures/sql.py,sha256=ht-OD6fMZ0inxucRzRZG4kEMNicqY8oJdlKbZzHhAJc,15900 +sqlalchemy/testing/pickleable.py,sha256=G3L0xL9OtbX7wThfreRjWd0GW7q0kUKcTUuCN5ETGno,2833 +sqlalchemy/testing/plugin/__init__.py,sha256=vRfF7M763cGm9tLQDWK6TyBNHc80J1nX2fmGGxN14wY,247 +sqlalchemy/testing/plugin/bootstrap.py,sha256=VYnVSMb-u30hGY6xGn6iG-LqiF0CubT90AJPFY_6UiY,1685 +sqlalchemy/testing/plugin/plugin_base.py,sha256=TBWdg2XgXB6QgUUFdKLv1O9-SXMitjHLm2rNNIzXZhQ,21578 +sqlalchemy/testing/plugin/pytestplugin.py,sha256=e0sdvPAQEZsWXfUcqTE1sFEk_1nJbkn5ynuhNyq9Ix4,27779 +sqlalchemy/testing/profiling.py,sha256=w-oNJcOwCiYyVv8fN8DDZ1vut8m0i0iAM66x_GhxTcM,10237 +sqlalchemy/testing/provision.py,sha256=6r2FTnm-t7u8MMbWo7eMhAH3qkL0w0WlmE29MUSEIu4,14702 +sqlalchemy/testing/requirements.py,sha256=rCvPgm5MbIar_gYeHkdTUQ8QgXJcftZmygW48aXrTM0,56103 +sqlalchemy/testing/schema.py,sha256=IImFumAdpzOyoKAs0WnaGakq8D3sSU4snD9W4LVOV3s,6513 +sqlalchemy/testing/suite/__init__.py,sha256=S8TLwTiif8xX67qlZUo5I9fl9UjZAFGSzvlptp2WoWc,722 +sqlalchemy/testing/suite/test_cte.py,sha256=_GnADXRnhm37RdSRBR5SthQenTeb5VVo3HoCuO0Vifw,7262 +sqlalchemy/testing/suite/test_ddl.py,sha256=MItp-votCzvahlRqHRagte2Omyq9XUOFdFsgzCb6_-g,12031 +sqlalchemy/testing/suite/test_deprecations.py,sha256=7C6IbxRmq7wg_DLq56f1V5RCS9iVrAv3epJZQTB-dOo,5337 +sqlalchemy/testing/suite/test_dialect.py,sha256=j3srr7k2aUd_kPtJPgqI1g1aYD6ko4MvuGu1a1HQgS8,24215 +sqlalchemy/testing/suite/test_insert.py,sha256=pR0VWMQ9JJPbnANE6634PzR0VFmWMF8im6OTahc4vsQ,18824 +sqlalchemy/testing/suite/test_reflection.py,sha256=nrCSSyukfIcMEGtL8LyX3pz6N3wJCPmPlXvdCbtlKGg,114891 +sqlalchemy/testing/suite/test_results.py,sha256=S7Vqqh_Wuqf7uhM8h0cBVeV1GS5GJRO_ZTVYmT7kwuc,17042 +sqlalchemy/testing/suite/test_rowcount.py,sha256=UVyHHQsU0TxkzV_dqCOKR1aROvIq7frKYMVjwUqLWfE,7900 +sqlalchemy/testing/suite/test_select.py,sha256=U6WHUBzko_x6dK32PCXY7-5xN9j0VuAS5z3C-zjDE8I,62041 +sqlalchemy/testing/suite/test_sequence.py,sha256=DMqyJkL1o4GClrNjzoy7GDn_jPNPTZNvk9t5e-MVXeo,9923 +sqlalchemy/testing/suite/test_types.py,sha256=C3wJn3DGlGf58eNr02SoYR3iFAl-vnnHPJS_SSWIu80,68013 +sqlalchemy/testing/suite/test_unicode_ddl.py,sha256=0zVc2e3zbCQag_xL4b0i7F062HblHwV46JHLMweYtcE,6141 +sqlalchemy/testing/suite/test_update_delete.py,sha256=_OxH0wggHUqPImalGEPI48RiRx6mO985Om1PtRYOCzA,3994 +sqlalchemy/testing/util.py,sha256=BuA4q-8cmNhrUVqPP35Rr15MnYGSjmW0hmUdS1SI0_I,14526 +sqlalchemy/testing/warnings.py,sha256=sj4vfTtjodcfoX6FPH_Zykb4fomjmgqIYj81QPpSwH8,1546 +sqlalchemy/types.py,sha256=Iq_rKisaj_zhHtzD2R2cxvg3jkug5frikbkcKG0S4Lg,3166 +sqlalchemy/util/__init__.py,sha256=5fNLIdnv3Rh8esnbffLSY3y5bHq8HhkzaAgHv94208w,8406 +sqlalchemy/util/_collections.py,sha256=JQkGm3MBq3RWr5WKG1-SwocPK3PwQHNslW8QqT7CAq0,20151 +sqlalchemy/util/_concurrency_py3k.py,sha256=UtPDkb67OOVWYvBqYaQgENg0k_jOA2mQOE04XmrbYq0,9170 +sqlalchemy/util/_has_cy.py,sha256=3oh7s5iQtW9qcI8zYunCfGAKG6fzo2DIpzP5p1BnE8Q,1247 +sqlalchemy/util/_py_collections.py,sha256=nxdOFQkO05ijXw-0u_InaH19pPj4VsFcat7tZNoIjt8,16650 +sqlalchemy/util/compat.py,sha256=PCHrgM1JG-RN5GwBRHsPC07wTOU3--q1FJABKXYkC2s,9173 +sqlalchemy/util/concurrency.py,sha256=GycODl5vsbDH8G_1Y_Edk1anLpqDmS9-YzzzVleDw48,3350 +sqlalchemy/util/deprecations.py,sha256=L7D4GqeIozpjO8iVybf7jL9dDlgfTbAaQH4TQAX74qE,12012 +sqlalchemy/util/langhelpers.py,sha256=lxiXhjMI6esHpcBXy_9mf6YDREDH6GB5RNMGrj3wmo4,68522 +sqlalchemy/util/preloaded.py,sha256=RMarsuhtMW8ZuvqLSuR0kwbp45VRlzKpJMLUe7p__qY,5904 +sqlalchemy/util/queue.py,sha256=w1ufhuiC7lzyiZDhciRtRz1uyxU72jRI7SWhhL-p600,10185 +sqlalchemy/util/tool_support.py,sha256=e7lWu6o1QlKq4e6c9PyDsuyFyiWe79vO72UQ_YX2pUA,6135 +sqlalchemy/util/topological.py,sha256=tbkMRY0TTgNiq44NUJpnazXR4xb9v4Q4mQ8BygMp0vY,3451 +sqlalchemy/util/typing.py,sha256=EB7YXmW8kQ25HfN6vmdfKQD2paDNcX9TQn5KojTBb-Q,22493 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/REQUESTED b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/WHEEL b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d170d6d9582d145f12244c4135d9446d597e1029 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.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_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/licenses/LICENSE b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..dfe1a4d815b4e81dcc25851f6f6d1770a311bf94 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/licenses/LICENSE @@ -0,0 +1,19 @@ +Copyright 2005-2025 SQLAlchemy authors and contributors . + +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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/top_level.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..39fb2befb58229af3357b22968f9db6bb7754cbe --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sqlalchemy-2.0.44.dist-info/top_level.txt @@ -0,0 +1 @@ +sqlalchemy diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..573f2e2c051cc3fcc0376a49b19737d2660c7683 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__init__.py @@ -0,0 +1,82 @@ +"""isort:skip_file""" +__version__ = '3.5.0' + +# --------------------------------------- +# Note: import order is significant here. + +# submodules +from .runtime import ( + autotune, + Config, + heuristics, + JITFunction, + KernelInterface, + reinterpret, + TensorWrapper, + OutOfResources, + InterpreterError, + MockTensor, +) +from .runtime.jit import constexpr_function, jit +from .runtime._async_compile import AsyncCompileMode, FutureKernel +from .compiler import compile, CompilationError +from .errors import TritonError +from .runtime._allocation import set_allocator + +from . import language +from . import testing +from . import tools + +must_use_result = language.core.must_use_result + +__all__ = [ + "AsyncCompileMode", + "autotune", + "cdiv", + "CompilationError", + "compile", + "Config", + "constexpr_function", + "FutureKernel", + "heuristics", + "InterpreterError", + "jit", + "JITFunction", + "KernelInterface", + "language", + "MockTensor", + "must_use_result", + "next_power_of_2", + "OutOfResources", + "reinterpret", + "runtime", + "set_allocator", + "TensorWrapper", + "TritonError", + "testing", + "tools", +] + +# ------------------------------------- +# misc. utilities that don't fit well +# into any specific module +# ------------------------------------- + + +@constexpr_function +def cdiv(x: int, y: int): + return (x + y - 1) // y + + +@constexpr_function +def next_power_of_2(n: int): + """Return the smallest power of 2 greater than or equal to n""" + n -= 1 + n |= n >> 1 + n |= n >> 2 + n |= n >> 4 + n |= n >> 8 + n |= n >> 16 + n |= n >> 32 + n += 1 + return n diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4a9218833ea3e3191c9f9a44e640b88485c04d4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__pycache__/_utils.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__pycache__/_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2083251ecf76a4573eb69e37934844270316dcb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__pycache__/_utils.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__pycache__/errors.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__pycache__/errors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83a4d39b16c1594ddb691c1dbc31ba0683070e2a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__pycache__/errors.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__pycache__/knobs.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__pycache__/knobs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4167baa1cd3dae124504b8b5a366ba478e17c473 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__pycache__/knobs.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__pycache__/testing.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__pycache__/testing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..246828751916dea0083473655142a672235c6d9a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/__pycache__/testing.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/_internal_testing.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/_internal_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..6914de8153fcd8b827f216042a6f97c6d913af7d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/_internal_testing.py @@ -0,0 +1,255 @@ +import os +import re +import numpy as np +import torch +import triton +import triton.language as tl +from triton import knobs +from typing import Optional, Set, Union +import pytest + +from numpy.random import RandomState +from triton.runtime.jit import TensorWrapper, reinterpret, type_canonicalisation_dict + +int_dtypes = ['int8', 'int16', 'int32', 'int64'] +uint_dtypes = ['uint8', 'uint16', 'uint32', 'uint64'] +integral_dtypes = int_dtypes + uint_dtypes +float_dtypes = ['float16', 'float32', 'float64'] +float_dtypes_with_bfloat16 = float_dtypes + ['bfloat16'] +dtypes = integral_dtypes + float_dtypes +dtypes_with_bfloat16 = dtypes + ['bfloat16'] +torch_float8_dtypes = ['float8_e4m3fn', 'float8_e5m2'] +torch_dtypes = ['bool'] + int_dtypes + ['uint8'] + float_dtypes + ['bfloat16'] +tma_dtypes = sorted(set(dtypes_with_bfloat16) - {"int64", "uint64", "float64"}) + + +def is_interpreter(): + return os.environ.get('TRITON_INTERPRET', '0') == '1' + + +def get_current_target(): + if is_interpreter(): + return None + return triton.runtime.driver.active.get_current_target() + + +def is_cuda(): + target = get_current_target() + return False if target is None else target.backend == "cuda" + + +def is_ampere_or_newer(): + return is_cuda() and torch.cuda.get_device_capability()[0] >= 8 + + +def is_blackwell(): + return is_cuda() and torch.cuda.get_device_capability()[0] == 10 + + +def is_hopper_or_newer(): + return is_cuda() and torch.cuda.get_device_capability()[0] >= 9 + + +def is_hopper(): + return is_cuda() and torch.cuda.get_device_capability()[0] == 9 + + +def is_hip(): + target = get_current_target() + return False if target is None else target.backend == "hip" + + +def is_hip_cdna2(): + target = get_current_target() + return target is not None and target.backend == 'hip' and target.arch == 'gfx90a' + + +def is_hip_cdna3(): + target = get_current_target() + return target is not None and target.backend == 'hip' and target.arch == 'gfx942' + + +def is_hip_cdna4(): + target = get_current_target() + return target is not None and target.backend == 'hip' and target.arch == 'gfx950' + + +def is_hip_gfx11(): + target = get_current_target() + return target is not None and target.backend == 'hip' and 'gfx11' in target.arch + + +def is_hip_gfx12(): + target = get_current_target() + return target is not None and target.backend == 'hip' and 'gfx12' in target.arch + + +def is_hip_cdna(): + return is_hip_cdna2() or is_hip_cdna3() or is_hip_cdna4() + + +def get_hip_lds_size(): + return 163840 if is_hip_cdna4() else 65536 + + +def is_xpu(): + target = get_current_target() + return False if target is None else target.backend == "xpu" + + +def get_arch(): + target = get_current_target() + return "" if target is None else str(target.arch) + + +def numpy_random(shape, dtype_str, rs: Optional[RandomState] = None, low=None, high=None): + """ + Override `rs` if you're calling this function twice and don't want the same + result for both calls. + """ + if isinstance(shape, int): + shape = (shape, ) + if rs is None: + rs = RandomState(seed=17) + if dtype_str in int_dtypes + uint_dtypes: + iinfo = np.iinfo(getattr(np, dtype_str)) + low = iinfo.min if low is None else max(low, iinfo.min) + high = iinfo.max if high is None else min(high, iinfo.max) + dtype = getattr(np, dtype_str) + x = rs.randint(low, high, shape, dtype=dtype) + x[x == 0] = 1 # Workaround. Never return zero so tests of division don't error out. + return x + elif dtype_str and 'float8' in dtype_str: + x = rs.randint(20, 40, shape, dtype=np.int8) + return x + elif dtype_str in float_dtypes: + return rs.normal(0, 1, shape).astype(dtype_str) + elif dtype_str == 'bfloat16': + return (rs.normal(0, 1, shape).astype('float32').view('uint32') & np.uint32(0xffff0000)).view('float32') + elif dtype_str in ['bool', 'int1', 'bool_']: + return rs.normal(0, 1, shape) > 0.0 + else: + raise RuntimeError(f'Unknown dtype {dtype_str}') + + +def to_triton(x: np.ndarray, device, dst_type=None) -> Union[TensorWrapper, torch.Tensor]: + ''' + Note: We need dst_type because the type of x can be different from dst_type. + For example: x is of type `float32`, dst_type is `bfloat16`. + If dst_type is None, we infer dst_type from x. + ''' + t = x.dtype.name + if t in uint_dtypes: + signed_type_name = t.lstrip('u') # e.g. "uint16" -> "int16" + x_signed = x.astype(getattr(np, signed_type_name)) + return reinterpret(torch.tensor(x_signed, device=device), getattr(tl, t)) + else: + if dst_type and 'float8' in dst_type: + return reinterpret(torch.tensor(x, device=device), getattr(tl, dst_type)) + if t == 'float32' and dst_type == 'bfloat16': + return torch.tensor(x, device=device).bfloat16() + return torch.tensor(x, device=device) + + +def str_to_triton_dtype(x: str) -> tl.dtype: + return tl.str_to_ty(type_canonicalisation_dict[x], None) + + +def torch_dtype_name(dtype) -> str: + if isinstance(dtype, triton.language.dtype): + return dtype.name + elif isinstance(dtype, torch.dtype): + # 'torch.int64' -> 'int64' + m = re.match(r'^torch\.(\w+)$', str(dtype)) + return m.group(1) + else: + raise TypeError(f'not a triton or torch dtype: {type(dtype)}') + + +def to_numpy(x): + if isinstance(x, TensorWrapper): + return x.base.cpu().numpy().astype(getattr(np, torch_dtype_name(x.dtype))) + elif isinstance(x, torch.Tensor): + if x.dtype is torch.bfloat16: + return x.cpu().float().numpy() + return x.cpu().numpy() + else: + raise ValueError(f"Not a triton-compatible tensor: {x}") + + +def supports_tma(byval_only=False): + if is_interpreter(): + return True + if not is_cuda(): + return False + cuda_version = knobs.nvidia.ptxas.version + min_cuda_version = (12, 0) if byval_only else (12, 3) + cuda_version_tuple = tuple(map(int, cuda_version.split("."))) + assert len(cuda_version_tuple) == 2, cuda_version_tuple + return torch.cuda.get_device_capability()[0] >= 9 and cuda_version_tuple >= min_cuda_version + + +def tma_skip_msg(byval_only=False): + if byval_only: + return "Requires __grid_constant__ TMA support (NVIDIA Hopper or higher, CUDA 12.0 or higher)" + else: + return "Requires advanced TMA support (NVIDIA Hopper or higher, CUDA 12.3 or higher)" + + +requires_tma = pytest.mark.skipif(not supports_tma(), reason=tma_skip_msg()) + + +def default_alloc_fn(size: int, align: int, _): + return torch.empty(size, dtype=torch.int8, device="cuda") + + +def unwrap_tensor(t: Union[torch.Tensor, triton.runtime.jit.TensorWrapper]) -> torch.Tensor: + if isinstance(t, triton.runtime.jit.TensorWrapper): + return t.base + return t + + +def _fresh_knobs_impl(skipped_attr: Optional[Set[str]] = None): + from triton import knobs + + if skipped_attr is None: + skipped_attr = set() + + monkeypatch = pytest.MonkeyPatch() + + knobs_map = { + name: knobset + for name, knobset in knobs.__dict__.items() + if isinstance(knobset, knobs.base_knobs) and knobset != knobs.base_knobs and name not in skipped_attr + } + + # We store which variables we need to unset below in finally because + # monkeypatch doesn't appear to reset variables that were never set + # before the monkeypatch.delenv call below. + env_to_unset = [] + prev_propagate_env = knobs.propagate_env + + def fresh_function(): + nonlocal env_to_unset + for name, knobset in knobs_map.items(): + setattr(knobs, name, knobset.copy().reset()) + for knob in knobset.knob_descriptors.values(): + if knob.key in os.environ: + monkeypatch.delenv(knob.key, raising=False) + else: + env_to_unset.append(knob.key) + knobs.propagate_env = True + return knobs + + def reset_function(): + for name, knobset in knobs_map.items(): + setattr(knobs, name, knobset) + # `undo` should be placed before `del os.environ` + # Otherwise, it may restore environment variables that monkeypatch deleted + monkeypatch.undo() + for k in env_to_unset: + if k in os.environ: + del os.environ[k] + knobs.propagate_env = prev_propagate_env + + return fresh_function, reset_function diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/_utils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d7d2455f0799c15a09f3ec30646a5ffef6f55407 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/_utils.py @@ -0,0 +1,126 @@ +from __future__ import annotations + +from functools import reduce +from typing import Any, Callable, TYPE_CHECKING, Union, List, Dict + +if TYPE_CHECKING: + from .language import core + IterableType = Union[list[Any], tuple[Any, ...], core.tuple, core.tuple_type] + ObjPath = tuple[int, ...] + +TRITON_MAX_TENSOR_NUMEL = 1048576 + + +def get_iterable_path(iterable: IterableType, path: ObjPath) -> Any: + return reduce(lambda a, idx: a[idx], path, iterable) # type: ignore[index] + + +def set_iterable_path(iterable: IterableType, path: tuple[int, ...], val: Any): + from .language import core + assert len(path) != 0 + prev = iterable if len(path) == 1 else get_iterable_path(iterable, path[:-1]) + assert isinstance(prev, core.tuple) + prev._setitem(path[-1], val) + + +def find_paths_if(iterable: Union[IterableType, Any], pred: Callable[[ObjPath, Any], bool]) -> list[ObjPath]: + from .language import core + is_iterable: Callable[[Any], bool] = lambda x: isinstance(x, (list, tuple, core.tuple, core.tuple_type)) + # We need to use dict so that ordering is maintained, while set doesn't guarantee order + ret: dict[ObjPath, None] = {} + + def _impl(path: tuple[int, ...], current: Any): + if is_iterable(current): + for idx, item in enumerate(current): + _impl((*path, idx), item) + elif pred(path, current): + ret[path] = None + + _impl((), iterable) + + return list(ret.keys()) + + +def is_power_of_two(x): + return (x & (x - 1)) == 0 + + +def validate_block_shape(shape: List[int]): + numel = 1 + for i, d in enumerate(shape): + if not isinstance(d, int): + raise TypeError(f"Shape element {i} must have type `constexpr[int]`, got `constexpr[{type(d)}]") + if not is_power_of_two(d): + raise ValueError(f"Shape element {i} must be a power of 2") + numel *= d + + if numel > TRITON_MAX_TENSOR_NUMEL: + raise ValueError(f"numel ({numel}) exceeds triton maximum tensor numel ({TRITON_MAX_TENSOR_NUMEL})") + return numel + + +type_canonicalisation_dict = { + # we canonicalise all bools to be unsigned: + "bool": "u1", + "int1": "u1", + "uint1": "u1", + "i1": "u1", + # floating-point dtypes: + "float8e4nv": "fp8e4nv", + "float8e5": "fp8e5", + "float8e4b15": "fp8e4b15", + "float8_e4m3fn": "fp8e4nv", + "float8e4b8": "fp8e4b8", + "float8_e4m3fnuz": "fp8e4b8", + "float8_e5m2": "fp8e5", + "float8e5b16": "fp8e5b16", + "float8_e5m2fnuz": "fp8e5b16", + "half": "fp16", + "float16": "fp16", + "bfloat16": "bf16", + "float": "fp32", + "float32": "fp32", + "double": "fp64", + "float64": "fp64", + # signed integers: + "int8": "i8", + "int16": "i16", + "int": "i32", + "int32": "i32", + "int64": "i64", + # unsigned integers: + "uint8": "u8", + "uint16": "u16", + "uint32": "u32", + "uint64": "u64", + "void": "void", +} + +for v in list(type_canonicalisation_dict.values()): + type_canonicalisation_dict[v] = v + + +def canonicalize_dtype(dtype): + dtype_str = str(dtype).split(".")[-1] + return type_canonicalisation_dict[dtype_str] + + +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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..69a8dab0a3616754b2531d619d8336153917c27d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7bde7fc542df78ce38c36b166bfdee6af841dee Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/__pycache__/compiler.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/__pycache__/compiler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cf4fd47da86957ce1e332568f8a86c490f9a8b1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/__pycache__/compiler.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/__pycache__/driver.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/__pycache__/driver.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3511993913444f6dfdcf80ec8c5e9fc2a05f461f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/__pycache__/driver.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/driver.c b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/driver.c new file mode 100644 index 0000000000000000000000000000000000000000..c84727d6da3c5dacf658b713938ede1ce2ed5b73 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/driver.c @@ -0,0 +1,283 @@ +#define __HIP_PLATFORM_AMD__ +#include +#include +#define PY_SSIZE_T_CLEAN +#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[] = {"/*py_libhip_search_path*/"}; + +// The list of HIP dynamic library symbols and their signature we are interested +// in this file. +// |FOR_EACH_ERR_FN| is a macro to process APIs that return hipError_t; +// |FOR_EACH_STR_FN| is a macro to process APIs that return const char *. +#define HIP_SYMBOL_LIST(FOR_EACH_ERR_FN, FOR_EACH_STR_FN) \ + FOR_EACH_STR_FN(hipGetErrorString, hipError_t hipError) \ + FOR_EACH_ERR_FN(hipGetDeviceProperties, hipDeviceProp_t *prop, int deviceId) \ + FOR_EACH_ERR_FN(hipModuleLoadDataEx, hipModule_t *module, const void *image, \ + unsigned int numOptions, hipJitOption *options, \ + void **optionValues) \ + FOR_EACH_ERR_FN(hipModuleGetFunction, hipFunction_t *function, \ + hipModule_t module, const char *kname) \ + FOR_EACH_ERR_FN(hipFuncGetAttribute, int *, hipFunction_attribute attr, \ + hipFunction_t function) + +// HIP driver version format: HIP_VERSION_MAJOR * 10000000 + HIP_VERSION_MINOR * +// 100000 + HIP_VERSION_PATCH. +#define TRITON_HIP_DRIVER_EXTRACT_MAJOR_VERSION(version) ((version) / 10000000) +#define TRITON_HIP_DRIVER_EXTRACT_MINOR_VERSION(version) \ + (((version) % 10000000) / 100000) +#define TRITON_HIP_DRIVER_EXTRACT_PATCH_VERSION(version) ((version) % 100000) +#define TRITON_HIP_DRIVER_REQ_MAJOR_VERSION (HIP_VERSION_MAJOR) + +// #define TRITON_HIP_DRIVER_DBG_VERSION +#ifdef TRITON_HIP_DRIVER_DBG_VERSION +#define TRITON_HIP_DRIVER_LOG_VERSION(version, msgBuff) \ + do { \ + snprintf(msgBuff, sizeof(msgBuff), "libamdhip64 version is: %d.%d.%d", \ + TRITON_HIP_DRIVER_EXTRACT_MAJOR_VERSION(version), \ + TRITON_HIP_DRIVER_EXTRACT_MINOR_VERSION(version), \ + TRITON_HIP_DRIVER_EXTRACT_PATCH_VERSION(version)); \ + printf("%s\n", msgBuff); \ + } while (0); +#else +#define TRITON_HIP_DRIVER_LOG_VERSION(version, msgBuff) \ + do { \ + (void)msgBuff; \ + (void)(version); \ + } while (0); +#endif + +#define TRITON_HIP_MSG_BUFF_SIZE (1024U) + +// The HIP symbol table for holding resolved dynamic library symbols. +struct HIPSymbolTable { +#define DEFINE_EACH_ERR_FIELD(hipSymbolName, ...) \ + hipError_t (*hipSymbolName)(__VA_ARGS__); +#define DEFINE_EACH_STR_FIELD(hipSymbolName, ...) \ + const char *(*hipSymbolName)(__VA_ARGS__); + + HIP_SYMBOL_LIST(DEFINE_EACH_ERR_FIELD, DEFINE_EACH_STR_FIELD) +}; + +static struct HIPSymbolTable hipSymbolTable; + +static int checkDriverVersion(void *lib) { + int hipVersion = -1; + const char *error = NULL; + typedef hipError_t (*hipDriverGetVersion_fn)(int *driverVersion); + hipDriverGetVersion_fn hipDriverGetVersion; + dlerror(); // Clear existing errors + hipDriverGetVersion = + (hipDriverGetVersion_fn)dlsym(lib, "hipDriverGetVersion"); + error = dlerror(); + if (error) { + PyErr_SetString(PyExc_RuntimeError, + "cannot query 'hipDriverGetVersion' from libamdhip64.so"); + dlclose(lib); + return -1; + } + + (void)hipDriverGetVersion(&hipVersion); + char msgBuff[TRITON_HIP_MSG_BUFF_SIZE] = {0}; + + const int hipMajVersion = TRITON_HIP_DRIVER_EXTRACT_MAJOR_VERSION(hipVersion); + if (hipMajVersion < TRITON_HIP_DRIVER_REQ_MAJOR_VERSION) { + const int hipMinVersion = + TRITON_HIP_DRIVER_EXTRACT_MINOR_VERSION(hipVersion); + const int hipPatchVersion = + TRITON_HIP_DRIVER_EXTRACT_PATCH_VERSION(hipVersion); + snprintf(msgBuff, sizeof(msgBuff), + "libamdhip64 version %d.%d.%d is not supported! Required major " + "version is >=%d.", + hipMajVersion, hipMinVersion, hipPatchVersion, + TRITON_HIP_DRIVER_REQ_MAJOR_VERSION); + PyErr_SetString(PyExc_RuntimeError, msgBuff); + dlclose(lib); + return -1; + } + + TRITON_HIP_DRIVER_LOG_VERSION(hipVersion, msgBuff); + + return hipVersion; +} + +bool initSymbolTable() { + void *lib; + + // Go through the list of search paths to dlopen the first HIP driver library. + int n = sizeof(hipLibSearchPaths) / sizeof(hipLibSearchPaths[0]); + for (int i = 0; i < n; ++i) { + void *handle = dlopen(hipLibSearchPaths[i], RTLD_LAZY | RTLD_LOCAL); + if (handle) { + lib = handle; + // printf("[triton] chosen %s\n", hipLibSearchPaths[i]); + } + } + + if (!lib) { + PyErr_SetString(PyExc_RuntimeError, "cannot open libamdhip64.so"); + return false; + } + + int hipVersion = checkDriverVersion(lib); + if (hipVersion == -1) + return false; + + const char *error = NULL; + typedef hipError_t (*hipGetProcAddress_fn)( + const char *symbol, void **pfn, int hipVersion, uint64_t hipFlags, + hipDriverProcAddressQueryResult *symbolStatus); + hipGetProcAddress_fn hipGetProcAddress; + dlerror(); // Clear existing errors + + *(void **)&hipGetProcAddress = dlsym(lib, "hipGetProcAddress"); + error = dlerror(); + if (error) { + PyErr_SetString(PyExc_RuntimeError, + "cannot query 'hipGetProcAddress' from libamdhip64.so"); + dlclose(lib); + return false; + } + + // Resolve all symbols we are interested in. + uint64_t hipFlags = 0; + hipDriverProcAddressQueryResult symbolStatus; + hipError_t status = hipSuccess; +#define QUERY_EACH_FN(hipSymbolName, ...) \ + status = hipGetProcAddress(#hipSymbolName, \ + (void **)&hipSymbolTable.hipSymbolName, \ + hipVersion, hipFlags, &symbolStatus); \ + if (status != hipSuccess) { \ + PyErr_SetString(PyExc_RuntimeError, \ + "cannot get address for '" #hipSymbolName \ + "' from libamdhip64.so"); \ + dlclose(lib); \ + return false; \ + } + + HIP_SYMBOL_LIST(QUERY_EACH_FN, QUERY_EACH_FN) + + return true; +} + +static inline void gpuAssert(hipError_t code, const char *file, int line) { + { + if (code != HIP_SUCCESS) { + { + const char *prefix = "Triton Error [HIP]: "; + const char *str = hipSymbolTable.hipGetErrorString(code); + char err[TRITON_HIP_MSG_BUFF_SIZE] = {0}; + snprintf(err, sizeof(err), "%s Code: %d, Messsage: %s", prefix, code, + str); + PyGILState_STATE gil_state; + gil_state = PyGILState_Ensure(); + PyErr_SetString(PyExc_RuntimeError, err); + PyGILState_Release(gil_state); + } + } + } +} + +#define HIP_CHECK(ans) \ + { \ + gpuAssert((ans), __FILE__, __LINE__); \ + if (PyErr_Occurred()) \ + return NULL; \ + } + +static PyObject *getDeviceProperties(PyObject *self, PyObject *args) { + int device_id; + if (!PyArg_ParseTuple(args, "i", &device_id)) + return NULL; + + hipDeviceProp_t props; + HIP_CHECK(hipSymbolTable.hipGetDeviceProperties(&props, device_id)); + + // create a struct to hold device properties + return Py_BuildValue( + "{s:i, s:i, s:i, s:i, s:i, s:i, s:s, s:i, s:i}", "max_shared_mem", + props.sharedMemPerBlock, "max_num_regs", props.regsPerBlock, + "multiprocessor_count", props.multiProcessorCount, "sm_clock_rate", + props.clockRate, "mem_clock_rate", props.memoryClockRate, "mem_bus_width", + props.memoryBusWidth, "arch", props.gcnArchName, "warpSize", + props.warpSize, "max_threads_per_sm", props.maxThreadsPerMultiProcessor); +} + +static PyObject *loadBinary(PyObject *self, PyObject *args) { + const char *name; + const char *data; + Py_ssize_t data_size; + int shared; + int device; + if (!PyArg_ParseTuple(args, "ss#ii", &name, &data, &data_size, &shared, + &device)) { + return NULL; + } + + // set HIP options + hipJitOption opt[] = {hipJitOptionErrorLogBufferSizeBytes, + hipJitOptionErrorLogBuffer, + hipJitOptionInfoLogBufferSizeBytes, + hipJitOptionInfoLogBuffer, hipJitOptionLogVerbose}; + const unsigned int errbufsize = 8192; + const unsigned int logbufsize = 8192; + char _err[errbufsize]; + char _log[logbufsize]; + void *optval[] = {(void *)(uintptr_t)errbufsize, (void *)_err, + (void *)(uintptr_t)logbufsize, (void *)_log, (void *)1}; + + // launch HIP Binary + hipModule_t mod; + hipFunction_t fun; + HIP_CHECK(hipSymbolTable.hipModuleLoadDataEx(&mod, data, 5, opt, optval)) + HIP_CHECK(hipSymbolTable.hipModuleGetFunction(&fun, mod, name)); + + // get allocated registers and spilled registers from the function + int n_regs = 0; + int n_spills = 0; + int32_t n_max_threads = 0; + hipSymbolTable.hipFuncGetAttribute(&n_regs, HIP_FUNC_ATTRIBUTE_NUM_REGS, fun); + hipSymbolTable.hipFuncGetAttribute(&n_spills, + HIP_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES, fun); + hipSymbolTable.hipFuncGetAttribute( + &n_max_threads, HIP_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, fun); + n_spills /= 4; + if (PyErr_Occurred()) { + return NULL; + } + return Py_BuildValue("(KKiii)", (uint64_t)mod, (uint64_t)fun, n_regs, + n_spills, n_max_threads); +} + +static 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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/driver.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/driver.py new file mode 100644 index 0000000000000000000000000000000000000000..3418ce26f10ab62e54a63c9ed10c25e7a042bfde --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/driver.py @@ -0,0 +1,724 @@ +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 import _allocation +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) + + # HIP_PATH should point to HIP SDK root if set + env_hip_path = os.getenv("HIP_PATH") + if env_hip_path: + hip_lib_path = os.path.join(env_hip_path, "lib", lib_name) + if os.path.exists(hip_lib_path): + return hip_lib_path + paths.append(hip_lib_path) + + # if available, `hipconfig --path` prints the HIP SDK root + try: + hip_root = subprocess.check_output(["hipconfig", "--path"]).decode().strip() + if hip_root: + hip_lib_path = os.path.join(hip_root, "lib", lib_name) + if os.path.exists(hip_lib_path): + return hip_lib_path + paths.append(hip_lib_path) + except (subprocess.CalledProcessError, FileNotFoundError): + # hipconfig may not be available + pass + + # ROCm lib dir based on env var + env_rocm_path = os.getenv("ROCM_PATH") + if env_rocm_path: + rocm_lib_path = os.path.join(env_rocm_path, "lib", lib_name) + if os.path.exists(rocm_lib_path): + return rocm_lib_path + paths.append(rocm_lib_path) + + # Afterwards try to search the loader dynamic library resolution paths. + libs = subprocess.check_output(["/sbin/ldconfig", "-p"]).decode(errors="ignore") + # each line looks like the following: + # libamdhip64.so.6 (libc6,x86-64) => /opt/rocm-6.0.2/lib/libamdhip64.so.6 + # libamdhip64.so (libc6,x86-64) => /opt/rocm-6.0.2/lib/libamdhip64.so + locs = [line.split()[-1] for line in libs.splitlines() if line.strip().endswith(lib_name)] + for loc in locs: + if os.path.exists(loc): + return loc + paths.append(loc) + + # As a last resort, guess if we have it in some common installation path. + common_install_path = os.path.join('/opt/rocm/lib/', lib_name) + if os.path.exists(common_install_path): + return common_install_path + paths.append(common_install_path) + + raise RuntimeError(f"cannot locate {lib_name} after attempted paths {paths}") + + +class HIPUtils(object): + + def __new__(cls): + if not hasattr(cls, "instance"): + cls.instance = super(HIPUtils, cls).__new__(cls) + return cls.instance + + def __init__(self): + libhip_path = _get_path_to_hip_runtime_dylib() + src = Path(os.path.join(dirname, "driver.c")).read_text() + # Just do a simple search and replace here instead of templates or format strings. + # This way we don't need to escape-quote C code curly brackets and we can replace + # exactly once. + src = src.replace('/*py_libhip_search_path*/', libhip_path, 1) + mod = compile_module_from_src(src=src, name="hip_utils", include_dirs=include_dirs) + self.load_binary = mod.load_binary + self.get_device_properties = mod.get_device_properties + + +# -------------------- Launcher ---------------------------- +def ty_to_cpp(ty): + if ty[0] == '*': + return "hipDeviceptr_t" + return { + "i1": "int8_t", + "i8": "int8_t", + "i16": "int16_t", + "i32": "int32_t", + "i64": "int64_t", + "u1": "uint8_t", + "u8": "uint8_t", + "u16": "uint16_t", + "u32": "uint32_t", + "u64": "uint64_t", + "fp16": "double", + "bf16": "double", + "fp32": "double", + "f32": "double", + "fp64": "double", + }[ty] + + +FLOAT_STORAGE_TYPE = { + "fp16": "uint16_t", + "bf16": "uint16_t", + "fp32": "uint32_t", + "f32": "uint32_t", + "fp64": "uint64_t", +} +FLOAT_PACK_FUNCTION = { + "fp16": "pack_fp16", + "bf16": "pack_bf16", + "fp32": "pack_fp32", + "f32": "pack_fp32", + "fp64": "pack_fp64", +} + +_BASE_ARGS_FORMAT = "piiiKKOOOOO" + + +def make_launcher(constants, signature, warp_size): + + 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") + output.append("i1") + # 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") + params.append("&profile_scratch") + src = f""" +#define __HIP_PLATFORM_AMD__ +#include +#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(hipGetLastError) \\ + 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; + }} + + typedef hipError_t (*hipGetProcAddress_fn)( + const char *symbol, void **pfn, int hipVersion, uint64_t hipFlags, + hipDriverProcAddressQueryResult *symbolStatus); + hipGetProcAddress_fn hipGetProcAddress; + dlerror(); // Clear existing errors + const char *error = NULL; + *(void **)&hipGetProcAddress = dlsym(lib, "hipGetProcAddress"); + error = dlerror(); + if (error) {{ + PyErr_SetString(PyExc_RuntimeError, + "cannot query 'hipGetProcAddress' from libamdhip64.so"); + dlclose(lib); + return false; + }} + + // Resolve all symbols we are interested in. + int hipVersion = HIP_VERSION; + uint64_t hipFlags = 0; + hipDriverProcAddressQueryResult symbolStatus; + hipError_t status = hipSuccess; +#define QUERY_EACH_FN(hipSymbolName, ...) \ + status = hipGetProcAddress(#hipSymbolName, \ + (void **)&hipSymbolTable.hipSymbolName, \ + hipVersion, hipFlags, &symbolStatus); \ + if (status != hipSuccess) {{ \ + PyErr_SetString(PyExc_RuntimeError, \ + "cannot get address for '" #hipSymbolName \ + "' from libamdhip64.so"); \ + dlclose(lib); \ + return false; \ + }} + + HIP_SYMBOL_LIST(QUERY_EACH_FN, QUERY_EACH_FN) + + return true; +}} + +static inline void gpuAssert(hipError_t code, const char *file, int line) +{{ + if (code != HIP_SUCCESS) + {{ + const char* prefix = "Triton Error [HIP]: "; + const char* str = hipSymbolTable.hipGetErrorString(code); + char err[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, hipDeviceptr_t profile_scratch{', ' + 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 PyObject* data_ptr_str = NULL; + +static inline DevicePtrInfo getPointer(PyObject *obj, int idx) {{ + DevicePtrInfo ptr_info; + hipError_t status = hipSuccess; + ptr_info.dev_ptr = 0; + ptr_info.valid = true; + if (PyLong_Check(obj)) {{ + ptr_info.dev_ptr = (hipDeviceptr_t)PyLong_AsUnsignedLongLong(obj); + return ptr_info; + }} + if (obj == Py_None) {{ + // valid nullptr + return ptr_info; + }} + PyObject *ret = PyObject_CallMethodNoArgs(obj, data_ptr_str); + if (!ret) {{ + PyErr_SetString(PyExc_TypeError, "Pointer argument must be either uint64 or have data_ptr method"); + ptr_info.valid = false; + goto cleanup; + }} + if (!PyLong_Check(ret)) {{ + PyErr_SetString(PyExc_TypeError, "data_ptr method of Pointer object must return 64-bit int"); + ptr_info.valid = false; + goto cleanup; + }} + ptr_info.dev_ptr = (hipDeviceptr_t)PyLong_AsUnsignedLongLong(ret); + if (!ptr_info.dev_ptr) + goto cleanup; + uint64_t dev_ptr; + status = hipSymbolTable.hipPointerGetAttribute(&dev_ptr, HIP_POINTER_ATTRIBUTE_DEVICE_POINTER, ptr_info.dev_ptr); + if (status == hipErrorInvalidValue) {{ + PyErr_Format(PyExc_ValueError, + "Pointer argument (at %d) cannot be accessed from Triton (cpu tensor?)", idx); + ptr_info.valid = false; + // Clear and ignore HIP error + (void)hipSymbolTable.hipGetLastError(); + }} + ptr_info.dev_ptr = (hipDeviceptr_t)dev_ptr; +cleanup: + Py_DECREF(ret); + return ptr_info; +}} + +static uint16_t pack_fp16(double f) {{ + uint16_t result; + // from https://github.com/python/pythoncapi-compat/blob/5e317108f872c904eb726cb8d560dcadbdf88a72/pythoncapi_compat.h#L482-L492 +#if 0x030600B1 <= PY_VERSION_HEX && PY_VERSION_HEX <= 0x030B00A1 && !defined(PYPY_VERSION) + _PyFloat_Pack2(f, (unsigned char*)&result, 1); +#else + PyFloat_Pack2(f, (char*)&result, 1); +#endif + return result; +}} + +static uint16_t pack_bf16(double f) {{ + float f32 = (float)f; + uint32_t u32 = *(uint32_t*)&f32; + return (uint16_t)(u32 >> 16); +}} + +static uint32_t pack_fp32(double f) {{ + float f32 = (float)f; + return *(uint32_t*)&f32; +}} + +static uint64_t pack_fp64(double f) {{ + return *(uint64_t*)&f; +}} + +static PyObject* launch(PyObject* self, PyObject* args) {{ + int gridX, gridY, gridZ; + uint64_t _stream; + uint64_t _function; + int launch_cooperative_grid; + PyObject *profile_scratch_obj = NULL; + PyObject *launch_enter_hook = NULL; + PyObject *launch_exit_hook = NULL; + PyObject *kernel_metadata = NULL; + PyObject *launch_metadata = NULL; + {' '.join([f"{_extracted_type(ty)} _arg{i}; " for i, ty in signature.items()])} + if(!PyArg_ParseTuple(args, \"{format}\", &launch_cooperative_grid, + &gridX, &gridY, &gridZ, &_stream, &_function, &profile_scratch_obj, + &kernel_metadata, &launch_metadata, + &launch_enter_hook, &launch_exit_hook {args_list})) {{ + return NULL; + }} + + {' '.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* ret = PyObject_CallOneArg(launch_enter_hook, launch_metadata); + if (!ret) + return NULL; + Py_DECREF(ret); + }} + + hipDeviceptr_t profile_scratch = 0; + if (profile_scratch_obj != Py_None) {{ + DevicePtrInfo profile_scratch_info = getPointer(profile_scratch_obj, -1); + if (!profile_scratch_info.valid) {{ + return NULL; + }} + profile_scratch = profile_scratch_info.dev_ptr; + }} + + // raise exception asap + {"; ".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, (hipDeviceptr_t)profile_scratch{', ' + ', '.join(internal_args_list) if len(internal_args_list) > 0 else ''}); + + if(launch_exit_hook != Py_None){{ + PyObject* ret = PyObject_CallOneArg(launch_exit_hook, launch_metadata); + if (!ret) + return NULL; + Py_DECREF(ret); + }} + + if(PyErr_Occurred()) {{ + return NULL; + }} + Py_RETURN_NONE; +}} + +static PyMethodDef ModuleMethods[] = {{ + {{"launch", launch, METH_VARARGS, "Entry point for all kernels with this signature"}}, + {{NULL, NULL, 0, NULL}} // sentinel +}}; + +static struct PyModuleDef ModuleDef = {{ + PyModuleDef_HEAD_INIT, + \"__triton_launcher\", + NULL, //documentation + -1, //size + ModuleMethods +}}; + +PyMODINIT_FUNC PyInit___triton_launcher(void) {{ + if (!initSymbolTable()) {{ + return NULL; + }} + PyObject *m = PyModule_Create(&ModuleDef); + if(m == NULL) {{ + return NULL; + }} + data_ptr_str = PyUnicode_InternFromString("data_ptr"); + if(data_ptr_str == NULL) {{ + return NULL; + }} + 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.padding == "nan", *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 + self.profile_scratch_size = metadata.profile_scratch_size + self.profile_scratch_align = metadata.profile_scratch_align + + def __call__(self, gridX, gridY, gridZ, stream, function, *args): + + def allocate_scratch(size, align, allocator): + if size > 0: + grid_size = gridX * gridY * gridZ + alloc_size = grid_size * size + alloc_fn = allocator.get() + return alloc_fn(alloc_size, align, stream) + return None + + profile_scratch = allocate_scratch(self.profile_scratch_size, self.profile_scratch_align, + _allocation._profile_allocator) + + self.launch(self.launch_cooperative_grid, gridX, gridY, gridZ, stream, function, profile_scratch, *args) + + +class HIPDriver(GPUDriver): + + def __init__(self): + super().__init__() + self.utils = HIPUtils() + self.launcher_cls = HIPLauncher + + def get_device_interface(self): + import torch + return torch.cuda + + @staticmethod + def is_active(): + try: + import torch + return torch.cuda.is_available() and (torch.version.hip is not None) + except ImportError: + return False + + def map_python_to_cpp_type(self, ty: str) -> str: + return ty_to_cpp(ty) + + def get_current_target(self): + device = self.get_current_device() + device_properties = self.utils.get_device_properties(device) + arch = knobs.runtime.override_arch or device_properties['arch'] + warp_size = device_properties['warpSize'] + return GPUTarget("hip", arch.split(':')[0], warp_size) + + def get_active_torch_device(self): + import torch + # when using hip devices, the device string in pytorch is "cuda" + return torch.device("cuda", self.get_current_device()) + + def get_benchmarker(self): + from triton.testing import do_bench + return do_bench + + def get_empty_cache_for_benchmark(self): + import torch + + # It's the same as the Nvidia backend. + cache_size = 256 * 1024 * 1024 + return torch.empty(int(cache_size // 4), dtype=torch.int, device='cuda') + + def clear_cache(self, cache): + cache.zero_() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_channel_descriptor.h b/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_device_functions.h b/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_atomic.h b/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_bf16.h b/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_bfloat16.h b/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_common.h b/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_complex.h b/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_cooperative_groups.h b/Scripts_Climate_n_LAI_to_Yield/.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/Scripts_Climate_n_LAI_to_Yield/.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(0), + uint64_t mask = static_cast(0)) { + _type = type; + _size = size; + _mask = mask; + } + + struct _tiled_info { + bool is_tiled; + unsigned int size; + unsigned int meta_group_rank; + unsigned int meta_group_size; + }; + + struct _coalesced_info { + lane_mask member_mask; + unsigned int size; + struct _tiled_info tiled_info; + } coalesced_info; + + friend __CG_QUALIFIER__ thread_group tiled_partition(const thread_group& parent, + unsigned int tile_size); + friend class thread_block; + + public: + // Total number of threads in the thread group, and this serves the purpose + // for all derived cooperative group types since their `size` is directly + // saved during the construction + __CG_QUALIFIER__ uint32_t size() const { return _size; } + __CG_QUALIFIER__ unsigned int cg_type() const { return _type; } + // Rank of the calling thread within [0, size()) + __CG_QUALIFIER__ uint32_t thread_rank() const; + // Is this cooperative group type valid? + __CG_QUALIFIER__ bool is_valid() const; + // synchronize the threads in the thread group + __CG_QUALIFIER__ void sync() const; +}; +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup CooperativeG Cooperative Groups + * @ingroup API + * @{ + * This section describes the cooperative groups functions of HIP runtime API. + * + * The cooperative groups provides flexible thread parallel programming algorithms, threads + * cooperate and share data to perform collective computations. + * + * @note Cooperative groups feature is implemented on Linux, under developement + * on Windows. + * + */ +/** \brief The multi-grid cooperative group type + * + * \details Represents an inter-device cooperative group type where the + * participating threads within the group spans across multple + * devices, running the (same) kernel on these devices + * @note The multi-grid cooperative group type is implemented on Linux, under developement + * on Windows. + */ +class multi_grid_group : public thread_group { + // Only these friend functions are allowed to construct an object of this class + // and access its resources + friend __CG_QUALIFIER__ multi_grid_group this_multi_grid(); + + protected: + // Construct mutli-grid thread group (through the API this_multi_grid()) + explicit __CG_QUALIFIER__ multi_grid_group(uint32_t size) + : thread_group(internal::cg_multi_grid, size) {} + + public: + // Number of invocations participating in this multi-grid group. In other + // words, the number of GPUs + __CG_QUALIFIER__ uint32_t num_grids() { return internal::multi_grid::num_grids(); } + // Rank of this invocation. In other words, an ID number within the range + // [0, num_grids()) of the GPU, this kernel is running on + __CG_QUALIFIER__ uint32_t grid_rank() { return internal::multi_grid::grid_rank(); } + __CG_QUALIFIER__ uint32_t thread_rank() const { return internal::multi_grid::thread_rank(); } + __CG_QUALIFIER__ bool is_valid() const { return internal::multi_grid::is_valid(); } + __CG_QUALIFIER__ void sync() const { internal::multi_grid::sync(); } +}; + +/** @brief User exposed API interface to construct multi-grid cooperative + * group type object - `multi_grid_group` + * + * \details User is not allowed to directly construct an object of type + * `multi_grid_group`. Instead, he should construct it through this + * API function + * @note This multi-grid cooperative API type is implemented on Linux, under developement + * on Windows. + */ +__CG_QUALIFIER__ multi_grid_group this_multi_grid() { + return multi_grid_group(internal::multi_grid::size()); +} + +/** @brief The grid cooperative group type + * + * \details Represents an inter-workgroup cooperative group type where the + * participating threads within the group spans across multiple + * workgroups running the (same) kernel on the same device + * @note This is implemented on Linux, under developement + * on Windows. + */ +class grid_group : public thread_group { + // Only these friend functions are allowed to construct an object of this class + // and access its resources + friend __CG_QUALIFIER__ grid_group this_grid(); + + protected: + // Construct grid thread group (through the API this_grid()) + explicit __CG_QUALIFIER__ grid_group(uint32_t size) : thread_group(internal::cg_grid, size) {} + + public: + __CG_QUALIFIER__ uint32_t thread_rank() const { return internal::grid::thread_rank(); } + __CG_QUALIFIER__ bool is_valid() const { return internal::grid::is_valid(); } + __CG_QUALIFIER__ void sync() const { internal::grid::sync(); } +}; + +/** @brief User exposed API interface to construct grid cooperative group type + * object - `grid_group` + * + * \details User is not allowed to directly construct an object of type + * `multi_grid_group`. Instead, he should construct it through this + * API function + * @note This function is implemented on Linux, under developement + * on Windows. + */ +__CG_QUALIFIER__ grid_group this_grid() { return grid_group(internal::grid::size()); } + +/** @brief The workgroup (thread-block in CUDA terminology) cooperative group + * type + * + * \details Represents an intra-workgroup cooperative group type where the + * participating threads within the group are exactly the same threads + * which are participated in the currently executing `workgroup` + * @note This is implemented on Linux, under developement + * on Windows. + */ +class thread_block : public thread_group { + // Only these friend functions are allowed to construct an object of thi + // class and access its resources + friend __CG_QUALIFIER__ thread_block this_thread_block(); + friend __CG_QUALIFIER__ thread_group tiled_partition(const thread_group& parent, + unsigned int tile_size); + friend __CG_QUALIFIER__ thread_group tiled_partition(const thread_block& parent, + unsigned int tile_size); + protected: + // Construct a workgroup thread group (through the API this_thread_block()) + explicit __CG_QUALIFIER__ thread_block(uint32_t size) + : thread_group(internal::cg_workgroup, size) {} + + __CG_QUALIFIER__ thread_group new_tiled_group(unsigned int tile_size) const { + const bool pow2 = ((tile_size & (tile_size - 1)) == 0); + // Invalid tile size, assert + if (!tile_size || (tile_size > __AMDGCN_WAVEFRONT_SIZE) || !pow2) { + __hip_assert(false && "invalid tile size"); + } + + auto block_size = size(); + auto rank = thread_rank(); + auto partitions = (block_size + tile_size - 1) / tile_size; + auto tail = (partitions * tile_size) - block_size; + auto partition_size = tile_size - tail * (rank >= (partitions - 1) * tile_size); + thread_group tiledGroup = thread_group(internal::cg_tiled_group, partition_size); + + tiledGroup.coalesced_info.tiled_info.size = tile_size; + tiledGroup.coalesced_info.tiled_info.is_tiled = true; + tiledGroup.coalesced_info.tiled_info.meta_group_rank = rank / tile_size; + tiledGroup.coalesced_info.tiled_info.meta_group_size = partitions; + return tiledGroup; + } + + public: + // 3-dimensional block index within the grid + __CG_STATIC_QUALIFIER__ dim3 group_index() { return internal::workgroup::group_index(); } + // 3-dimensional thread index within the block + __CG_STATIC_QUALIFIER__ dim3 thread_index() { return internal::workgroup::thread_index(); } + __CG_STATIC_QUALIFIER__ uint32_t thread_rank() { return internal::workgroup::thread_rank(); } + __CG_STATIC_QUALIFIER__ uint32_t size() { return internal::workgroup::size(); } + __CG_STATIC_QUALIFIER__ bool is_valid() { return internal::workgroup::is_valid(); } + __CG_STATIC_QUALIFIER__ void sync() { internal::workgroup::sync(); } + __CG_QUALIFIER__ dim3 group_dim() { return internal::workgroup::block_dim(); } +}; + +/** \brief User exposed API interface to construct workgroup cooperative + * group type object - `thread_block`. + * + * \details User is not allowed to directly construct an object of type + * `thread_block`. Instead, he should construct it through this API + * function. + * @note This function is implemented on Linux, under developement + * on Windows. + */ +__CG_QUALIFIER__ thread_block this_thread_block() { + return thread_block(internal::workgroup::size()); +} + +/** \brief The tiled_group cooperative group type + * + * \details Represents one tiled thread group in a wavefront. + * This group type also supports sub-wave level intrinsics. + * @note This is implemented on Linux, under developement + * on Windows. + */ + +class tiled_group : public thread_group { + private: + friend __CG_QUALIFIER__ thread_group tiled_partition(const thread_group& parent, + unsigned int tile_size); + friend __CG_QUALIFIER__ tiled_group tiled_partition(const tiled_group& parent, + unsigned int tile_size); + + __CG_QUALIFIER__ tiled_group new_tiled_group(unsigned int tile_size) const { + const bool pow2 = ((tile_size & (tile_size - 1)) == 0); + + if (!tile_size || (tile_size > __AMDGCN_WAVEFRONT_SIZE) || !pow2) { + __hip_assert(false && "invalid tile size"); + } + + if (size() <= tile_size) { + return *this; + } + + tiled_group tiledGroup = tiled_group(tile_size); + tiledGroup.coalesced_info.tiled_info.is_tiled = true; + return tiledGroup; + } + + protected: + explicit __CG_QUALIFIER__ tiled_group(unsigned int tileSize) + : thread_group(internal::cg_tiled_group, tileSize) { + coalesced_info.tiled_info.size = tileSize; + coalesced_info.tiled_info.is_tiled = true; + } + + public: + __CG_QUALIFIER__ unsigned int size() const { return (coalesced_info.tiled_info.size); } + + __CG_QUALIFIER__ unsigned int thread_rank() const { + return (internal::workgroup::thread_rank() & (coalesced_info.tiled_info.size - 1)); + } + + __CG_QUALIFIER__ void sync() const { + internal::tiled_group::sync(); + } +}; + +/** \brief The coalesced_group cooperative group type + * + * \details Represents a active thread group in a wavefront. + * This group type also supports sub-wave level intrinsics. + * @note This is implemented on Linux, under developement + * on Windows. + */ +class coalesced_group : public thread_group { + private: + friend __CG_QUALIFIER__ coalesced_group coalesced_threads(); + friend __CG_QUALIFIER__ thread_group tiled_partition(const thread_group& parent, unsigned int tile_size); + friend __CG_QUALIFIER__ coalesced_group tiled_partition(const coalesced_group& parent, unsigned int tile_size); + + __CG_QUALIFIER__ coalesced_group new_tiled_group(unsigned int tile_size) const { + const bool pow2 = ((tile_size & (tile_size - 1)) == 0); + + if (!tile_size || (tile_size > size()) || !pow2) { + return coalesced_group(0); + } + + // If a tiled group is passed to be partitioned further into a coalesced_group. + // prepare a mask for further partitioning it so that it stays coalesced. + if (coalesced_info.tiled_info.is_tiled) { + unsigned int base_offset = (thread_rank() & (~(tile_size - 1))); + unsigned int masklength = min(static_cast(size()) - base_offset, tile_size); + lane_mask member_mask = static_cast(-1) >> (__AMDGCN_WAVEFRONT_SIZE - masklength); + + member_mask <<= (__lane_id() & ~(tile_size - 1)); + coalesced_group coalesced_tile = coalesced_group(member_mask); + coalesced_tile.coalesced_info.tiled_info.is_tiled = true; + coalesced_tile.coalesced_info.tiled_info.meta_group_rank = thread_rank() / tile_size; + coalesced_tile.coalesced_info.tiled_info.meta_group_size = size() / tile_size; + return coalesced_tile; + } + // Here the parent coalesced_group is not partitioned. + else { + lane_mask member_mask = 0; + unsigned int tile_rank = 0; + int lanes_to_skip = ((thread_rank()) / tile_size) * tile_size; + + for (unsigned int i = 0; i < __AMDGCN_WAVEFRONT_SIZE; i++) { + lane_mask active = coalesced_info.member_mask & (1 << i); + // Make sure the lane is active + if (active) { + if (lanes_to_skip <= 0 && tile_rank < tile_size) { + // Prepare a member_mask that is appropriate for a tile + member_mask |= active; + tile_rank++; + } + lanes_to_skip--; + } + } + coalesced_group coalesced_tile = coalesced_group(member_mask); + coalesced_tile.coalesced_info.tiled_info.meta_group_rank = thread_rank() / tile_size; + coalesced_tile.coalesced_info.tiled_info.meta_group_size = + (size() + tile_size - 1) / tile_size; + return coalesced_tile; + } + return coalesced_group(0); + } + + protected: + // Constructor + explicit __CG_QUALIFIER__ coalesced_group(lane_mask member_mask) + : thread_group(internal::cg_coalesced_group) { + coalesced_info.member_mask = member_mask; // Which threads are active + coalesced_info.size = __popcll(coalesced_info.member_mask); // How many threads are active + coalesced_info.tiled_info.is_tiled = false; // Not a partitioned group + coalesced_info.tiled_info.meta_group_rank = 0; + coalesced_info.tiled_info.meta_group_size = 1; + } + + public: + __CG_QUALIFIER__ unsigned int size() const { + return coalesced_info.size; + } + + __CG_QUALIFIER__ unsigned int thread_rank() const { + return internal::coalesced_group::masked_bit_count(coalesced_info.member_mask); + } + + __CG_QUALIFIER__ void sync() const { + internal::coalesced_group::sync(); + } + + __CG_QUALIFIER__ unsigned int meta_group_rank() const { + return coalesced_info.tiled_info.meta_group_rank; + } + + __CG_QUALIFIER__ unsigned int meta_group_size() const { + return coalesced_info.tiled_info.meta_group_size; + } + + template + __CG_QUALIFIER__ T shfl(T var, int srcRank) const { + static_assert(is_valid_type::value, "Neither an integer or float type."); + + srcRank = srcRank % static_cast(size()); + + int lane = (size() == __AMDGCN_WAVEFRONT_SIZE) ? srcRank + : (__AMDGCN_WAVEFRONT_SIZE == 64) ? __fns64(coalesced_info.member_mask, 0, (srcRank + 1)) + : __fns32(coalesced_info.member_mask, 0, (srcRank + 1)); + + return __shfl(var, lane, __AMDGCN_WAVEFRONT_SIZE); + } + + template + __CG_QUALIFIER__ T shfl_down(T var, unsigned int lane_delta) const { + static_assert(is_valid_type::value, "Neither an integer or float type."); + + // Note: The cuda implementation appears to use the remainder of lane_delta + // and WARP_SIZE as the shift value rather than lane_delta itself. + // This is not described in the documentation and is not done here. + + if (size() == __AMDGCN_WAVEFRONT_SIZE) { + return __shfl_down(var, lane_delta, __AMDGCN_WAVEFRONT_SIZE); + } + + int lane; + if (__AMDGCN_WAVEFRONT_SIZE == 64) { + lane = __fns64(coalesced_info.member_mask, __lane_id(), lane_delta + 1); + } + else { + lane = __fns32(coalesced_info.member_mask, __lane_id(), lane_delta + 1); + } + + if (lane == -1) { + lane = __lane_id(); + } + + return __shfl(var, lane, __AMDGCN_WAVEFRONT_SIZE); + } + + template + __CG_QUALIFIER__ T shfl_up(T var, unsigned int lane_delta) const { + static_assert(is_valid_type::value, "Neither an integer or float type."); + + // Note: The cuda implementation appears to use the remainder of lane_delta + // and WARP_SIZE as the shift value rather than lane_delta itself. + // This is not described in the documentation and is not done here. + + if (size() == __AMDGCN_WAVEFRONT_SIZE) { + return __shfl_up(var, lane_delta, __AMDGCN_WAVEFRONT_SIZE); + } + + int lane; + if (__AMDGCN_WAVEFRONT_SIZE == 64) { + lane = __fns64(coalesced_info.member_mask, __lane_id(), -(lane_delta + 1)); + } + else if (__AMDGCN_WAVEFRONT_SIZE == 32) { + lane = __fns32(coalesced_info.member_mask, __lane_id(), -(lane_delta + 1)); + } + + if (lane == -1) { + lane = __lane_id(); + } + + return __shfl(var, lane, __AMDGCN_WAVEFRONT_SIZE); + } +}; + +/** \brief User exposed API to create coalesced groups. + * + * \details A collective operation that groups all active lanes into a new thread group. + * @note This function is implemented on Linux, under developement + * on Windows. + */ + +__CG_QUALIFIER__ coalesced_group coalesced_threads() { + return cooperative_groups::coalesced_group(__builtin_amdgcn_read_exec()); +} + +/** + * Implemenation of all publicly exposed base class APIs + * @note This function is implemented on Linux, under developement + * on Windows. + */ +__CG_QUALIFIER__ uint32_t thread_group::thread_rank() const { + switch (this->_type) { + case internal::cg_multi_grid: { + return (static_cast(this)->thread_rank()); + } + case internal::cg_grid: { + return (static_cast(this)->thread_rank()); + } + case internal::cg_workgroup: { + return (static_cast(this)->thread_rank()); + } + case internal::cg_tiled_group: { + return (static_cast(this)->thread_rank()); + } + case internal::cg_coalesced_group: { + return (static_cast(this)->thread_rank()); + } + default: { + __hip_assert(false && "invalid cooperative group type"); + return -1; + } + } +} +/** + * Implemenation of all publicly exposed thread group API + * @note This function is implemented on Linux, under developement + * on Windows. + */ +__CG_QUALIFIER__ bool thread_group::is_valid() const { + switch (this->_type) { + case internal::cg_multi_grid: { + return (static_cast(this)->is_valid()); + } + case internal::cg_grid: { + return (static_cast(this)->is_valid()); + } + case internal::cg_workgroup: { + return (static_cast(this)->is_valid()); + } + case internal::cg_tiled_group: { + return (static_cast(this)->is_valid()); + } + case internal::cg_coalesced_group: { + return (static_cast(this)->is_valid()); + } + default: { + __hip_assert(false && "invalid cooperative group type"); + return false; + } + } +} +/** + * Implemenation of all publicly exposed thread group sync API + * @note This function is implemented on Linux, under developement + * on Windows. + */ +__CG_QUALIFIER__ void thread_group::sync() const { + switch (this->_type) { + case internal::cg_multi_grid: { + static_cast(this)->sync(); + break; + } + case internal::cg_grid: { + static_cast(this)->sync(); + break; + } + case internal::cg_workgroup: { + static_cast(this)->sync(); + break; + } + case internal::cg_tiled_group: { + static_cast(this)->sync(); + break; + } + case internal::cg_coalesced_group: { + static_cast(this)->sync(); + break; + } + default: { + __hip_assert(false && "invalid cooperative group type"); + } + } +} + +/** + * Implemenation of publicly exposed `wrapper` API on top of basic cooperative + * group type APIs + * @note This function is implemented on Linux, under developement + * on Windows. + */ +template __CG_QUALIFIER__ uint32_t group_size(CGTy const& g) { return g.size(); } +/** + * Implemenation of publicly exposed `wrapper` API on top of basic cooperative + * group type APIs + * @note This function is implemented on Linux, under developement + * on Windows. + */ +template __CG_QUALIFIER__ uint32_t thread_rank(CGTy const& g) { + return g.thread_rank(); +} +/** + * Implemenation of publicly exposed `wrapper` API on top of basic cooperative + * group type APIs + * @note This function is implemented on Linux, under developement + * on Windows. + */ +template __CG_QUALIFIER__ bool is_valid(CGTy const& g) { return g.is_valid(); } +/** + * Implemenation of publicly exposed `wrapper` API on top of basic cooperative + * group type APIs + * @note This function is implemented on Linux, under developement + * on Windows. + */ +template __CG_QUALIFIER__ void sync(CGTy const& g) { g.sync(); } +/** + * template class tile_base + * @note This class is implemented on Linux, under developement + * on Windows. + */ +template class tile_base { + protected: + _CG_STATIC_CONST_DECL_ unsigned int numThreads = tileSize; + + public: + // Rank of the thread within this tile + _CG_STATIC_CONST_DECL_ unsigned int thread_rank() { + return (internal::workgroup::thread_rank() & (numThreads - 1)); + } + + // Number of threads within this tile + __CG_STATIC_QUALIFIER__ unsigned int size() { return numThreads; } +}; +/** + * template class thread_block_tile_base + * @note This class is implemented on Linux, under developement + * on Windows. + */ +template class thread_block_tile_base : public tile_base { + static_assert(is_valid_tile_size::value, + "Tile size is either not a power of 2 or greater than the wavefront size"); + using tile_base::numThreads; + + public: + __CG_STATIC_QUALIFIER__ void sync() { + internal::tiled_group::sync(); + } + + template __CG_QUALIFIER__ T shfl(T var, int srcRank) const { + static_assert(is_valid_type::value, "Neither an integer or float type."); + return (__shfl(var, srcRank, numThreads)); + } + + template __CG_QUALIFIER__ T shfl_down(T var, unsigned int lane_delta) const { + static_assert(is_valid_type::value, "Neither an integer or float type."); + return (__shfl_down(var, lane_delta, numThreads)); + } + + template __CG_QUALIFIER__ T shfl_up(T var, unsigned int lane_delta) const { + static_assert(is_valid_type::value, "Neither an integer or float type."); + return (__shfl_up(var, lane_delta, numThreads)); + } + + template __CG_QUALIFIER__ T shfl_xor(T var, unsigned int laneMask) const { + static_assert(is_valid_type::value, "Neither an integer or float type."); + return (__shfl_xor(var, laneMask, numThreads)); + } +}; +/** \brief User exposed API that captures the state of the parent group pre-partition + */ +template +class parent_group_info { +public: + // Returns the linear rank of the group within the set of tiles partitioned + // from a parent group (bounded by meta_group_size) + __CG_STATIC_QUALIFIER__ unsigned int meta_group_rank() { + return ParentCGTy::thread_rank() / tileSize; + } + + // Returns the number of groups created when the parent group was partitioned. + __CG_STATIC_QUALIFIER__ unsigned int meta_group_size() { + return (ParentCGTy::size() + tileSize - 1) / tileSize; + } +}; + +/** \brief Group type - thread_block_tile + * + * \details Represents one tile of thread group. + * @note This type is implemented on Linux, under developement + * on Windows. + */ +template +class thread_block_tile_type : public thread_block_tile_base, + public tiled_group, + public parent_group_info { + _CG_STATIC_CONST_DECL_ unsigned int numThreads = tileSize; + typedef thread_block_tile_base tbtBase; + protected: + __CG_QUALIFIER__ thread_block_tile_type() : tiled_group(numThreads) { + coalesced_info.tiled_info.size = numThreads; + coalesced_info.tiled_info.is_tiled = true; + } + public: + using tbtBase::size; + using tbtBase::sync; + using tbtBase::thread_rank; +}; + +// Partial template specialization +template +class thread_block_tile_type : public thread_block_tile_base, + public tiled_group + { + _CG_STATIC_CONST_DECL_ unsigned int numThreads = tileSize; + + typedef thread_block_tile_base tbtBase; + + protected: + + __CG_QUALIFIER__ thread_block_tile_type(unsigned int meta_group_rank, unsigned int meta_group_size) + : tiled_group(numThreads) { + coalesced_info.tiled_info.size = numThreads; + coalesced_info.tiled_info.is_tiled = true; + coalesced_info.tiled_info.meta_group_rank = meta_group_rank; + coalesced_info.tiled_info.meta_group_size = meta_group_size; + } + + public: + using tbtBase::size; + using tbtBase::sync; + using tbtBase::thread_rank; + + __CG_QUALIFIER__ unsigned int meta_group_rank() const { + return coalesced_info.tiled_info.meta_group_rank; + } + + __CG_QUALIFIER__ unsigned int meta_group_size() const { + return coalesced_info.tiled_info.meta_group_size; + } +// end of operative group +/** +* @} +*/ +}; + + +/** \brief User exposed API to partition groups. + * + * \details A collective operation that partitions the parent group into a one-dimensional, + * row-major, tiling of subgroups. + */ + +__CG_QUALIFIER__ thread_group tiled_partition(const thread_group& parent, unsigned int tile_size) { + if (parent.cg_type() == internal::cg_tiled_group) { + const tiled_group* cg = static_cast(&parent); + return cg->new_tiled_group(tile_size); + } + else if(parent.cg_type() == internal::cg_coalesced_group) { + const coalesced_group* cg = static_cast(&parent); + return cg->new_tiled_group(tile_size); + } + else { + const thread_block* tb = static_cast(&parent); + return tb->new_tiled_group(tile_size); + } +} + +// Thread block type overload +__CG_QUALIFIER__ thread_group tiled_partition(const thread_block& parent, unsigned int tile_size) { + return (parent.new_tiled_group(tile_size)); +} + +__CG_QUALIFIER__ tiled_group tiled_partition(const tiled_group& parent, unsigned int tile_size) { + return (parent.new_tiled_group(tile_size)); +} + +// If a coalesced group is passed to be partitioned, it should remain coalesced +__CG_QUALIFIER__ coalesced_group tiled_partition(const coalesced_group& parent, unsigned int tile_size) { + return (parent.new_tiled_group(tile_size)); +} + +template class thread_block_tile; + +namespace impl { +template class thread_block_tile_internal; + +template +class thread_block_tile_internal : public thread_block_tile_type { + protected: + template + __CG_QUALIFIER__ thread_block_tile_internal( + const thread_block_tile_internal& g) + : thread_block_tile_type(g.meta_group_rank(), g.meta_group_size()) {} + + __CG_QUALIFIER__ thread_block_tile_internal(const thread_block& g) + : thread_block_tile_type() {} +}; +} // namespace impl + +template +class thread_block_tile : public impl::thread_block_tile_internal { + protected: + __CG_QUALIFIER__ thread_block_tile(const ParentCGTy& g) + : impl::thread_block_tile_internal(g) {} + + public: + __CG_QUALIFIER__ operator thread_block_tile() const { + return thread_block_tile(*this); + } +}; + + +template +class thread_block_tile : public impl::thread_block_tile_internal { + template friend class thread_block_tile; + + protected: + public: + template + __CG_QUALIFIER__ thread_block_tile(const thread_block_tile& g) + : impl::thread_block_tile_internal(g) {} +}; + +template class thread_block_tile; + +namespace impl { +template struct tiled_partition_internal; + +template +struct tiled_partition_internal : public thread_block_tile { + __CG_QUALIFIER__ tiled_partition_internal(const thread_block& g) + : thread_block_tile(g) {} +}; + +} // namespace impl + +/** \brief User exposed API to partition groups. + * + * \details This constructs a templated class derieved from thread_group. + * The template defines tile size of the new thread group at compile time. + */ +template +__CG_QUALIFIER__ thread_block_tile tiled_partition(const ParentCGTy& g) { + static_assert(is_valid_tile_size::value, + "Tiled partition with size > wavefront size. Currently not supported "); + return impl::tiled_partition_internal(g); +} +} // namespace cooperative_groups + +#endif // __cplusplus +#endif // HIP_INCLUDE_HIP_AMD_DETAIL_HIP_COOPERATIVE_GROUPS_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_fp16.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_fp16.h new file mode 100644 index 0000000000000000000000000000000000000000..62d88a3756b1ac2607593ca7c52a44a5034db6a2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_fp16.h @@ -0,0 +1,1809 @@ +/* +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. +*/ + +#pragma once +#ifndef HIP_INCLUDE_HIP_AMD_DETAIL_HIP_FP16_H +#define HIP_INCLUDE_HIP_AMD_DETAIL_HIP_FP16_H + +#if defined(__HIPCC_RTC__) + #define __HOST_DEVICE__ __device__ +#else + #define __HOST_DEVICE__ __host__ __device__ + #include + #include "hip/amd_detail/host_defines.h" + #include + #if defined(__cplusplus) + #include + #include + #include +#endif +#endif // !defined(__HIPCC_RTC__) + +#if defined(__clang__) && defined(__HIP__) + typedef _Float16 _Float16_2 __attribute__((ext_vector_type(2))); + + struct __half_raw { + union { + static_assert(sizeof(_Float16) == sizeof(unsigned short), ""); + + _Float16 data; + unsigned short x; + }; + }; + + struct __half2_raw { + union { + static_assert(sizeof(_Float16_2) == sizeof(unsigned short[2]), ""); + + struct { + __half_raw x; + __half_raw y; + }; + _Float16_2 data; + }; + }; + + #if defined(__cplusplus) + #if !defined(__HIPCC_RTC__) + #include "hip_fp16_math_fwd.h" + #include "amd_hip_vector_types.h" + #include "host_defines.h" + #include "amd_device_functions.h" + #include "amd_warp_functions.h" + #endif + namespace std + { + template<> struct is_floating_point<_Float16> : std::true_type {}; + } + + template + using Enable_if_t = typename std::enable_if::type; + + // BEGIN STRUCT __HALF + struct __half { + protected: + union { + static_assert(sizeof(_Float16) == sizeof(unsigned short), ""); + + _Float16 data; + unsigned short __x; + }; + public: + // CREATORS + __HOST_DEVICE__ + __half() = default; + __HOST_DEVICE__ + __half(const __half_raw& x) : data{x.data} {} + #if !defined(__HIP_NO_HALF_CONVERSIONS__) + __HOST_DEVICE__ + __half(decltype(data) x) : data{x} {} + template< + typename T, + Enable_if_t{}>* = nullptr> + __HOST_DEVICE__ + __half(T x) : data{static_cast<_Float16>(x)} {} + #endif + __HOST_DEVICE__ + __half(const __half&) = default; + __HOST_DEVICE__ + __half(__half&&) = default; + __HOST_DEVICE__ + ~__half() = default; + + // CREATORS - DEVICE ONLY + #if !defined(__HIP_NO_HALF_CONVERSIONS__) + template< + typename T, Enable_if_t{}>* = nullptr> + __HOST_DEVICE__ + __half(T x) : data{static_cast<_Float16>(x)} {} + #endif + + // MANIPULATORS + __HOST_DEVICE__ + __half& operator=(const __half&) = default; + __HOST_DEVICE__ + __half& operator=(__half&&) = default; + __HOST_DEVICE__ + __half& operator=(const __half_raw& x) + { + data = x.data; + return *this; + } + __HOST_DEVICE__ + volatile __half& operator=(const __half_raw& x) volatile + { + data = x.data; + return *this; + } + volatile __half& operator=(const volatile __half_raw& x) volatile + { + data = x.data; + return *this; + } + __half& operator=(__half_raw&& x) + { + data = x.data; + return *this; + } + volatile __half& operator=(__half_raw&& x) volatile + { + data = x.data; + return *this; + } + volatile __half& operator=(volatile __half_raw&& x) volatile + { + data = x.data; + return *this; + } + #if !defined(__HIP_NO_HALF_CONVERSIONS__) + template< + typename T, + Enable_if_t{}>* = nullptr> + __HOST_DEVICE__ + __half& operator=(T x) + { + data = static_cast<_Float16>(x); + return *this; + } + #endif + + // MANIPULATORS - DEVICE ONLY + #if !defined(__HIP_NO_HALF_CONVERSIONS__) + template< + typename T, Enable_if_t{}>* = nullptr> + __device__ + __half& operator=(T x) + { + data = static_cast<_Float16>(x); + return *this; + } + #endif + + #if !defined(__HIP_NO_HALF_OPERATORS__) + __device__ + __half& operator+=(const __half& x) + { + data += x.data; + return *this; + } + __device__ + __half& operator-=(const __half& x) + { + data -= x.data; + return *this; + } + __device__ + __half& operator*=(const __half& x) + { + data *= x.data; + return *this; + } + __device__ + __half& operator/=(const __half& x) + { + data /= x.data; + return *this; + } + __device__ + __half& operator++() { ++data; return *this; } + __device__ + __half operator++(int) + { + __half tmp{*this}; + ++*this; + return tmp; + } + __device__ + __half& operator--() { --data; return *this; } + __device__ + __half operator--(int) + { + __half tmp{*this}; + --*this; + return tmp; + } + #endif + + // ACCESSORS + #if !defined(__HIP_NO_HALF_CONVERSIONS__) + template< + typename T, + Enable_if_t{}>* = nullptr> + __HOST_DEVICE__ + operator T() const { return data; } + #endif + __HOST_DEVICE__ + operator __half_raw() const { return __half_raw{data}; } + __HOST_DEVICE__ + operator __half_raw() const volatile + { + return __half_raw{data}; + } + + #if !defined(__HIP_NO_HALF_CONVERSIONS__) + template< + typename T, Enable_if_t{}>* = nullptr> + __HOST_DEVICE__ + operator T() const { return data; } + #endif + + #if !defined(__HIP_NO_HALF_OPERATORS__) + __device__ + __half operator+() const { return *this; } + __device__ + __half operator-() const + { + __half tmp{*this}; + tmp.data = -tmp.data; + return tmp; + } + #endif + + // FRIENDS + #if !defined(__HIP_NO_HALF_OPERATORS__) + friend + inline + __device__ + __half operator+(const __half& x, const __half& y) + { + return __half{x} += y; + } + friend + inline + __device__ + __half operator-(const __half& x, const __half& y) + { + return __half{x} -= y; + } + friend + inline + __device__ + __half operator*(const __half& x, const __half& y) + { + return __half{x} *= y; + } + friend + inline + __device__ + __half operator/(const __half& x, const __half& y) + { + return __half{x} /= y; + } + friend + inline + __device__ + bool operator==(const __half& x, const __half& y) + { + return x.data == y.data; + } + friend + inline + __device__ + bool operator!=(const __half& x, const __half& y) + { + return !(x == y); + } + friend + inline + __device__ + bool operator<(const __half& x, const __half& y) + { + return x.data < y.data; + } + friend + inline + __device__ + bool operator>(const __half& x, const __half& y) + { + return y.data < x.data; + } + friend + inline + __device__ + bool operator<=(const __half& x, const __half& y) + { + return !(y < x); + } + friend + inline + __device__ + bool operator>=(const __half& x, const __half& y) + { + return !(x < y); + } + #endif // !defined(__HIP_NO_HALF_OPERATORS__) + }; + // END STRUCT __HALF + + // BEGIN STRUCT __HALF2 + struct __half2 { + public: + union { + static_assert( + sizeof(_Float16_2) == sizeof(unsigned short[2]), ""); + + struct { + __half x; + __half y; + }; + _Float16_2 data; + }; + + // CREATORS + __HOST_DEVICE__ + __half2() = default; + __HOST_DEVICE__ + __half2(const __half2_raw& xx) : data{xx.data} {} + __HOST_DEVICE__ + __half2(decltype(data) xx) : data{xx} {} + __HOST_DEVICE__ + __half2(const __half& xx, const __half& yy) + : + data{static_cast<__half_raw>(xx).data, + static_cast<__half_raw>(yy).data} + {} + __HOST_DEVICE__ + __half2(const __half2&) = default; + __HOST_DEVICE__ + __half2(__half2&&) = default; + __HOST_DEVICE__ + ~__half2() = default; + + // MANIPULATORS + __HOST_DEVICE__ + __half2& operator=(const __half2&) = default; + __HOST_DEVICE__ + __half2& operator=(__half2&&) = default; + __HOST_DEVICE__ + __half2& operator=(const __half2_raw& xx) + { + data = xx.data; + return *this; + } + + // MANIPULATORS - DEVICE ONLY + #if !defined(__HIP_NO_HALF_OPERATORS__) + __device__ + __half2& operator+=(const __half2& xx) + { + data += xx.data; + return *this; + } + __device__ + __half2& operator-=(const __half2& xx) + { + data -= xx.data; + return *this; + } + __device__ + __half2& operator*=(const __half2& xx) + { + data *= xx.data; + return *this; + } + __device__ + __half2& operator/=(const __half2& xx) + { + data /= xx.data; + return *this; + } + __device__ + __half2& operator++() { return *this += _Float16_2{1, 1}; } + __device__ + __half2 operator++(int) + { + __half2 tmp{*this}; + ++*this; + return tmp; + } + __device__ + __half2& operator--() { return *this -= _Float16_2{1, 1}; } + __device__ + __half2 operator--(int) + { + __half2 tmp{*this}; + --*this; + return tmp; + } + #endif + + // ACCESSORS + __HOST_DEVICE__ + operator decltype(data)() const { return data; } + __HOST_DEVICE__ + operator __half2_raw() const { + __half2_raw r; + r.data = data; + return r; + } + + // ACCESSORS - DEVICE ONLY + #if !defined(__HIP_NO_HALF_OPERATORS__) + __device__ + __half2 operator+() const { return *this; } + __device__ + __half2 operator-() const + { + __half2 tmp{*this}; + tmp.data = -tmp.data; + return tmp; + } + #endif + + // FRIENDS + #if !defined(__HIP_NO_HALF_OPERATORS__) + friend + inline + __device__ + __half2 operator+(const __half2& xx, const __half2& yy) + { + return __half2{xx} += yy; + } + friend + inline + __device__ + __half2 operator-(const __half2& xx, const __half2& yy) + { + return __half2{xx} -= yy; + } + friend + inline + __device__ + __half2 operator*(const __half2& xx, const __half2& yy) + { + return __half2{xx} *= yy; + } + friend + inline + __device__ + __half2 operator/(const __half2& xx, const __half2& yy) + { + return __half2{xx} /= yy; + } + friend + inline + __device__ + bool operator==(const __half2& xx, const __half2& yy) + { + auto r = xx.data == yy.data; + return r.x != 0 && r.y != 0; + } + friend + inline + __device__ + bool operator!=(const __half2& xx, const __half2& yy) + { + return !(xx == yy); + } + friend + inline + __device__ + bool operator<(const __half2& xx, const __half2& yy) + { + auto r = xx.data < yy.data; + return r.x != 0 && r.y != 0; + } + friend + inline + __device__ + bool operator>(const __half2& xx, const __half2& yy) + { + return yy < xx; + } + friend + inline + __device__ + bool operator<=(const __half2& xx, const __half2& yy) + { + return !(yy < xx); + } + friend + inline + __device__ + bool operator>=(const __half2& xx, const __half2& yy) + { + return !(xx < yy); + } + #endif // !defined(__HIP_NO_HALF_OPERATORS__) + }; + // END STRUCT __HALF2 + + namespace + { + inline + __HOST_DEVICE__ + __half2 make_half2(__half x, __half y) + { + return __half2{x, y}; + } + + inline + __HOST_DEVICE__ + __half __low2half(__half2 x) + { + return __half{__half_raw{static_cast<__half2_raw>(x).data.x}}; + } + + inline + __HOST_DEVICE__ + __half __high2half(__half2 x) + { + return __half{__half_raw{static_cast<__half2_raw>(x).data.y}}; + } + + inline + __HOST_DEVICE__ + __half2 __half2half2(__half x) + { + return __half2{x, x}; + } + + inline + __HOST_DEVICE__ + __half2 __halves2half2(__half x, __half y) + { + return __half2{x, y}; + } + + inline + __HOST_DEVICE__ + __half2 __low2half2(__half2 x) + { + return __half2{ + _Float16_2{ + static_cast<__half2_raw>(x).data.x, + static_cast<__half2_raw>(x).data.x}}; + } + + inline + __HOST_DEVICE__ + __half2 __high2half2(__half2 x) + { + return __half2{ + _Float16_2{ + static_cast<__half2_raw>(x).data.y, + static_cast<__half2_raw>(x).data.y}}; + } + + inline + __HOST_DEVICE__ + __half2 __lows2half2(__half2 x, __half2 y) + { + return __half2{ + _Float16_2{ + static_cast<__half2_raw>(x).data.x, + static_cast<__half2_raw>(y).data.x}}; + } + + inline + __HOST_DEVICE__ + __half2 __highs2half2(__half2 x, __half2 y) + { + return __half2{ + _Float16_2{ + static_cast<__half2_raw>(x).data.y, + static_cast<__half2_raw>(y).data.y}}; + } + + inline + __HOST_DEVICE__ + __half2 __lowhigh2highlow(__half2 x) + { + return __half2{ + _Float16_2{ + static_cast<__half2_raw>(x).data.y, + static_cast<__half2_raw>(x).data.x}}; + } + + // Bitcasts + inline + __device__ + short __half_as_short(__half x) + { + return static_cast<__half_raw>(x).x; + } + + inline + __device__ + unsigned short __half_as_ushort(__half x) + { + return static_cast<__half_raw>(x).x; + } + + inline + __device__ + __half __short_as_half(short x) + { + __half_raw r; r.x = x; + return r; + } + + inline + __device__ + __half __ushort_as_half(unsigned short x) + { + __half_raw r; r.x = x; + return r; + } + + // float -> half | half2 + inline + __HOST_DEVICE__ + __half __float2half(float x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __HOST_DEVICE__ + __half __float2half_rn(float x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + #if !defined(__HIPCC_RTC__) + // TODO: rounding behaviour is not correct for host functions. + inline + __host__ + __half __float2half_rz(float x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __host__ + __half __float2half_rd(float x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __host__ + __half __float2half_ru(float x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + #endif + inline + __device__ + __half __float2half_rz(float x) + { + return __half_raw{__ocml_cvtrtz_f16_f32(x)}; + } + inline + __device__ + __half __float2half_rd(float x) + { + return __half_raw{__ocml_cvtrtn_f16_f32(x)}; + } + inline + __device__ + __half __float2half_ru(float x) + { + return __half_raw{__ocml_cvtrtp_f16_f32(x)}; + } + inline + __HOST_DEVICE__ + __half2 __float2half2_rn(float x) + { + return __half2{ + _Float16_2{ + static_cast<_Float16>(x), static_cast<_Float16>(x)}}; + } + inline + __HOST_DEVICE__ + __half2 __floats2half2_rn(float x, float y) + { + return __half2{_Float16_2{ + static_cast<_Float16>(x), static_cast<_Float16>(y)}}; + } + inline + __HOST_DEVICE__ + __half2 __float22half2_rn(float2 x) + { + return __floats2half2_rn(x.x, x.y); + } + + // half | half2 -> float + inline + __HOST_DEVICE__ + float __half2float(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __HOST_DEVICE__ + float __low2float(__half2 x) + { + return static_cast<__half2_raw>(x).data.x; + } + inline + __HOST_DEVICE__ + float __high2float(__half2 x) + { + return static_cast<__half2_raw>(x).data.y; + } + inline + __HOST_DEVICE__ + float2 __half22float2(__half2 x) + { + return make_float2( + static_cast<__half2_raw>(x).data.x, + static_cast<__half2_raw>(x).data.y); + } + + // half -> int + inline + __device__ + int __half2int_rn(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + int __half2int_rz(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + int __half2int_rd(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + int __half2int_ru(__half x) + { + return static_cast<__half_raw>(x).data; + } + + // int -> half + inline + __device__ + __half __int2half_rn(int x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __int2half_rz(int x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __int2half_rd(int x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __int2half_ru(int x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + + // half -> short + inline + __device__ + short __half2short_rn(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + short __half2short_rz(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + short __half2short_rd(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + short __half2short_ru(__half x) + { + return static_cast<__half_raw>(x).data; + } + + // short -> half + inline + __device__ + __half __short2half_rn(short x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __short2half_rz(short x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __short2half_rd(short x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __short2half_ru(short x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + + // half -> long long + inline + __device__ + long long __half2ll_rn(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + long long __half2ll_rz(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + long long __half2ll_rd(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + long long __half2ll_ru(__half x) + { + return static_cast<__half_raw>(x).data; + } + + // long long -> half + inline + __device__ + __half __ll2half_rn(long long x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __ll2half_rz(long long x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __ll2half_rd(long long x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __ll2half_ru(long long x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + + // half -> unsigned int + inline + __device__ + unsigned int __half2uint_rn(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + unsigned int __half2uint_rz(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + unsigned int __half2uint_rd(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + unsigned int __half2uint_ru(__half x) + { + return static_cast<__half_raw>(x).data; + } + + // unsigned int -> half + inline + __device__ + __half __uint2half_rn(unsigned int x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __uint2half_rz(unsigned int x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __uint2half_rd(unsigned int x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __uint2half_ru(unsigned int x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + + // half -> unsigned short + inline + __device__ + unsigned short __half2ushort_rn(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + unsigned short __half2ushort_rz(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + unsigned short __half2ushort_rd(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + unsigned short __half2ushort_ru(__half x) + { + return static_cast<__half_raw>(x).data; + } + + // unsigned short -> half + inline + __device__ + __half __ushort2half_rn(unsigned short x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __ushort2half_rz(unsigned short x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __ushort2half_rd(unsigned short x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __ushort2half_ru(unsigned short x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + + // half -> unsigned long long + inline + __device__ + unsigned long long __half2ull_rn(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + unsigned long long __half2ull_rz(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + unsigned long long __half2ull_rd(__half x) + { + return static_cast<__half_raw>(x).data; + } + inline + __device__ + unsigned long long __half2ull_ru(__half x) + { + return static_cast<__half_raw>(x).data; + } + + // unsigned long long -> half + inline + __device__ + __half __ull2half_rn(unsigned long long x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __ull2half_rz(unsigned long long x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __ull2half_rd(unsigned long long x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + inline + __device__ + __half __ull2half_ru(unsigned long long x) + { + return __half_raw{static_cast<_Float16>(x)}; + } + + // Load primitives + inline + __device__ + __half __ldg(const __half* ptr) { return *ptr; } + inline + __device__ + __half __ldcg(const __half* ptr) { return *ptr; } + inline + __device__ + __half __ldca(const __half* ptr) { return *ptr; } + inline + __device__ + __half __ldcs(const __half* ptr) { return *ptr; } + + inline + __HOST_DEVICE__ + __half2 __ldg(const __half2* ptr) { return *ptr; } + inline + __HOST_DEVICE__ + __half2 __ldcg(const __half2* ptr) { return *ptr; } + inline + __HOST_DEVICE__ + __half2 __ldca(const __half2* ptr) { return *ptr; } + inline + __HOST_DEVICE__ + __half2 __ldcs(const __half2* ptr) { return *ptr; } + + // Relations + inline + __device__ + bool __heq(__half x, __half y) + { + return static_cast<__half_raw>(x).data == + static_cast<__half_raw>(y).data; + } + inline + __device__ + bool __hne(__half x, __half y) + { + return static_cast<__half_raw>(x).data != + static_cast<__half_raw>(y).data; + } + inline + __device__ + bool __hle(__half x, __half y) + { + return static_cast<__half_raw>(x).data <= + static_cast<__half_raw>(y).data; + } + inline + __device__ + bool __hge(__half x, __half y) + { + return static_cast<__half_raw>(x).data >= + static_cast<__half_raw>(y).data; + } + inline + __device__ + bool __hlt(__half x, __half y) + { + return static_cast<__half_raw>(x).data < + static_cast<__half_raw>(y).data; + } + inline + __device__ + bool __hgt(__half x, __half y) + { + return static_cast<__half_raw>(x).data > + static_cast<__half_raw>(y).data; + } + inline __device__ + bool __hequ(__half x, __half y) { + return !(static_cast<__half_raw>(x).data < static_cast<__half_raw>(y).data) && + !(static_cast<__half_raw>(x).data > static_cast<__half_raw>(y).data); + } + inline __device__ + bool __hneu(__half x, __half y) { + return !(static_cast<__half_raw>(x).data == static_cast<__half_raw>(y).data); + } + inline __device__ + bool __hleu(__half x, __half y) { + return !(static_cast<__half_raw>(x).data > static_cast<__half_raw>(y).data); + } + inline + __device__ + bool __hgeu(__half x, __half y) { + return !(static_cast<__half_raw>(x).data < static_cast<__half_raw>(y).data); + } + inline + __device__ + bool __hltu(__half x, __half y) { + return !(static_cast<__half_raw>(x).data >= static_cast<__half_raw>(y).data); + } + inline + __device__ + bool __hgtu(__half x, __half y) { + return !(static_cast<__half_raw>(x).data <= static_cast<__half_raw>(y).data); + } + + inline + __HOST_DEVICE__ + __half2 __heq2(__half2 x, __half2 y) + { + auto r = static_cast<__half2_raw>(x).data == + static_cast<__half2_raw>(y).data; + return __builtin_convertvector(-r, _Float16_2); + } + inline + __HOST_DEVICE__ + __half2 __hne2(__half2 x, __half2 y) + { + auto r = static_cast<__half2_raw>(x).data != + static_cast<__half2_raw>(y).data; + return __builtin_convertvector(-r, _Float16_2); + } + inline + __HOST_DEVICE__ + __half2 __hle2(__half2 x, __half2 y) + { + auto r = static_cast<__half2_raw>(x).data <= + static_cast<__half2_raw>(y).data; + return __builtin_convertvector(-r, _Float16_2); + } + inline + __HOST_DEVICE__ + __half2 __hge2(__half2 x, __half2 y) + { + auto r = static_cast<__half2_raw>(x).data >= + static_cast<__half2_raw>(y).data; + return __builtin_convertvector(-r, _Float16_2); + } + inline + __HOST_DEVICE__ + __half2 __hlt2(__half2 x, __half2 y) + { + auto r = static_cast<__half2_raw>(x).data < + static_cast<__half2_raw>(y).data; + return __builtin_convertvector(-r, _Float16_2); + } + inline + __HOST_DEVICE__ + __half2 __hgt2(__half2 x, __half2 y) + { + auto r = static_cast<__half2_raw>(x).data > + static_cast<__half2_raw>(y).data; + return __builtin_convertvector(-r, _Float16_2); + } + inline __HOST_DEVICE__ + __half2 __hequ2(__half2 x, __half2 y) { + auto r = !(static_cast<__half2_raw>(x).data < static_cast<__half2_raw>(y).data) && + !(static_cast<__half2_raw>(x).data > static_cast<__half2_raw>(y).data); + return __builtin_convertvector(-r, _Float16_2); + } + inline + __HOST_DEVICE__ + __half2 __hneu2(__half2 x, __half2 y) { + auto r = !(static_cast<__half2_raw>(x).data == static_cast<__half2_raw>(y).data); + return __builtin_convertvector(-r, _Float16_2); + } + inline + __HOST_DEVICE__ + __half2 __hleu2(__half2 x, __half2 y) { + auto r = !(static_cast<__half2_raw>(x).data > static_cast<__half2_raw>(y).data); + return __builtin_convertvector(-r, _Float16_2); + } + inline + __HOST_DEVICE__ + __half2 __hgeu2(__half2 x, __half2 y) { + auto r = !(static_cast<__half2_raw>(x).data < static_cast<__half2_raw>(y).data); + return __builtin_convertvector(-r, _Float16_2); + } + inline + __HOST_DEVICE__ + __half2 __hltu2(__half2 x, __half2 y) { + auto r = !(static_cast<__half2_raw>(x).data >= static_cast<__half2_raw>(y).data); + return __builtin_convertvector(-r, _Float16_2); + } + inline + __HOST_DEVICE__ + __half2 __hgtu2(__half2 x, __half2 y) { + auto r = !(static_cast<__half2_raw>(x).data <= static_cast<__half2_raw>(y).data); + return __builtin_convertvector(-r, _Float16_2); + } + + inline + __HOST_DEVICE__ + bool __hbeq2(__half2 x, __half2 y) + { + auto r = static_cast<__half2_raw>(__heq2(x, y)); + return r.data.x != 0 && r.data.y != 0; + } + inline + __HOST_DEVICE__ + bool __hbne2(__half2 x, __half2 y) + { + auto r = static_cast<__half2_raw>(__hne2(x, y)); + return r.data.x != 0 && r.data.y != 0; + } + inline + __HOST_DEVICE__ + bool __hble2(__half2 x, __half2 y) + { + auto r = static_cast<__half2_raw>(__hle2(x, y)); + return r.data.x != 0 && r.data.y != 0; + } + inline + __HOST_DEVICE__ + bool __hbge2(__half2 x, __half2 y) + { + auto r = static_cast<__half2_raw>(__hge2(x, y)); + return r.data.x != 0 && r.data.y != 0; + } + inline + __HOST_DEVICE__ + bool __hblt2(__half2 x, __half2 y) + { + auto r = static_cast<__half2_raw>(__hlt2(x, y)); + return r.data.x != 0 && r.data.y != 0; + } + inline + __HOST_DEVICE__ + bool __hbgt2(__half2 x, __half2 y) + { + auto r = static_cast<__half2_raw>(__hgt2(x, y)); + return r.data.x != 0 && r.data.y != 0; + } + inline + __HOST_DEVICE__ + bool __hbequ2(__half2 x, __half2 y) { return __hbeq2(x, y); } + inline + __HOST_DEVICE__ + bool __hbneu2(__half2 x, __half2 y) { return __hbne2(x, y); } + inline + __HOST_DEVICE__ + bool __hbleu2(__half2 x, __half2 y) { return __hble2(x, y); } + inline + __HOST_DEVICE__ + bool __hbgeu2(__half2 x, __half2 y) { return __hbge2(x, y); } + inline + __HOST_DEVICE__ + bool __hbltu2(__half2 x, __half2 y) { return __hblt2(x, y); } + inline + __HOST_DEVICE__ + bool __hbgtu2(__half2 x, __half2 y) { return __hbgt2(x, y); } + inline + __device__ + __half __hmax(const __half x, const __half y) { + return __half_raw{__ocml_fmax_f16(static_cast<__half_raw>(x).data, + static_cast<__half_raw>(y).data)}; + } + inline + __device__ + __half __hmax_nan(const __half x, const __half y) { + if(__ocml_isnan_f16(static_cast<__half_raw>(x).data)) { + return x; + } else if (__ocml_isnan_f16(static_cast<__half_raw>(y).data)) { + return y; + } + return __hmax(x, y); + } + inline + __device__ + __half __hmin(const __half x, const __half y) { + return __half_raw{__ocml_fmin_f16(static_cast<__half_raw>(x).data, + static_cast<__half_raw>(y).data)}; + } + inline + __device__ + __half __hmin_nan(const __half x, const __half y) { + if(__ocml_isnan_f16(static_cast<__half_raw>(x).data)) { + return x; + } else if (__ocml_isnan_f16(static_cast<__half_raw>(y).data)) { + return y; + } + return __hmin(x, y); + } + + // Arithmetic + inline + __device__ + __half __clamp_01(__half x) + { + auto r = static_cast<__half_raw>(x); + + if (__hlt(x, __half_raw{0})) return __half_raw{0}; + if (__hlt(__half_raw{1}, x)) return __half_raw{1}; + return r; + } + + inline + __device__ + __half __hadd(__half x, __half y) + { + return __half_raw{ + static_cast<__half_raw>(x).data + + static_cast<__half_raw>(y).data}; + } + inline + __device__ + __half __habs(__half x) + { + return __half_raw{ + __ocml_fabs_f16(static_cast<__half_raw>(x).data)}; + } + inline + __device__ + __half __hsub(__half x, __half y) + { + return __half_raw{ + static_cast<__half_raw>(x).data - + static_cast<__half_raw>(y).data}; + } + inline + __device__ + __half __hmul(__half x, __half y) + { + return __half_raw{ + static_cast<__half_raw>(x).data * + static_cast<__half_raw>(y).data}; + } + inline + __device__ + __half __hadd_sat(__half x, __half y) + { + return __clamp_01(__hadd(x, y)); + } + inline + __device__ + __half __hsub_sat(__half x, __half y) + { + return __clamp_01(__hsub(x, y)); + } + inline + __device__ + __half __hmul_sat(__half x, __half y) + { + return __clamp_01(__hmul(x, y)); + } + inline + __device__ + __half __hfma(__half x, __half y, __half z) + { + return __half_raw{__ocml_fma_f16( + static_cast<__half_raw>(x).data, + static_cast<__half_raw>(y).data, + static_cast<__half_raw>(z).data)}; + } + inline + __device__ + __half __hfma_sat(__half x, __half y, __half z) + { + return __clamp_01(__hfma(x, y, z)); + } + inline + __device__ + __half __hdiv(__half x, __half y) + { + return __half_raw{ + static_cast<__half_raw>(x).data / + static_cast<__half_raw>(y).data}; + } + + inline + __HOST_DEVICE__ + __half2 __hadd2(__half2 x, __half2 y) + { + return __half2{ + static_cast<__half2_raw>(x).data + + static_cast<__half2_raw>(y).data}; + } + inline + __HOST_DEVICE__ + __half2 __habs2(__half2 x) + { + return __half2{ + __ocml_fabs_2f16(static_cast<__half2_raw>(x).data)}; + } + inline + __HOST_DEVICE__ + __half2 __hsub2(__half2 x, __half2 y) + { + return __half2{ + static_cast<__half2_raw>(x).data - + static_cast<__half2_raw>(y).data}; + } + inline + __HOST_DEVICE__ + __half2 __hmul2(__half2 x, __half2 y) + { + return __half2{ + static_cast<__half2_raw>(x).data * + static_cast<__half2_raw>(y).data}; + } + inline + __HOST_DEVICE__ + __half2 __hadd2_sat(__half2 x, __half2 y) + { + auto r = static_cast<__half2_raw>(__hadd2(x, y)); + return __half2{ + __clamp_01(__half_raw{r.data.x}), + __clamp_01(__half_raw{r.data.y})}; + } + inline + __HOST_DEVICE__ + __half2 __hsub2_sat(__half2 x, __half2 y) + { + auto r = static_cast<__half2_raw>(__hsub2(x, y)); + return __half2{ + __clamp_01(__half_raw{r.data.x}), + __clamp_01(__half_raw{r.data.y})}; + } + inline + __HOST_DEVICE__ + __half2 __hmul2_sat(__half2 x, __half2 y) + { + auto r = static_cast<__half2_raw>(__hmul2(x, y)); + return __half2{ + __clamp_01(__half_raw{r.data.x}), + __clamp_01(__half_raw{r.data.y})}; + } + inline + __HOST_DEVICE__ + __half2 __hfma2(__half2 x, __half2 y, __half2 z) + { + return __half2{__ocml_fma_2f16(x, y, z)}; + } + inline + __HOST_DEVICE__ + __half2 __hfma2_sat(__half2 x, __half2 y, __half2 z) + { + auto r = static_cast<__half2_raw>(__hfma2(x, y, z)); + return __half2{ + __clamp_01(__half_raw{r.data.x}), + __clamp_01(__half_raw{r.data.y})}; + } + inline + __HOST_DEVICE__ + __half2 __h2div(__half2 x, __half2 y) + { + return __half2{ + static_cast<__half2_raw>(x).data / + static_cast<__half2_raw>(y).data}; + } + + // Math functions + #if defined(__clang__) && defined(__HIP__) + inline + __device__ + float amd_mixed_dot(__half2 a, __half2 b, float c, bool saturate) { + return __ockl_fdot2(static_cast<__half2_raw>(a).data, + static_cast<__half2_raw>(b).data, + c, saturate); + } + #endif + inline + __device__ + __half htrunc(__half x) + { + return __half_raw{ + __ocml_trunc_f16(static_cast<__half_raw>(x).data)}; + } + inline + __device__ + __half hceil(__half x) + { + return __half_raw{ + __ocml_ceil_f16(static_cast<__half_raw>(x).data)}; + } + inline + __device__ + __half hfloor(__half x) + { + return __half_raw{ + __ocml_floor_f16(static_cast<__half_raw>(x).data)}; + } + inline + __device__ + __half hrint(__half x) + { + return __half_raw{ + __ocml_rint_f16(static_cast<__half_raw>(x).data)}; + } + inline + __device__ + __half hsin(__half x) + { + return __half_raw{ + __ocml_sin_f16(static_cast<__half_raw>(x).data)}; + } + inline + __device__ + __half hcos(__half x) + { + return __half_raw{ + __ocml_cos_f16(static_cast<__half_raw>(x).data)}; + } + inline + __device__ + __half hexp(__half x) + { + return __half_raw{ + __ocml_exp_f16(static_cast<__half_raw>(x).data)}; + } + inline + __device__ + __half hexp2(__half x) + { + return __half_raw{ + __ocml_exp2_f16(static_cast<__half_raw>(x).data)}; + } + inline + __device__ + __half hexp10(__half x) + { + return __half_raw{ + __ocml_exp10_f16(static_cast<__half_raw>(x).data)}; + } + inline + __device__ + __half hlog2(__half x) + { + return __half_raw{ + __ocml_log2_f16(static_cast<__half_raw>(x).data)}; + } + inline + __device__ + __half hlog(__half x) + { + return __half_raw{ + __ocml_log_f16(static_cast<__half_raw>(x).data)}; + } + inline + __device__ + __half hlog10(__half x) + { + return __half_raw{ + __ocml_log10_f16(static_cast<__half_raw>(x).data)}; + } + inline + __device__ + __half hrcp(__half x) + { + return __half_raw{ + static_cast<_Float16>(1.0f) /static_cast<__half_raw>(x).data}; + } + inline + __device__ + __half hrsqrt(__half x) + { + return __half_raw{ + __ocml_rsqrt_f16(static_cast<__half_raw>(x).data)}; + } + inline + __device__ + __half hsqrt(__half x) + { + return __half_raw{ + __ocml_sqrt_f16(static_cast<__half_raw>(x).data)}; + } + inline + __device__ + bool __hisinf(__half x) + { + return __ocml_isinf_f16(static_cast<__half_raw>(x).data); + } + inline + __device__ + bool __hisnan(__half x) + { + return __ocml_isnan_f16(static_cast<__half_raw>(x).data); + } + inline + __device__ + __half __hneg(__half x) + { + return __half_raw{-static_cast<__half_raw>(x).data}; + } + + inline + __HOST_DEVICE__ + __half2 h2trunc(__half2 x) + { + return __half2{__ocml_trunc_2f16(x)}; + } + inline + __HOST_DEVICE__ + __half2 h2ceil(__half2 x) + { + return __half2{__ocml_ceil_2f16(x)}; + } + inline + __HOST_DEVICE__ + __half2 h2floor(__half2 x) + { + return __half2{__ocml_floor_2f16(x)}; + } + inline + __HOST_DEVICE__ + __half2 h2rint(__half2 x) + { + return __half2{__ocml_rint_2f16(x)}; + } + inline + __HOST_DEVICE__ + __half2 h2sin(__half2 x) + { + return __half2{__ocml_sin_2f16(x)}; + } + inline + __HOST_DEVICE__ + __half2 h2cos(__half2 x) + { + return __half2{__ocml_cos_2f16(x)}; + } + inline + __HOST_DEVICE__ + __half2 h2exp(__half2 x) + { + return __half2{__ocml_exp_2f16(x)}; + } + inline + __HOST_DEVICE__ + __half2 h2exp2(__half2 x) + { + return __half2{__ocml_exp2_2f16(x)}; + } + inline + __HOST_DEVICE__ + __half2 h2exp10(__half2 x) + { + return __half2{__ocml_exp10_2f16(x)}; + } + inline + __HOST_DEVICE__ + __half2 h2log2(__half2 x) + { + return __half2{__ocml_log2_2f16(x)}; + } + inline + __HOST_DEVICE__ + __half2 h2log(__half2 x) { return __ocml_log_2f16(x); } + inline + __HOST_DEVICE__ + __half2 h2log10(__half2 x) { return __ocml_log10_2f16(x); } + inline + __HOST_DEVICE__ + __half2 h2rcp(__half2 x) { + return _Float16_2{ + _Float16_2{static_cast<_Float16>(1.0f), static_cast<_Float16>(1.0f)} / x.data}; + } + inline + __HOST_DEVICE__ + __half2 h2rsqrt(__half2 x) { return __ocml_rsqrt_2f16(x); } + inline + __HOST_DEVICE__ + __half2 h2sqrt(__half2 x) { return __ocml_sqrt_2f16(x); } + inline + __HOST_DEVICE__ + __half2 __hisinf2(__half2 x) + { + auto r = __ocml_isinf_2f16(x); + return __half2{_Float16_2{ + static_cast<_Float16>(r.x), static_cast<_Float16>(r.y)}}; + } + inline + __HOST_DEVICE__ + __half2 __hisnan2(__half2 x) + { + auto r = __ocml_isnan_2f16(x); + return __half2{_Float16_2{ + static_cast<_Float16>(r.x), static_cast<_Float16>(r.y)}}; + } + inline + __HOST_DEVICE__ + __half2 __hneg2(__half2 x) + { + return __half2{-static_cast<__half2_raw>(x).data}; + } + } // Anonymous namespace. + + #if !defined(HIP_NO_HALF) + using half = __half; + using half2 = __half2; + #endif + __device__ + inline + __half __shfl(__half var, int src_lane, int width = warpSize) { + union { int i; __half h; } tmp; tmp.h = var; + tmp.i = __shfl(tmp.i, src_lane, width); + return tmp.h; + } + __device__ + inline + __half2 __shfl(__half2 var, int src_lane, int width = warpSize) { + union { int i; __half2 h; } tmp; tmp.h = var; + tmp.i = __shfl(tmp.i, src_lane, width); + return tmp.h; + } + __device__ + inline + __half __shfl_up(__half var, unsigned int lane_delta, int width = warpSize) { + union { int i; __half h; } tmp; tmp.h = var; + tmp.i = __shfl_up(tmp.i, lane_delta, width); + return tmp.h; + } + __device__ + inline + __half2 __shfl_up(__half2 var, unsigned int lane_delta, int width = warpSize) { + union { int i; __half2 h; } tmp; tmp.h = var; + tmp.i = __shfl_up(tmp.i, lane_delta, width); + return tmp.h; + } + __device__ + inline + __half __shfl_down(__half var, unsigned int lane_delta, int width = warpSize) { + union { int i; __half h; } tmp; tmp.h = var; + tmp.i = __shfl_down(tmp.i, lane_delta, width); + return tmp.h; + } + __device__ + inline + __half2 __shfl_down(__half2 var, unsigned int lane_delta, int width = warpSize) { + union { int i; __half2 h; } tmp; tmp.h = var; + tmp.i = __shfl_down(tmp.i, lane_delta, width); + return tmp.h; + } + __device__ + inline + __half __shfl_xor(__half var, int lane_mask, int width = warpSize) { + union { int i; __half h; } tmp; tmp.h = var; + tmp.i = __shfl_xor(tmp.i, lane_mask, width); + return tmp.h; + } + __device__ + inline + __half2 __shfl_xor(__half2 var, int lane_mask, int width = warpSize) { + union { int i; __half2 h; } tmp; tmp.h = var; + tmp.i = __shfl_xor(tmp.i, lane_mask, width); + return tmp.h; + } + #endif // defined(__cplusplus) +#elif defined(__GNUC__) + #if !defined(__HIPCC_RTC__) + #include "hip_fp16_gcc.h" + #endif +#endif // !defined(__clang__) && defined(__GNUC__) + +#endif // HIP_INCLUDE_HIP_AMD_DETAIL_HIP_FP16_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_fp8.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_fp8.h new file mode 100644 index 0000000000000000000000000000000000000000..e54c70241701838952a6d362f786edbce06f33b9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_fp8.h @@ -0,0 +1,1391 @@ +/** + * 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 amd_hip_fp8.h header, for AMD fp8 data types + */ + +#ifndef _HIP_INCLUDE_HIP_AMD_DETAIL_HIP_FP8_H_ +#define _HIP_INCLUDE_HIP_AMD_DETAIL_HIP_FP8_H_ + +#if (defined(__gfx940__) || defined(__gfx941__) || defined(__gfx942__)) && __HIP_DEVICE_COMPILE__ +#define HIP_FP8_CVT_FAST_PATH 1 +#else +#define HIP_FP8_CVT_FAST_PATH 0 +#endif + +#if !defined(__HIPCC_RTC__) +#include +#include + +#include "host_defines.h" // __hip_internal:: +#include "amd_hip_vector_types.h" // float2 etc +#include "amd_hip_fp16.h" // __half_raw +#include "amd_hip_bf16.h" // bf16 +#include "math_fwd.h" // ocml device functions +#endif // !defined(__HIPCC_RTC__) + +#if defined(__HIPCC_RTC__) +#define __FP8_HOST_DEVICE__ __device__ +#define __FP8_HOST_DEVICE_STATIC__ __FP8_HOST_DEVICE__ static +#else +#define __FP8_HOST_DEVICE__ __host__ __device__ +#define __FP8_HOST_DEVICE_STATIC__ __FP8_HOST_DEVICE__ static inline +#endif // __HIPCC_RTC__ + +#if !defined(__HIPCC_RTC__) +static_assert(CHAR_BIT == 8, "byte size should be of 8 bits"); +#endif +static_assert(sizeof(unsigned char) == 1); +static_assert(sizeof(unsigned short int) == 2); +static_assert(sizeof(unsigned int) == 4); + +/** + * \brief Describes FP8 interpretation + */ +enum __hip_fp8_interpretation_t { + __HIP_E4M3_FNUZ = 0, /**< Standard FP8 */ + __HIP_E5M2_FNUZ = 1, /**< BF8 */ +}; + +/** + * \brief Describes saturation behavior + */ +enum __hip_saturation_t { + __HIP_NOSAT = 0, /**< No saturation */ + __HIP_SATFINITE = 1, /**< Saturate to finite */ +}; + +/** \typedef __hip_fp8_storage_t + * + * \brief type to store single fp8 number + */ +typedef unsigned char __hip_fp8_storage_t; + + +/** \typedef __hip_fp8x2_storage_t + * + * \brief type to store two fp8 numbers + */ +typedef unsigned short int __hip_fp8x2_storage_t; + + +/** \typedef __hip_fp8x4_storage_t + * + * \brief type to store four fp8 numbers + */ +typedef unsigned int __hip_fp8x4_storage_t; + +namespace internal { +// The conversion function is from rocblas +// https://github.com/ROCm/rocBLAS/blob/9b7f692abe3c54b88d1e77e045a7db7f1f188b69/library/include/internal/rocblas_hip_f8_impl.h#L39 +// This has been modified to add double types conversion as well +template +__FP8_HOST_DEVICE_STATIC__ __hip_fp8_storage_t cast_to_f8(T _x, int wm, int we, bool clip = false, + bool stoch = false, + unsigned int rng = 0) { + constexpr bool is_half = __hip_internal::is_same::value; + constexpr bool is_float = __hip_internal::is_same::value; + constexpr bool is_double = __hip_internal::is_same::value; + static_assert(is_half || is_float || is_double, "Only half, float and double can be cast to f8"); + + const int mfmt = (sizeof(T) == 8) ? 52 : ((sizeof(T) == 4) ? 23 : 10); + unsigned long long x; + + if (sizeof(T) == 8) + x = reinterpret_cast(_x); + else if (sizeof(T) == 4) + x = reinterpret_cast(_x); + else + x = reinterpret_cast(_x); + + + unsigned long long head, mantissa; + int exponent, bias; + unsigned int sign; + + if (sizeof(T) == 8) { + head = x & 0xFFF0000000000000ull; + mantissa = x & 0xFFFFFFFFFFFFFull; + exponent = (head >> 52) & 0x7FF; + sign = head >> 63; + bias = 1023; + } else if (sizeof(T) == 4) { + head = x & 0xFF800000; + mantissa = x & 0x7FFFFF; + exponent = (head >> 23) & 0xFF; + sign = head >> 31; + bias = 127; + } else { + head = x & 0xFC00; + mantissa = x & 0x3FF; + exponent = (head >> 10) & 0x1F; + sign = head >> 15; + bias = 15; + } + + unsigned int signed_inf = (sign << 7) + (((1 << we) - 1) << wm); + + // Deal with inf and NaNs + if (negative_zero_nan) { + if (sizeof(T) == 8) { + if ((x & 0x7FF0000000000000ull) == 0x7FF0000000000000ull) return 0x80; + } else if (sizeof(T) == 4) { + if ((x & 0x7F800000) == 0x7F800000) return 0x80; + } else { + if ((x & 0x7C00) == 0x7C00) return 0x80; + } + } else { + if (sizeof(T) == 8) { + if ((x & 0x7FF0000000000000ull) == 0x7FF0000000000000ull) + return signed_inf + (mantissa != 0 ? 1 : 0); + } else if (sizeof(T) == 4) { + if ((x & 0x7F800000) == 0x7F800000) return signed_inf + (mantissa != 0 ? 1 : 0); + } else { + if ((x & 0x7C00) == 0x7C00) return signed_inf + (mantissa != 0 ? 1 : 0); + } + } + + if (x == 0) { + return 0; + } + + // First need to check if it is normal or denorm as there is a difference of implict 1 + // Then need to adjust the exponent to align with the F8 exponent, in the meanwhile, shift + // The mantissa. Then for stochastic rounding, add rng to mantissa and truncate. And for + // RNE, no need to add rng. Then probably need to check whether there is carry and adjust + // exponent and mantissa again + + // For IEEE bias mode, the bias is 2^(k-1) -1 where k is the width of exponent bits + const int f8_bias = (1 << (we - 1)) - 1 + (negative_zero_nan ? 1 : 0); + const int f8_denormal_act_exponent = 1 - f8_bias; // actual exponent of f8 denormal + // act_exponent is the actual exponent of fp32/fp16 (after subtracting bias) + // f8_exponent is the converted f8 exponent with bias encoding + // exponent_diff is the diff between fp32/fp16 exponent and f8 exponent, + // the difference needs to be adjusted and mantissa shifted + int act_exponent, f8_exponent, exponent_diff; + + if (exponent == 0) { // fp32/fp16 is in denormal. + /* fp32 denormal is below 2^-127 so it is usually not a concern here, we mostly concern fp16 +here. In this case, f8 is usually in denormal. But there could be exceptions. fp16 denormal has +exponent bias 15 while bf8 with NANOO has exponent bias 16. It means that there are some numbers in +fp16 denormal but they are bf8 (NANOO) normals - smallest bf8 (NANOO) normal is 2^-15. fp16 numbers +where exponent==0 (actual exponent -14) and highest bit of mantissa is 1 are bf8 (NANOO) normal. In +this case, the fp16 mantissa should be shift left by 1 */ + act_exponent = exponent - bias + 1; + exponent_diff = f8_denormal_act_exponent - + act_exponent; // actual exponent is exponent-bias+1 as it is denormal + } else { // fp32/fp16 is normal with implicit 1 + act_exponent = exponent - bias; + if (act_exponent <= f8_denormal_act_exponent) { + /* This is the case where fp32/fp16 is normal but it is in f8 denormal range. +For example fp8 nanoo mode, denormal exponent is -7, but if the fp32/fp16 +actual exponent is -7, it is actually larger due to the implict 1, +Therefore it needs to be adjust to -6 and mantissa shift right by 1. +So for fp32/fp16, exponent -8 is the cut point to convert to fp8 nanoo */ + exponent_diff = f8_denormal_act_exponent - act_exponent; + } else { // both fp32/fp16 and f8 are in normal range + exponent_diff = 0; // exponent_diff=0 does not mean there is no difference for this case, + // act_exponent could be larger. Just that it does not need shift mantissa + } + mantissa += (1ull << mfmt); // Add the implicit 1 into mantissa + } + + bool midpoint = (mantissa & ((1ull << (mfmt - wm + exponent_diff)) - 1)) == + (1ull << (mfmt - wm + exponent_diff - 1)); + /* This part is a bit tricky. The judgment of whether it is a tie needs to be done before we shift +right as shift right could rip off some residual part and make something not midpoint look like +midpoint. For example, the fp16 number 0x1002 (0 00100 0000000010), it is larger than midpoint, but +after shift right by 4 bits, it would look like midpoint. +*/ + + if (exponent_diff > 0) + mantissa >>= exponent_diff; + else if (exponent_diff == -1) + mantissa <<= -exponent_diff; + bool implicit_one = mantissa & (1ull << mfmt); + // if there is no implict 1, it means the f8 is denormal and need to adjust to denorm exponent + f8_exponent = + (act_exponent + exponent_diff) /*actual f8 exponent*/ + f8_bias - (implicit_one ? 0 : 1); + + // Now we have the exponent and mantissa adjusted + unsigned long long drop_mask = (1ull << (mfmt - wm)) - 1; + bool odd = + mantissa & (1ull << (mfmt - wm)); // if the least significant bit that is not truncated is 1 + mantissa += + (stoch ? rng : (midpoint ? (odd ? mantissa : mantissa - 1ull) : mantissa)) & drop_mask; + + // Now we deal with overflow + if (f8_exponent == 0) { + if ((1ull << mfmt) & mantissa) { + f8_exponent = 1; // denormal overflow to become normal, promote exponent + } + } else { + if ((1ull << (mfmt + 1)) & mantissa) { + mantissa >>= 1; + f8_exponent++; + } + } + + mantissa >>= (mfmt - wm); + + // above range: quantize to maximum possible float of the same sign + const int max_exp = (1 << we) - (negative_zero_nan ? 1 : 2); + if (f8_exponent > max_exp) { + if (clip) { + mantissa = (1 << wm) - 1; + f8_exponent = max_exp; + } else { + return signed_inf; + } + } + + if (f8_exponent == 0 && mantissa == 0) return negative_zero_nan ? 0 : (sign << 7); + mantissa &= (1 << wm) - 1; + return (sign << 7) | (f8_exponent << wm) | mantissa; +} + +// The conversion function is from rocblas +// https://github.com/ROCm/rocBLAS/blob/9b7f692abe3c54b88d1e77e045a7db7f1f188b69/library/include/internal/rocblas_hip_f8_impl.h#L220 +// This has been modified to handle double types as well +template +__FP8_HOST_DEVICE_STATIC__ T cast_from_f8(__hip_fp8_storage_t x, int wm, int we) { + constexpr bool is_half = __hip_internal::is_same::value; + constexpr bool is_float = __hip_internal::is_same::value; + constexpr bool is_double = __hip_internal::is_same::value; + static_assert(is_half || is_float || is_double, "only half, float and double are supported"); + + constexpr int weo = is_half ? 5 : (is_float ? 8 : 11); + constexpr int wmo = is_half ? 10 : (is_float ? 23 : 52); + + T fInf, fNegInf, fNaN, fNeg0; + if (is_half) { + const unsigned short int ihInf = 0x7C00; + const unsigned short int ihNegInf = 0xFC00; + const unsigned short int ihNaN = 0x7C01; + const unsigned short int ihNeg0 = 0x8000; + fInf = reinterpret_cast(ihInf); + fNegInf = reinterpret_cast(ihNegInf); + fNaN = reinterpret_cast(ihNaN); + fNeg0 = reinterpret_cast(ihNeg0); + } else if (is_float) { + const unsigned int ifInf = 0x7F800000; + const unsigned int ifNegInf = 0xFF800000; + const unsigned int ifNaN = 0x7F800001; + const unsigned int ifNeg0 = 0x80000000; + fInf = reinterpret_cast(ifInf); + fNegInf = reinterpret_cast(ifNegInf); + fNaN = reinterpret_cast(ifNaN); + fNeg0 = reinterpret_cast(ifNeg0); + } else if (is_double) { + const unsigned long long ifInf = 0x7FF0000000000000ull; + const unsigned long long ifNegInf = 0xFFF0000000000000ull; + const unsigned long long ifNaN = 0x7FF0000000000001ull; + const unsigned long long ifNeg0 = 0x8000000000000000ull; + fInf = reinterpret_cast(ifInf); + fNegInf = reinterpret_cast(ifNegInf); + fNaN = reinterpret_cast(ifNaN); + fNeg0 = reinterpret_cast(ifNeg0); + } + + if (x == 0) { + return 0; + } + + unsigned long long sign = x >> 7; + unsigned long long mantissa = x & ((1 << wm) - 1); + int exponent = (x & 0x7F) >> wm; + if (negative_zero_nan) { + if (x == 0x80) return fNaN; + } else { + if (x == 0x80) return fNeg0; + if (exponent == ((1 << we) - 1)) return (mantissa == 0) ? (sign ? fNegInf : fInf) : fNaN; + } + + typename __hip_internal::conditional< + sizeof(T) == 2, unsigned short int, + typename __hip_internal::conditional::type>::type retval; + + if (we == 5 && is_half && !negative_zero_nan) { + retval = x << 8; + return reinterpret_cast(retval); + } + + const int exp_low_cutoff = (1 << (weo - 1)) - (1 << (we - 1)) + 1 - (negative_zero_nan ? 1 : 0); + + // subnormal input + if (exponent == 0) { +#if __HIP_DEVICE_COMPILE__ + // guaranteed mantissa!=0 since cases 0x0 and 0x80 are handled above + int sh = 1 + __clz(mantissa) - (32 - wm); +#else + int sh = 1 + __builtin_clz(mantissa) - (32 - wm); +#endif + mantissa <<= sh; + exponent += 1 - sh; + mantissa &= ((1ull << wm) - 1); + } + exponent += exp_low_cutoff - 1; + mantissa <<= wmo - wm; + + // subnormal output (occurs when T=half, we=5, negative_zero_nan=true) + if (exponent <= 0) { + mantissa |= 1 << wmo; + mantissa >>= 1 - exponent; + exponent = 0; + } + + if (sizeof(T) == 2) + retval = (sign << 15) | (exponent << 10) | mantissa; + else if (sizeof(T) == 4) + retval = (sign << 31) | (exponent << 23) | mantissa; + else + retval = (sign << 63) | (static_cast(exponent) << 52) | mantissa; + return reinterpret_cast(retval); +} + +#if HIP_FP8_CVT_FAST_PATH +// The conversion function is from rocblas +// https://github.com/ROCm/rocBLAS/blob/9b7f692abe3c54b88d1e77e045a7db7f1f188b69/library/include/internal/rocblas_float8.h#L79 +template +static __device__ __hip_fp8_storage_t cast_to_f8_from_f32(float v, bool saturate, + __hip_fp8_interpretation_t interpret, + unsigned int rng = 0) { + __hip_fp8_storage_t i8data; + union { + float fval; + unsigned int i32val; + unsigned char i8val[4]; // NOTE: not endian independent + } val; + + unsigned int ival = 0; + val.fval = v; + + if (saturate) { + if (interpret == __HIP_E4M3_FNUZ) { + if ((val.i32val & 0x7F800000) != 0x7F800000) { /// propagate NAN/INF, no clipping + val.fval = __builtin_amdgcn_fmed3f(val.fval, 240.0, -240.0); + } + } else { + if ((val.i32val & 0x7F800000) != 0x7F800000) { /// propagate NAN/INF, no clipping + val.fval = __builtin_amdgcn_fmed3f(val.fval, 57344.0, -57344.0); + } + } + } + + if (stochastic_rounding) { + ival = interpret == __HIP_E4M3_FNUZ + ? __builtin_amdgcn_cvt_sr_fp8_f32(val.fval, rng, ival, 0) + : __builtin_amdgcn_cvt_sr_bf8_f32(val.fval, rng, ival, 0); // 0 pos + val.i32val = ival; + i8data = val.i8val[0]; // little endian + } else { // RNE CVT + ival = interpret == __HIP_E4M3_FNUZ + ? __builtin_amdgcn_cvt_pk_fp8_f32(val.fval, val.fval, ival, false) + : __builtin_amdgcn_cvt_pk_bf8_f32(val.fval, val.fval, ival, false); // false -> WORD0 + val.i32val = ival; + i8data = val.i8val[0]; + } + return i8data; +} + +static __device__ __hip_fp8x2_storage_t +cast_to_f8x2_from_f32x2(float2 v, bool saturate, __hip_fp8_interpretation_t interpret) { + union { + static_assert(sizeof(float2) == sizeof(unsigned int[2])); + static_assert(sizeof(float2) == sizeof(unsigned short[4])); + float2 fval; + unsigned int i32val[2]; + unsigned short i16val[4]; + } f2val; + + f2val.fval = v; + + if (saturate) { /// propagate NAN/INF, no clipping + if ((f2val.i32val[0] & 0x7F800000) != 0x7F800000) { + f2val.fval.x = __builtin_amdgcn_fmed3f(f2val.fval.x, 240.0, -240.0); + } + if ((f2val.i32val[1] & 0x7F800000) != 0x7F800000) { + f2val.fval.y = __builtin_amdgcn_fmed3f(f2val.fval.x, 240.0, -240.0); + } + } + + f2val.i32val[0] = interpret == __HIP_E4M3_FNUZ + ? __builtin_amdgcn_cvt_pk_fp8_f32(v.x, v.y, 0, false) + : __builtin_amdgcn_cvt_pk_bf8_f32(v.x, v.y, 0, false); + + return static_cast<__hip_fp8x2_storage_t>(f2val.i16val[0]); +} + +static __device__ float cast_to_f32_from_f8(__hip_fp8_storage_t v, + __hip_fp8_interpretation_t interpret) { + union { + unsigned int i32val; + unsigned char i8val[4]; + } val; + val.i8val[0] = v; + + float fval = interpret == __HIP_E4M3_FNUZ ? __builtin_amdgcn_cvt_f32_fp8(val.i32val, 0) + : __builtin_amdgcn_cvt_f32_bf8(val.i32val, 0); + return fval; +} + +static __device__ float2 cast_to_f32x2_from_f8x2(__hip_fp8x2_storage_t v, + __hip_fp8_interpretation_t interpret) { + union { + unsigned int i32val; + unsigned short i16val[2]; + } val; + val.i16val[0] = v; + + auto f2 = interpret == __HIP_E4M3_FNUZ ? __builtin_amdgcn_cvt_pk_f32_fp8(val.i32val, false) + : __builtin_amdgcn_cvt_pk_f32_bf8(val.i32val, false); + return float2{f2[0], f2[1]}; +} +#endif // HIP_FP8_CVT_FAST_PATH + +/* For fp8 fnuz types, finite and NaN values are supported. Zero is unsigned. +Inf are not supported. This gives us one additional number to represent. +NaN are represented by 1-0000-000 or 1-00000-00 */ +__FP8_HOST_DEVICE_STATIC__ bool hip_fp8_fnuz_is_nan(__hip_fp8_storage_t a) { + return static_cast(a) == 0x80; +} +} // namespace internal + +/** + * \brief convert float to @p __hip_fp8_storage_t + * + * \param f float number + * \param sat saturation of fp8 + * \param type interpretation of fp8 + * \return __hip_fp8_storage_t + */ +__FP8_HOST_DEVICE_STATIC__ __hip_fp8_storage_t __hip_cvt_float_to_fp8( + const float f, const __hip_saturation_t sat, const __hip_fp8_interpretation_t type) { +#if HIP_FP8_CVT_FAST_PATH + return internal::cast_to_f8_from_f32(f, sat == __HIP_SATFINITE, type); +#else // HIP_FP8_CVT_FAST_PATH + int we = type == __HIP_E4M3_FNUZ ? 4 : 5; + int wm = type == __HIP_E4M3_FNUZ ? 3 : 2; + return internal::cast_to_f8(f, wm, we, sat == __HIP_SATFINITE); +#endif // HIP_FP8_CVT_FAST_PATH +} + +/** + * \brief convert float2 to @p __hip_fp8x2_storage_t + * + * \param f2 float2 number + * \param sat saturation of fp8 + * \param type interpretation of fp8 + * \return __hip_fp8x2_storage_t + */ +__FP8_HOST_DEVICE_STATIC__ __hip_fp8x2_storage_t __hip_cvt_float2_to_fp8x2( + const float2 f2, const __hip_saturation_t sat, const __hip_fp8_interpretation_t type) { +#if HIP_FP8_CVT_FAST_PATH + return internal::cast_to_f8x2_from_f32x2(f2, sat == __HIP_SATFINITE, type); +#else + return static_cast<__hip_fp8x2_storage_t>( + static_cast(__hip_cvt_float_to_fp8(f2.y, sat, type)) << 8 | + static_cast(__hip_cvt_float_to_fp8(f2.x, sat, type))); +#endif +} + +/** + * \brief convert double to @p __hip_fp8_storage_t + * + * \param d double val + * \param sat saturation of fp8 + * \param type interpretation of fp8 + * \return __hip_fp8_storage_t + */ +__FP8_HOST_DEVICE_STATIC__ __hip_fp8_storage_t __hip_cvt_double_to_fp8( + const double d, const __hip_saturation_t sat, const __hip_fp8_interpretation_t type) { + int we = type == __HIP_E4M3_FNUZ ? 4 : 5; + int wm = type == __HIP_E4M3_FNUZ ? 3 : 2; + return internal::cast_to_f8(d, wm, we, sat == __HIP_SATFINITE); +} + +/** + * \brief convert double2 to @p __hip_fp8x2_storage_t + * + * \param d2 double2 val + * \param sat saturation of fp8 + * \param type interpretation of fp8 + * \return __hip_fp8x2_storage_t + */ +__FP8_HOST_DEVICE_STATIC__ __hip_fp8x2_storage_t __hip_cvt_double2_to_fp8x2( + const double2 d2, const __hip_saturation_t sat, const __hip_fp8_interpretation_t type) { + return static_cast<__hip_fp8x2_storage_t>( + static_cast(__hip_cvt_double_to_fp8(d2.y, sat, type)) << 8 | + static_cast(__hip_cvt_double_to_fp8(d2.x, sat, type))); +} + +/** + * \brief convert __hip_bfloat16_raw to @p __hip_fp8_storage_t + * + * \param hr __hip_bfloat16_raw val + * \param sat saturation of fp8 + * \param type interpretation of fp8 + * \return __hip_fp8_storage_t + */ +__FP8_HOST_DEVICE_STATIC__ __hip_fp8_storage_t +__hip_cvt_bfloat16raw_to_fp8(const __hip_bfloat16_raw hr, const __hip_saturation_t sat, + const __hip_fp8_interpretation_t type) { + float fval = __hip_bfloat16(hr); + return __hip_cvt_float_to_fp8(fval, sat, type); +} + +/** + * \brief convert double2 to @p __hip_fp8x2_storage_t + * + * \param hr __hip_bfloat162_raw value + * \param sat saturation of fp8 + * \param type interpretation of fp8 + * \return __hip_fp8x2_storage_t + */ +__FP8_HOST_DEVICE_STATIC__ __hip_fp8x2_storage_t +__hip_cvt_bfloat16raw2_to_fp8x2(const __hip_bfloat162_raw hr, const __hip_saturation_t sat, + const __hip_fp8_interpretation_t type) { + float2 f2 = __hip_bfloat162(hr); + return __hip_cvt_float2_to_fp8x2(f2, sat, type); +} + +/** + * \brief convert @p __hip_fp8_storage_t to __half_raw + * + * \param x __hip_fp8_storage_t val + * \param type interpretation of fp8 + * \return __half_raw + */ +__FP8_HOST_DEVICE_STATIC__ __half_raw +__hip_cvt_fp8_to_halfraw(const __hip_fp8_storage_t x, const __hip_fp8_interpretation_t type) { + unsigned int we = type == __HIP_E4M3_FNUZ ? 4 : 5; + unsigned int wm = type == __HIP_E4M3_FNUZ ? 3 : 2; + return __half_raw{internal::cast_from_f8<_Float16, true>(x, wm, we)}; +} + +/** + * \brief convert @p __hip_fp8x2_storage_t to __half2_raw + * + * \param x __hip_fp8x2_storage_t val + * \param type interpretation of fp8 + * \return __half2_raw + */ +__FP8_HOST_DEVICE_STATIC__ __half2_raw +__hip_cvt_fp8x2_to_halfraw2(const __hip_fp8x2_storage_t x, const __hip_fp8_interpretation_t type) { + __half2 ret(static_cast<__half>( + __hip_cvt_fp8_to_halfraw(static_cast<__hip_fp8_storage_t>(x & 0xFF), type)), + static_cast<__half>( + __hip_cvt_fp8_to_halfraw(static_cast<__hip_fp8_storage_t>(x >> 8), type))); + return static_cast<__half2_raw>(ret); +} + +/** + * \brief convert __half_raw to @p __hip_fp8_storage_t + * + * \param x __half_raw value + * \param sat saturation of fp8 + * \param type interpretation of fp8 + * \return __hip_fp8_storage_t + */ +__FP8_HOST_DEVICE_STATIC__ __hip_fp8_storage_t __hip_cvt_halfraw_to_fp8( + const __half_raw x, const __hip_saturation_t sat, const __hip_fp8_interpretation_t type) { + return __hip_cvt_float_to_fp8(__half2float(__half(x)), sat, type); +} + +/** + * \brief convert __half2_raw to @p __hip_fp8x2_storage_t + * + * \param x __half2_raw value + * \param sat saturation of fp8 + * \param type interpretation of fp8 + * \return __hip_fp8x2_storage_t + */ +__FP8_HOST_DEVICE_STATIC__ __hip_fp8x2_storage_t __hip_cvt_halfraw2_to_fp8x2( + const __half2_raw x, const __hip_saturation_t sat, const __hip_fp8_interpretation_t type) { + return __hip_cvt_float2_to_fp8x2(__half22float2(__half2(x)), sat, type); +} + +/** + * \brief struct representing single fp8 number with e4m3 interpretation + * + */ +struct __hip_fp8_e4m3_fnuz { + __hip_fp8_storage_t __x; //! raw storage of fp8 number + constexpr static __hip_saturation_t __default_saturation = __HIP_SATFINITE; + constexpr static __hip_fp8_interpretation_t __default_interpret = __HIP_E4M3_FNUZ; + constexpr static unsigned int __we = 4; + constexpr static unsigned int __wm = 3; + + // TODO: SWDEV-452411 + // Add cast from unsigned long long, long long to fp8 + + /*! create fp8 e4m3 from long */ + __FP8_HOST_DEVICE__ __hip_fp8_e4m3_fnuz(const long int val) + : __x(__hip_cvt_float_to_fp8(static_cast(val), __default_saturation, + __default_interpret)) {} + + /*! create fp8 e4m3 from int */ + __FP8_HOST_DEVICE__ __hip_fp8_e4m3_fnuz(const int val) + : __x(__hip_cvt_float_to_fp8(static_cast(val), __default_saturation, + __default_interpret)) {} + + /*! create fp8 e4m3 from short int */ + __FP8_HOST_DEVICE__ __hip_fp8_e4m3_fnuz(const short int val) + : __x(__hip_cvt_float_to_fp8(static_cast(val), __default_saturation, + __default_interpret)) {} + + /*! create fp8 e4m3 from unsigned long */ + __FP8_HOST_DEVICE__ __hip_fp8_e4m3_fnuz(const unsigned long int val) + : __x(__hip_cvt_float_to_fp8(static_cast(val), __default_saturation, + __default_interpret)) {} + + /*! create fp8 e4m3 from unsigned int */ + __FP8_HOST_DEVICE__ __hip_fp8_e4m3_fnuz(const unsigned int val) + : __x(__hip_cvt_float_to_fp8(static_cast(val), __default_saturation, + __default_interpret)) {} + + /*! create fp8 e4m3 from unsigned short */ + __FP8_HOST_DEVICE__ __hip_fp8_e4m3_fnuz(const unsigned short int val) + : __x(__hip_cvt_float_to_fp8(static_cast(val), __default_saturation, + __default_interpret)) {} + + /*! create fp8 e4m3 from double */ + __FP8_HOST_DEVICE__ __hip_fp8_e4m3_fnuz(const double f) + : __x(__hip_cvt_double_to_fp8(f, __default_saturation, __default_interpret)) {} + + /*! create fp8 e4m3 from float */ + __FP8_HOST_DEVICE__ __hip_fp8_e4m3_fnuz(const float f) + : __x(__hip_cvt_float_to_fp8(f, __default_saturation, __default_interpret)) {} + + /*! create fp8 e4m3 from __hip_bfloat16 */ + __FP8_HOST_DEVICE__ __hip_fp8_e4m3_fnuz(const __hip_bfloat16 f) + : __x(__hip_cvt_float_to_fp8(static_cast(f), __default_saturation, + __default_interpret)) {} + + /*! create fp8 e4m3 from __half */ + __FP8_HOST_DEVICE__ __hip_fp8_e4m3_fnuz(const __half f) + : __x(__hip_cvt_halfraw_to_fp8(static_cast<__half_raw>(f), __default_saturation, + __default_interpret)) {} + + /*! default construct fp8 e4m3 */ + __FP8_HOST_DEVICE__ __hip_fp8_e4m3_fnuz() = default; + + /*! convert fp8 e4m3 to __half */ + __FP8_HOST_DEVICE__ operator __half() const { + return __half(__hip_cvt_fp8_to_halfraw(__x, __default_interpret)); + } + + /*! convert fp8 e4m3 to __hip_bfloat16 */ + __FP8_HOST_DEVICE__ operator __hip_bfloat16() const { + float f = *this; + return __hip_bfloat16(f); + } + + /*! convert fp8 e4m3 to bool, return false if value is 0, true otherwise */ + __FP8_HOST_DEVICE__ operator bool() const { + // it can be 0x00 (+0.0) since 0x80 will be nan + return !(static_cast(__x) == 0); + } + + /*! convert fp8 e4m3 to char, clamp number to CHAR_MIN/CHAR_MAX if its out of range */ + __FP8_HOST_DEVICE__ operator char() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + auto fval = internal::cast_from_f8(__x, __wm, __we); + auto llval = static_cast(fval); + if (llval <= CHAR_MIN) { + return CHAR_MIN; + } else if (llval >= CHAR_MAX) { + return CHAR_MAX; + } + return static_cast(fval); + } + + /*! convert fp8 e4m3 to double */ + __FP8_HOST_DEVICE__ operator double() const { + return internal::cast_from_f8(__x, __wm, __we); + } + + /*! convert fp8 e4m3 to float */ + __FP8_HOST_DEVICE__ operator float() const { +#if HIP_FP8_CVT_FAST_PATH + return internal::cast_to_f32_from_f8(__x, __default_interpret); +#else + return internal::cast_from_f8(__x, __wm, __we); +#endif + } + + /*! convert fp8 e4m3 to int, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + return static_cast(fval); + } + + /*! convert fp8 e4m3 to long, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator long int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + return static_cast(fval); + } + + /*! convert fp8 e4m3 to long long, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator long long int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + return static_cast(fval); + } + + /*! convert fp8 e4m3 to short int, clamp out of bound values, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator short int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + auto llval = static_cast(fval); + if (llval <= SHRT_MIN) { + return SHRT_MIN; + } else if (llval >= SHRT_MAX) { + return SHRT_MAX; + } + return static_cast(fval); + } + + /*! convert fp8 e4m3 to signed char, clamp out of bound values, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator signed char() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + auto llval = static_cast(fval); + if (llval <= SCHAR_MIN) { + return SCHAR_MIN; + } else if (llval >= SCHAR_MAX) { + return SCHAR_MAX; + } + return static_cast(fval); + } + + /*! convert fp8 e4m3 to unsigned char, clamp out of bound values, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator unsigned char() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + auto llval = static_cast(fval); + if (llval <= 0) { + return 0; + } else if (llval >= UCHAR_MAX) { + return UCHAR_MAX; + } + return static_cast(fval); + } + + /*! convert fp8 e4m3 to unsigned int, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator unsigned int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + auto llval = static_cast(fval); + if (llval <= 0) { + return 0; + } + return static_cast(fval); + } + + /*! convert fp8 e4m3 to unsigned long, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator unsigned long int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + auto llval = static_cast(fval); + if (llval <= 0) { + return 0; + } + return static_cast(fval); + } + + /*! convert fp8 e4m3 to long long int, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator unsigned long long int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + auto llval = static_cast(fval); + if (llval <= 0) { + return 0; + } + return static_cast(fval); + } + + /*! convert fp8 e4m3 to unsigned short, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator unsigned short int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + auto llval = static_cast(fval); + if (llval <= 0) { + return 0; + } + return static_cast(fval); + } +}; + +/** + * \brief struct representing two fp8 numbers with e4m3 interpretation + * + */ +struct __hip_fp8x2_e4m3_fnuz { + __hip_fp8x2_storage_t __x; //! raw storage of two fp8 numbers + static constexpr __hip_saturation_t __default_saturation = __HIP_SATFINITE; + static constexpr __hip_fp8_interpretation_t __default_interpret = __HIP_E4M3_FNUZ; + static constexpr unsigned int __we = 4; + static constexpr unsigned int __wm = 3; + + /*! create fp8x2 e4m3 type from double2 */ + __FP8_HOST_DEVICE__ __hip_fp8x2_e4m3_fnuz(const double2 val) + : __x(__hip_cvt_double2_to_fp8x2(val, __default_saturation, __default_interpret)) {} + + /*! create fp8x2 e4m3 type from float2 */ + __FP8_HOST_DEVICE__ __hip_fp8x2_e4m3_fnuz(const float2 val) + : __x(__hip_cvt_float2_to_fp8x2(val, __default_saturation, __default_interpret)) {} + + /*! create fp8x2 e4m3 type from __hip_bfloat162 */ + __FP8_HOST_DEVICE__ __hip_fp8x2_e4m3_fnuz(const __hip_bfloat162 val) + : __x(__hip_cvt_bfloat16raw2_to_fp8x2(val, __default_saturation, __default_interpret)) {} + + /*! create fp8x2 e4m3 type from __half2 */ + __FP8_HOST_DEVICE__ __hip_fp8x2_e4m3_fnuz(const __half2 val) + : __x(__hip_cvt_halfraw2_to_fp8x2(val, __default_saturation, __default_interpret)) {} + + /*! Default construct of fp8x2 e4m3 */ + __FP8_HOST_DEVICE__ __hip_fp8x2_e4m3_fnuz() = default; + + /*! convert fp8x2 e4m3 to __half2 */ + __FP8_HOST_DEVICE__ operator __half2() const { + return __half2(__hip_cvt_fp8x2_to_halfraw2(__x, __default_interpret)); + } + + /*! convert fp8x2 e4m3 to float2 */ + __FP8_HOST_DEVICE__ operator float2() const { +#if HIP_FP8_CVT_FAST_PATH + return internal::cast_to_f32x2_from_f8x2(__x, __default_interpret); +#else + return float2(internal::cast_from_f8(static_cast<__hip_fp8_storage_t>(__x & 0xFF), + __wm, __we), + internal::cast_from_f8(static_cast<__hip_fp8_storage_t>(__x >> 8), + __wm, __we)); +#endif + } +}; + +/** + * \brief struct representing four fp8 numbers with e4m3 interpretation + * + */ +struct __hip_fp8x4_e4m3_fnuz { + __hip_fp8x4_storage_t __x; //! raw storage of four fp8 numbers + static constexpr __hip_saturation_t __default_saturation = __HIP_SATFINITE; + static constexpr __hip_fp8_interpretation_t __default_interpret = __HIP_E4M3_FNUZ; + static constexpr unsigned int __we = 4; + static constexpr unsigned int __wm = 3; + + /*! create fp8x4 e4m3 type from double4 */ + __FP8_HOST_DEVICE__ __hip_fp8x4_e4m3_fnuz(const double4 val) + : __x{reinterpret_cast<__hip_fp8x4_storage_t>( + static_cast(reinterpret_cast(__hip_cvt_double_to_fp8( + val.x, __default_saturation, __default_interpret)) | + reinterpret_cast(__hip_cvt_double_to_fp8( + val.y, __default_saturation, __default_interpret)) + << 8 | + reinterpret_cast(__hip_cvt_double_to_fp8( + val.z, __default_saturation, __default_interpret)) + << 16 | + reinterpret_cast(__hip_cvt_double_to_fp8( + val.w, __default_saturation, __default_interpret)) + << 24))} {} + + /*! create fp8x4 e4m3 type from float4 */ + __FP8_HOST_DEVICE__ __hip_fp8x4_e4m3_fnuz(const float4 val) + : __x{reinterpret_cast<__hip_fp8x4_storage_t>( + static_cast(reinterpret_cast(__hip_cvt_float_to_fp8( + val.x, __default_saturation, __default_interpret)) | + reinterpret_cast(__hip_cvt_float_to_fp8( + val.y, __default_saturation, __default_interpret)) + << 8 | + reinterpret_cast(__hip_cvt_float_to_fp8( + val.z, __default_saturation, __default_interpret)) + << 16 | + reinterpret_cast(__hip_cvt_float_to_fp8( + val.w, __default_saturation, __default_interpret)) + << 24))} {} + + /*! create fp8x4 e4m3 type from two __hip_bfloat162 */ + __FP8_HOST_DEVICE__ __hip_fp8x4_e4m3_fnuz(const __hip_bfloat162 low, const __hip_bfloat162 high) + : __x(reinterpret_cast<__hip_fp8x4_storage_t>(static_cast( + reinterpret_cast( + __hip_cvt_bfloat16raw2_to_fp8x2(high, __default_saturation, __default_interpret)) | + reinterpret_cast( + __hip_cvt_bfloat16raw2_to_fp8x2(low, __default_saturation, __default_interpret)) + << 16))) {} + + /*! create fp8x4 e4m3 type from two __half2 */ + __FP8_HOST_DEVICE__ __hip_fp8x4_e4m3_fnuz(const __half2 low, const __half2 high) + : __x(reinterpret_cast<__hip_fp8x4_storage_t>( + static_cast(reinterpret_cast(__hip_cvt_halfraw2_to_fp8x2( + high, __default_saturation, __default_interpret)) | + reinterpret_cast(__hip_cvt_halfraw2_to_fp8x2( + low, __default_saturation, __default_interpret)) + << 16))) {} + + /*! Default construct fp8x4 e4m3 */ + __FP8_HOST_DEVICE__ __hip_fp8x4_e4m3_fnuz() = default; + + /*! convert fp8x4 e4m3 to float4 */ + __FP8_HOST_DEVICE__ operator float4() const { + auto x = __x; // bypass const + auto fp8x2_low = *reinterpret_cast<__hip_fp8x2_storage_t*>(&x); // Little E + auto fp8x2_high = *(reinterpret_cast<__hip_fp8x2_storage_t*>(&x) + 1); +#if HIP_FP8_CVT_FAST_PATH + float2 high = internal::cast_to_f32x2_from_f8x2(fp8x2_high, __default_interpret); + float2 low = internal::cast_to_f32x2_from_f8x2(fp8x2_low, __default_interpret); +#else + float2 high = float2(internal::cast_from_f8( + static_cast<__hip_fp8_storage_t>((fp8x2_high << 8) >> 8), __wm, __we), + internal::cast_from_f8( + static_cast<__hip_fp8_storage_t>(fp8x2_high >> 8), __wm, __we)); + float2 low = float2(internal::cast_from_f8( + static_cast<__hip_fp8_storage_t>((fp8x2_low << 8) >> 8), __wm, __we), + internal::cast_from_f8( + static_cast<__hip_fp8_storage_t>(fp8x2_low >> 8), __wm, __we)); +#endif + return float4(low.x, low.y, high.x, high.y); + } +}; + +/** + * \brief struct representing one fp8 number with e5m2 interpretation + * + */ +struct __hip_fp8_e5m2_fnuz { + __hip_fp8_storage_t __x; //! raw storage of one fp8 numbers + static constexpr __hip_saturation_t __default_saturation = __HIP_SATFINITE; + static constexpr __hip_fp8_interpretation_t __default_interpret = __HIP_E5M2_FNUZ; + static constexpr unsigned int __we = 5; + static constexpr unsigned int __wm = 2; + + + // TODO: SWDEV-452411 + // Add cast from unsigned long long, long long to fp8 + + /*! create fp8 e5m2 type from long */ + __FP8_HOST_DEVICE__ __hip_fp8_e5m2_fnuz(const long int val) + : __x(__hip_cvt_float_to_fp8(static_cast(val), __default_saturation, + __default_interpret)) {} + + /*! create fp8 e5m2 type from int */ + __FP8_HOST_DEVICE__ __hip_fp8_e5m2_fnuz(const int val) + : __x(__hip_cvt_float_to_fp8(static_cast(val), __default_saturation, + __default_interpret)) {} + + /*! create fp8 e5m2 type from short int */ + __FP8_HOST_DEVICE__ __hip_fp8_e5m2_fnuz(const short int val) + : __x(__hip_cvt_float_to_fp8(static_cast(val), __default_saturation, + __default_interpret)) {} + + /*! create fp8 e5m2 type from unsigned long */ + __FP8_HOST_DEVICE__ __hip_fp8_e5m2_fnuz(const unsigned long int val) + : __x(__hip_cvt_float_to_fp8(static_cast(val), __default_saturation, + __default_interpret)) {} + + /*! create fp8 e5m2 type from unsigned int */ + __FP8_HOST_DEVICE__ __hip_fp8_e5m2_fnuz(const unsigned int val) + : __x(__hip_cvt_float_to_fp8(static_cast(val), __default_saturation, + __default_interpret)) {} + + /*! create fp8 e5m2 type from unsigned short */ + __FP8_HOST_DEVICE__ __hip_fp8_e5m2_fnuz(const unsigned short int val) + : __x(__hip_cvt_float_to_fp8(static_cast(val), __default_saturation, + __default_interpret)) {} + + /*! create fp8 e5m2 type from double */ + __FP8_HOST_DEVICE__ __hip_fp8_e5m2_fnuz(const double f) + : __x(__hip_cvt_double_to_fp8(f, __default_saturation, __default_interpret)) {} + + /*! create fp8 e5m2 type from float */ + __FP8_HOST_DEVICE__ __hip_fp8_e5m2_fnuz(const float f) + : __x(__hip_cvt_float_to_fp8(f, __default_saturation, __default_interpret)) {} + + /*! create fp8 e5m2 type from __hip_bfloat16 */ + __FP8_HOST_DEVICE__ __hip_fp8_e5m2_fnuz(const __hip_bfloat16 f) + : __x(__hip_cvt_float_to_fp8(static_cast(f), __default_saturation, + __default_interpret)) {} + + /*! create fp8 e5m2 type from __hip_bfloat16 */ + __FP8_HOST_DEVICE__ __hip_fp8_e5m2_fnuz(const __half f) + : __x(__hip_cvt_halfraw_to_fp8(static_cast<__half_raw>(f), __default_saturation, + __default_interpret)) {} + + /*! default construct fp8 e5m2 */ + __FP8_HOST_DEVICE__ __hip_fp8_e5m2_fnuz() = default; + + /*! convert fp8 e5m2 to float */ + __FP8_HOST_DEVICE__ operator float() const { +#if HIP_FP8_CVT_FAST_PATH + return internal::cast_to_f32_from_f8(__x, __default_interpret); +#else + return internal::cast_from_f8(__x, __wm, __we); +#endif + } + + /*! convert fp8 e5m2 to __half */ + __FP8_HOST_DEVICE__ operator __half() const { + return __half(__hip_cvt_fp8_to_halfraw(__x, __default_interpret)); + } + + /*! convert fp8 e5m2 to __hip_bfloat16 */ + __FP8_HOST_DEVICE__ operator __hip_bfloat16() const { + float f = *this; + return __hip_bfloat16(f); + } + + /*! convert fp8 e4m3 to bool, return false if value is 0, true otherwise */ + __FP8_HOST_DEVICE__ operator bool() const { + // it can be 0x00 (+0.0) since 0x80 will be nan + return !(static_cast(__x) == 0); + } + + /*! convert fp8 e5m2 to char, clamp out of bound values, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator char() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + auto llval = static_cast(fval); + if (llval <= CHAR_MIN) { + return CHAR_MIN; + } else if (llval >= CHAR_MAX) { + return CHAR_MAX; + } + return static_cast(fval); + } + + /*! convert fp8 e5m2 to double */ + __FP8_HOST_DEVICE__ operator double() const { + return internal::cast_from_f8(__x, __wm, __we); + } + + /*! convert fp8 e5m2 to int, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + return static_cast(fval); + } + + /*! convert fp8 e5m2 to long, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator long int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + return static_cast(fval); + } + + /*! convert fp8 e5m2 to long long, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator long long int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + return static_cast(fval); + } + + /*! convert fp8 e5m2 to short, clamp out of bound values, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator short int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + auto llval = static_cast(fval); + if (llval <= SHRT_MIN) { + return SHRT_MIN; + } else if (llval >= SHRT_MAX) { + return SHRT_MAX; + } + return static_cast(fval); + } + + /*! convert fp8 e5m2 to signed char, clamp out of bound values, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator signed char() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + auto llval = static_cast(fval); + if (llval <= SCHAR_MIN) { + return SCHAR_MIN; + } else if (llval >= SCHAR_MAX) { + return SCHAR_MAX; + } + return static_cast(fval); + } + + /*! convert fp8 e5m2 to unsigned char, clamp out of bound values, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator unsigned char() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + auto llval = static_cast(fval); + if (llval <= 0) { + return 0; + } else if (llval >= UCHAR_MAX) { + return UCHAR_MAX; + } + return static_cast(fval); + } + + /*! convert fp8 e5m2 to unsigned int, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator unsigned int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + auto llval = static_cast(fval); + if (llval <= 0) { + return 0; + } + return static_cast(fval); + } + + /*! convert fp8 e5m2 to unsigned long, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator unsigned long int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + auto llval = static_cast(fval); + if (llval <= 0) { + return 0; + } + return static_cast(fval); + } + + /*! convert fp8 e5m2 to unsigned long long, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator unsigned long long int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + auto llval = static_cast(fval); + if (llval <= 0) { + return 0; + } + return static_cast(fval); + } + + /*! convert fp8 e5m2 to unsigned short, return 0 if value is NaN */ + __FP8_HOST_DEVICE__ operator unsigned short int() const { + if (internal::hip_fp8_fnuz_is_nan(__x)) { + return 0; + } + + float fval = *this; + auto llval = static_cast(fval); + if (llval <= 0) { + return 0; + } + return static_cast(fval); + } +}; + +/** + * \brief struct representing two fp8 numbers with e5m2 interpretation + * + */ +struct __hip_fp8x2_e5m2_fnuz { + __hip_fp8x2_storage_t __x; //! raw storage of two fp8 numbers + static constexpr __hip_saturation_t __default_saturation = __HIP_SATFINITE; + static constexpr __hip_fp8_interpretation_t __default_interpret = __HIP_E5M2_FNUZ; + static constexpr unsigned int __we = 5; + static constexpr unsigned int __wm = 2; + + /*! create fp8x2 e5m2 type from double2 */ + __FP8_HOST_DEVICE__ __hip_fp8x2_e5m2_fnuz(const double2 val) + : __x(__hip_cvt_double2_to_fp8x2(val, __default_saturation, __default_interpret)) {} + + /*! create fp8x2 e5m2 type from float2 */ + __FP8_HOST_DEVICE__ __hip_fp8x2_e5m2_fnuz(const float2 val) + : __x(__hip_cvt_float2_to_fp8x2(val, __default_saturation, __default_interpret)) {} + + /*! create fp8x2 e5m2 type from __hip_bfloat162 */ + __FP8_HOST_DEVICE__ __hip_fp8x2_e5m2_fnuz(const __hip_bfloat162 val) + : __x(__hip_cvt_bfloat16raw2_to_fp8x2(val, __default_saturation, __default_interpret)) {} + + /*! create fp8x2 e5m2 type from __half2 */ + __FP8_HOST_DEVICE__ __hip_fp8x2_e5m2_fnuz(const __half2 val) + : __x(__hip_cvt_halfraw2_to_fp8x2(val, __default_saturation, __default_interpret)) {} + + /*! default construct fp8x2 e5m2 */ + __FP8_HOST_DEVICE__ __hip_fp8x2_e5m2_fnuz() = default; + + /*! convert fp8x2 e5m2 to __half2 */ + __FP8_HOST_DEVICE__ operator __half2() const { + return __half2(__hip_cvt_fp8x2_to_halfraw2(__x, __default_interpret)); + } + + /*! convert fp8x2 e5m2 to float2 */ + __FP8_HOST_DEVICE__ operator float2() const { +#if HIP_FP8_CVT_FAST_PATH + return internal::cast_to_f32x2_from_f8x2(__x, __default_interpret); +#else + return float2(internal::cast_from_f8(static_cast<__hip_fp8_storage_t>(__x & 0xFF), + __wm, __we), + internal::cast_from_f8(static_cast<__hip_fp8_storage_t>(__x >> 8), + __wm, __we)); +#endif + } +}; + +/** + * \brief struct representing four fp8 numbers with e5m2 interpretation + * + */ +struct __hip_fp8x4_e5m2_fnuz { + __hip_fp8x4_storage_t __x; //! raw storage of four fp8 numbers + static constexpr __hip_saturation_t __default_saturation = __HIP_SATFINITE; + static constexpr __hip_fp8_interpretation_t __default_interpret = __HIP_E5M2_FNUZ; + static constexpr unsigned int __we = 5; + static constexpr unsigned int __wm = 2; + + /*! create fp8x4 e5m2 type from double4 */ + __FP8_HOST_DEVICE__ __hip_fp8x4_e5m2_fnuz(const double4 val) + : __x(reinterpret_cast<__hip_fp8x4_storage_t>( + static_cast(reinterpret_cast(__hip_cvt_double_to_fp8( + val.x, __default_saturation, __default_interpret)) | + reinterpret_cast(__hip_cvt_double_to_fp8( + val.y, __default_saturation, __default_interpret)) + << 8 | + reinterpret_cast(__hip_cvt_double_to_fp8( + val.z, __default_saturation, __default_interpret)) + << 16 | + reinterpret_cast(__hip_cvt_double_to_fp8( + val.w, __default_saturation, __default_interpret)) + << 24))) {} + + /*! create fp8x4 e5m2 type from float4 */ + __FP8_HOST_DEVICE__ __hip_fp8x4_e5m2_fnuz(const float4 val) + : __x(reinterpret_cast<__hip_fp8x4_storage_t>( + static_cast(reinterpret_cast(__hip_cvt_float_to_fp8( + val.x, __default_saturation, __default_interpret)) | + reinterpret_cast(__hip_cvt_float_to_fp8( + val.y, __default_saturation, __default_interpret)) + << 8 | + reinterpret_cast(__hip_cvt_float_to_fp8( + val.z, __default_saturation, __default_interpret)) + << 16 | + reinterpret_cast(__hip_cvt_float_to_fp8( + val.w, __default_saturation, __default_interpret)) + << 24))) {} + + /*! create fp8x4 e5m2 type from two __hip_bfloat162 */ + __FP8_HOST_DEVICE__ __hip_fp8x4_e5m2_fnuz(const __hip_bfloat162 low, const __hip_bfloat162 high) + : __x(reinterpret_cast<__hip_fp8x4_storage_t>(static_cast( + reinterpret_cast( + __hip_cvt_bfloat16raw2_to_fp8x2(high, __default_saturation, __default_interpret)) | + reinterpret_cast( + __hip_cvt_bfloat16raw2_to_fp8x2(low, __default_saturation, __default_interpret)) + << 16))) {} + + /*! create fp8x4 e5m2 type from two __half2 */ + __FP8_HOST_DEVICE__ __hip_fp8x4_e5m2_fnuz(const __half2 low, const __half2 high) + : __x(reinterpret_cast<__hip_fp8x4_storage_t>( + static_cast(reinterpret_cast(__hip_cvt_halfraw2_to_fp8x2( + high, __default_saturation, __default_interpret)) | + reinterpret_cast(__hip_cvt_halfraw2_to_fp8x2( + low, __default_saturation, __default_interpret)) + << 16))) {} + + /* default construct fp8x4 e5m2 */ + __FP8_HOST_DEVICE__ __hip_fp8x4_e5m2_fnuz() = default; + + /*! convert fp8x4 e5m2 to float4 */ + __FP8_HOST_DEVICE__ operator float4() const { + auto x = __x; // bypass const + auto fp8x2_low = *reinterpret_cast<__hip_fp8x2_storage_t*>(&x); // Little E + auto fp8x2_high = *(reinterpret_cast<__hip_fp8x2_storage_t*>(&x) + 1); +#if HIP_FP8_CVT_FAST_PATH + float2 high = internal::cast_to_f32x2_from_f8x2(fp8x2_high, __default_interpret); + float2 low = internal::cast_to_f32x2_from_f8x2(fp8x2_low, __default_interpret); +#else + float2 high = float2(internal::cast_from_f8( + static_cast<__hip_fp8_storage_t>((fp8x2_high << 8) >> 8), __wm, __we), + internal::cast_from_f8( + static_cast<__hip_fp8_storage_t>(fp8x2_high >> 8), __wm, __we)); + float2 low = float2(internal::cast_from_f8( + static_cast<__hip_fp8_storage_t>((fp8x2_low << 8) >> 8), __wm, __we), + internal::cast_from_f8( + static_cast<__hip_fp8_storage_t>(fp8x2_low >> 8), __wm, __we)); +#endif + return float4(low.x, low.y, high.x, high.y); + } +}; + +#endif // _HIP_INCLUDE_HIP_AMD_DETAIL_HIP_FP8_H_ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_gl_interop.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_gl_interop.h new file mode 100644 index 0000000000000000000000000000000000000000..740e37a6db47b5e51b948e5f25ab4f3bf7cc8a14 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_gl_interop.h @@ -0,0 +1,108 @@ +/* +Copyright (c) 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_AMD_HIP_GL_INTEROP_H +#define HIP_INCLUDE_AMD_HIP_GL_INTEROP_H + +#if defined(__cplusplus) +extern "C" { +#endif + +/** + * + * @addtogroup GlobalDefs + * @{ + * + */ + +/** + * HIP Devices used by current OpenGL Context. + */ +typedef enum hipGLDeviceList { + hipGLDeviceListAll = 1, ///< All hip devices used by current OpenGL context. + hipGLDeviceListCurrentFrame = 2, ///< Hip devices used by current OpenGL context in current + ///< frame + hipGLDeviceListNextFrame = 3 ///< Hip devices used by current OpenGL context in next + ///< frame. +} hipGLDeviceList; + + +/** GLuint as uint.*/ +typedef unsigned int GLuint; +/** GLenum as uint.*/ +typedef unsigned int GLenum; +/** +* @} +*/ + +/** + * @ingroup GL + * @{ + * + */ +/** + * @brief Queries devices associated with the current OpenGL context. + * + * @param [out] pHipDeviceCount - Pointer of number of devices on the current GL context. + * @param [out] pHipDevices - Pointer of devices on the current OpenGL context. + * @param [in] hipDeviceCount - Size of device. + * @param [in] deviceList - The setting of devices. It could be either hipGLDeviceListCurrentFrame + * for the devices used to render the current frame, or hipGLDeviceListAll for all devices. + * The default setting is Invalid deviceList value. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + */ +hipError_t hipGLGetDevices(unsigned int* pHipDeviceCount, int* pHipDevices, + unsigned int hipDeviceCount, hipGLDeviceList deviceList); +/** + * @brief Registers a GL Buffer for interop and returns corresponding graphics resource. + * + * @param [out] resource - Returns pointer of graphics resource. + * @param [in] buffer - Buffer to be registered. + * @param [in] flags - Register flags. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown, #hipErrorInvalidResourceHandle + * + */ +hipError_t hipGraphicsGLRegisterBuffer(hipGraphicsResource** resource, GLuint buffer, + unsigned int flags); +/** + * @brief Register a GL Image for interop and returns the corresponding graphic resource. + * + * @param [out] resource - Returns pointer of graphics resource. + * @param [in] image - Image to be registered. + * @param [in] target - Valid target value Id. + * @param [in] flags - Register flags. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown, #hipErrorInvalidResourceHandle + * + */ +hipError_t hipGraphicsGLRegisterImage(hipGraphicsResource** resource, GLuint image, + GLenum target, unsigned int flags); +/** +* @} +*/ +#if defined(__cplusplus) +} +#endif /* __cplusplus */ +#endif /* HIP_INCLUDE_AMD_HIP_GL_INTEROP_H */ \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_math_constants.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_math_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..148fdcc4fb07f3b9fcca5bd6100bb6553413965a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_math_constants.h @@ -0,0 +1,124 @@ +/* +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 AMD_HIP_MATH_CONSTANTS_H +#define AMD_HIP_MATH_CONSTANTS_H + +// single precision constants +#define HIP_INF_F __int_as_float(0x7f800000U) +#define HIP_NAN_F __int_as_float(0x7fffffffU) +#define HIP_MIN_DENORM_F __int_as_float(0x00000001U) +#define HIP_MAX_NORMAL_F __int_as_float(0x7f7fffffU) +#define HIP_NEG_ZERO_F __int_as_float(0x80000000U) +#define HIP_ZERO_F 0.0F +#define HIP_ONE_F 1.0F +#define HIP_SQRT_HALF_F 0.707106781F +#define HIP_SQRT_HALF_HI_F 0.707106781F +#define HIP_SQRT_HALF_LO_F 1.210161749e-08F +#define HIP_SQRT_TWO_F 1.414213562F +#define HIP_THIRD_F 0.333333333F +#define HIP_PIO4_F 0.785398163F +#define HIP_PIO2_F 1.570796327F +#define HIP_3PIO4_F 2.356194490F +#define HIP_2_OVER_PI_F 0.636619772F +#define HIP_SQRT_2_OVER_PI_F 0.797884561F +#define HIP_PI_F 3.141592654F +#define HIP_L2E_F 1.442695041F +#define HIP_L2T_F 3.321928094F +#define HIP_LG2_F 0.301029996F +#define HIP_LGE_F 0.434294482F +#define HIP_LN2_F 0.693147181F +#define HIP_LNT_F 2.302585093F +#define HIP_LNPI_F 1.144729886F +#define HIP_TWO_TO_M126_F 1.175494351e-38F +#define HIP_TWO_TO_126_F 8.507059173e37F +#define HIP_NORM_HUGE_F 3.402823466e38F +#define HIP_TWO_TO_23_F 8388608.0F +#define HIP_TWO_TO_24_F 16777216.0F +#define HIP_TWO_TO_31_F 2147483648.0F +#define HIP_TWO_TO_32_F 4294967296.0F +#define HIP_REMQUO_BITS_F 3U +#define HIP_REMQUO_MASK_F (~((~0U)< + +#if !defined(__HIPCC_RTC__) +#ifdef __cplusplus +#include +#else +#include +#endif // __cplusplus +#endif // !defined(__HIPCC_RTC__) + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Query the installed library build name. + * + * This function can be used even when the library is not initialized. + * + * @returns Returns a string describing the build version of the library. The + * string is owned by the library. + */ +const char* amd_dbgapi_get_build_name(); + +/** + * @brief Query the installed library git hash. + * + * This function can be used even when the library is not initialized. + * + * @returns Returns git hash of the library. + */ +const char* amd_dbgapi_get_git_hash(); + +/** + * @brief Query the installed library build ID. + * + * This function can be used even when the library is not initialized. + * + * @returns Returns build ID of the library. + */ +size_t amd_dbgapi_get_build_id(); + +#ifdef __cplusplus +} /* extern "c" */ +#endif + +//--- +// Top part of file can be compiled with any compiler + +#if !defined(__HIPCC_RTC__) +#ifdef __cplusplus +#include +#include +#include +#else +#include +#include +#endif // __cplusplus +#else +#if !__HIP_NO_STD_DEFS__ +typedef unsigned int uint32_t; +typedef unsigned long long uint64_t; +typedef signed int int32_t; +typedef signed long long int64_t; +namespace std { +using ::uint32_t; +using ::uint64_t; +using ::int32_t; +using ::int64_t; +} +#endif // __HIP_NO_STD_DEFS__ +#endif // !defined(__HIPCC_RTC__) + +#if __HIP_CLANG_ONLY__ + +#if !defined(__align__) +#define __align__(x) __attribute__((aligned(x))) +#endif + +#define CUDA_SUCCESS hipSuccess + +#if !defined(__HIPCC_RTC__) +#include +#include +#include +#include +#include +#include +extern int HIP_TRACE_API; +#endif // !defined(__HIPCC_RTC__) + +#ifdef __cplusplus +#include +#endif + +#include + +// TODO-HCC remove old definitions ; ~1602 hcc supports __HCC_ACCELERATOR__ define. +#if defined(__KALMAR_ACCELERATOR__) && !defined(__HCC_ACCELERATOR__) +#define __HCC_ACCELERATOR__ __KALMAR_ACCELERATOR__ +#endif + +// Feature tests: +#if (defined(__HCC_ACCELERATOR__) && (__HCC_ACCELERATOR__ != 0)) || __HIP_DEVICE_COMPILE__ +// Device compile and not host compile: + +// 32-bit Atomics: +#define __HIP_ARCH_HAS_GLOBAL_INT32_ATOMICS__ (1) +#define __HIP_ARCH_HAS_GLOBAL_FLOAT_ATOMIC_EXCH__ (1) +#define __HIP_ARCH_HAS_SHARED_INT32_ATOMICS__ (1) +#define __HIP_ARCH_HAS_SHARED_FLOAT_ATOMIC_EXCH__ (1) +#define __HIP_ARCH_HAS_FLOAT_ATOMIC_ADD__ (1) + +// 64-bit Atomics: +#define __HIP_ARCH_HAS_GLOBAL_INT64_ATOMICS__ (1) +#define __HIP_ARCH_HAS_SHARED_INT64_ATOMICS__ (1) + +// Doubles +#define __HIP_ARCH_HAS_DOUBLES__ (1) + +// warp cross-lane operations: +#define __HIP_ARCH_HAS_WARP_VOTE__ (1) +#define __HIP_ARCH_HAS_WARP_BALLOT__ (1) +#define __HIP_ARCH_HAS_WARP_SHUFFLE__ (1) +#define __HIP_ARCH_HAS_WARP_FUNNEL_SHIFT__ (0) + +// sync +#define __HIP_ARCH_HAS_THREAD_FENCE_SYSTEM__ (1) +#define __HIP_ARCH_HAS_SYNC_THREAD_EXT__ (0) + +// misc +#define __HIP_ARCH_HAS_SURFACE_FUNCS__ (0) +#define __HIP_ARCH_HAS_3DGRID__ (1) +#define __HIP_ARCH_HAS_DYNAMIC_PARALLEL__ (0) + +#endif /* Device feature flags */ + + +#define launch_bounds_impl0(requiredMaxThreadsPerBlock) \ + __attribute__((amdgpu_flat_work_group_size(1, requiredMaxThreadsPerBlock))) +#define launch_bounds_impl1(requiredMaxThreadsPerBlock, minBlocksPerMultiprocessor) \ + __attribute__((amdgpu_flat_work_group_size(1, requiredMaxThreadsPerBlock), \ + amdgpu_waves_per_eu(minBlocksPerMultiprocessor))) +#define select_impl_(_1, _2, impl_, ...) impl_ +#define __launch_bounds__(...) \ + select_impl_(__VA_ARGS__, launch_bounds_impl1, launch_bounds_impl0, )(__VA_ARGS__) + +#if !defined(__HIPCC_RTC__) +__host__ inline void* __get_dynamicgroupbaseptr() { return nullptr; } +#endif // !defined(__HIPCC_RTC__) + +// End doxygen API: +/** + * @} + */ + +// +// hip-clang functions +// +#if !defined(__HIPCC_RTC__) +#define HIP_KERNEL_NAME(...) __VA_ARGS__ +#define HIP_SYMBOL(X) X + +typedef int hipLaunchParm; + +template ::type* = nullptr> +void pArgs(const std::tuple&, void*) {} + +template ::type* = nullptr> +void pArgs(const std::tuple& formals, void** _vargs) { + using T = typename std::tuple_element >::type; + + static_assert(!std::is_reference{}, + "A __global__ function cannot have a reference as one of its " + "arguments."); +#if defined(HIP_STRICT) + static_assert(std::is_trivially_copyable{}, + "Only TriviallyCopyable types can be arguments to a __global__ " + "function"); +#endif + _vargs[n] = const_cast(reinterpret_cast(&std::get(formals))); + return pArgs(formals, _vargs); +} + +template +std::tuple validateArgsCountType(void (*kernel)(Formals...), std::tuple(actuals)) { + static_assert(sizeof...(Formals) == sizeof...(Actuals), "Argument Count Mismatch"); + std::tuple to_formals{std::move(actuals)}; + return to_formals; +} + +#if defined(HIP_TEMPLATE_KERNEL_LAUNCH) +template +void hipLaunchKernelGGL(F kernel, const dim3& numBlocks, const dim3& dimBlocks, + std::uint32_t sharedMemBytes, hipStream_t stream, Args... args) { + constexpr size_t count = sizeof...(Args); + auto tup_ = std::tuple{args...}; + auto tup = validateArgsCountType(kernel, tup_); + void* _Args[count]; + pArgs<0>(tup, _Args); + + auto k = reinterpret_cast(kernel); + hipLaunchKernel(k, numBlocks, dimBlocks, _Args, sharedMemBytes, stream); +} +#else +#define hipLaunchKernelGGLInternal(kernelName, numBlocks, numThreads, memPerBlock, streamId, ...) \ + do { \ + kernelName<<<(numBlocks), (numThreads), (memPerBlock), (streamId)>>>(__VA_ARGS__); \ + } while (0) + +#define hipLaunchKernelGGL(kernelName, ...) hipLaunchKernelGGLInternal((kernelName), __VA_ARGS__) +#endif + +#include +#endif // !defined(__HIPCC_RTC__) + +#if defined(__HIPCC_RTC__) +typedef struct dim3 { + uint32_t x; ///< x + uint32_t y; ///< y + uint32_t z; ///< z +#ifdef __cplusplus + constexpr __device__ dim3(uint32_t _x = 1, uint32_t _y = 1, uint32_t _z = 1) : x(_x), y(_y), z(_z){}; +#endif +} dim3; +#endif // !defined(__HIPCC_RTC__) + +#pragma push_macro("__DEVICE__") +#define __DEVICE__ static __device__ __forceinline__ + +extern "C" __device__ __attribute__((const)) size_t __ockl_get_local_id(unsigned int); +__DEVICE__ unsigned int __hip_get_thread_idx_x() { return __ockl_get_local_id(0); } +__DEVICE__ unsigned int __hip_get_thread_idx_y() { return __ockl_get_local_id(1); } +__DEVICE__ unsigned int __hip_get_thread_idx_z() { return __ockl_get_local_id(2); } + +extern "C" __device__ __attribute__((const)) size_t __ockl_get_group_id(unsigned int); +__DEVICE__ unsigned int __hip_get_block_idx_x() { return __ockl_get_group_id(0); } +__DEVICE__ unsigned int __hip_get_block_idx_y() { return __ockl_get_group_id(1); } +__DEVICE__ unsigned int __hip_get_block_idx_z() { return __ockl_get_group_id(2); } + +extern "C" __device__ __attribute__((const)) size_t __ockl_get_local_size(unsigned int); +__DEVICE__ unsigned int __hip_get_block_dim_x() { return __ockl_get_local_size(0); } +__DEVICE__ unsigned int __hip_get_block_dim_y() { return __ockl_get_local_size(1); } +__DEVICE__ unsigned int __hip_get_block_dim_z() { return __ockl_get_local_size(2); } + +extern "C" __device__ __attribute__((const)) size_t __ockl_get_num_groups(unsigned int); +__DEVICE__ unsigned int __hip_get_grid_dim_x() { return __ockl_get_num_groups(0); } +__DEVICE__ unsigned int __hip_get_grid_dim_y() { return __ockl_get_num_groups(1); } +__DEVICE__ unsigned int __hip_get_grid_dim_z() { return __ockl_get_num_groups(2); } + +#define __HIP_DEVICE_BUILTIN(DIMENSION, FUNCTION) \ + __declspec(property(get = __get_##DIMENSION)) unsigned int DIMENSION; \ + __DEVICE__ unsigned int __get_##DIMENSION(void) { \ + return FUNCTION; \ + } + +struct __hip_builtin_threadIdx_t { + __HIP_DEVICE_BUILTIN(x,__hip_get_thread_idx_x()); + __HIP_DEVICE_BUILTIN(y,__hip_get_thread_idx_y()); + __HIP_DEVICE_BUILTIN(z,__hip_get_thread_idx_z()); +#ifdef __cplusplus + __device__ operator dim3() const { return dim3(x, y, z); } +#endif +}; + +struct __hip_builtin_blockIdx_t { + __HIP_DEVICE_BUILTIN(x,__hip_get_block_idx_x()); + __HIP_DEVICE_BUILTIN(y,__hip_get_block_idx_y()); + __HIP_DEVICE_BUILTIN(z,__hip_get_block_idx_z()); +#ifdef __cplusplus + __device__ operator dim3() const { return dim3(x, y, z); } +#endif +}; + +struct __hip_builtin_blockDim_t { + __HIP_DEVICE_BUILTIN(x,__hip_get_block_dim_x()); + __HIP_DEVICE_BUILTIN(y,__hip_get_block_dim_y()); + __HIP_DEVICE_BUILTIN(z,__hip_get_block_dim_z()); +#ifdef __cplusplus + __device__ operator dim3() const { return dim3(x, y, z); } +#endif +}; + +struct __hip_builtin_gridDim_t { + __HIP_DEVICE_BUILTIN(x,__hip_get_grid_dim_x()); + __HIP_DEVICE_BUILTIN(y,__hip_get_grid_dim_y()); + __HIP_DEVICE_BUILTIN(z,__hip_get_grid_dim_z()); +#ifdef __cplusplus + __device__ operator dim3() const { return dim3(x, y, z); } +#endif +}; + +#undef __HIP_DEVICE_BUILTIN +#pragma pop_macro("__DEVICE__") + +extern const __device__ __attribute__((weak)) __hip_builtin_threadIdx_t threadIdx; +extern const __device__ __attribute__((weak)) __hip_builtin_blockIdx_t blockIdx; +extern const __device__ __attribute__((weak)) __hip_builtin_blockDim_t blockDim; +extern const __device__ __attribute__((weak)) __hip_builtin_gridDim_t gridDim; + +#define hipThreadIdx_x threadIdx.x +#define hipThreadIdx_y threadIdx.y +#define hipThreadIdx_z threadIdx.z + +#define hipBlockIdx_x blockIdx.x +#define hipBlockIdx_y blockIdx.y +#define hipBlockIdx_z blockIdx.z + +#define hipBlockDim_x blockDim.x +#define hipBlockDim_y blockDim.y +#define hipBlockDim_z blockDim.z + +#define hipGridDim_x gridDim.x +#define hipGridDim_y gridDim.y +#define hipGridDim_z gridDim.z + +#if !defined(__HIPCC_RTC__) +#include +#endif + +#if __HIP_HCC_COMPAT_MODE__ +// Define HCC work item functions in terms of HIP builtin variables. +#pragma push_macro("__DEFINE_HCC_FUNC") +#define __DEFINE_HCC_FUNC(hc_fun,hip_var) \ +inline __device__ __attribute__((always_inline)) unsigned int hc_get_##hc_fun(unsigned int i) { \ + if (i==0) \ + return hip_var.x; \ + else if(i==1) \ + return hip_var.y; \ + else \ + return hip_var.z; \ +} + +__DEFINE_HCC_FUNC(workitem_id, threadIdx) +__DEFINE_HCC_FUNC(group_id, blockIdx) +__DEFINE_HCC_FUNC(group_size, blockDim) +__DEFINE_HCC_FUNC(num_groups, gridDim) +#pragma pop_macro("__DEFINE_HCC_FUNC") + +extern "C" __device__ __attribute__((const)) size_t __ockl_get_global_id(unsigned int); +inline __device__ __attribute__((always_inline)) unsigned int +hc_get_workitem_absolute_id(int dim) +{ + return (unsigned int)__ockl_get_global_id(dim); +} + +#endif + +#if !__CLANG_HIP_RUNTIME_WRAPPER_INCLUDED__ +#if !defined(__HIPCC_RTC__) +// Support std::complex. +#if !_OPENMP || __HIP_ENABLE_CUDA_WRAPPER_FOR_OPENMP__ +#pragma push_macro("__CUDA__") +#define __CUDA__ +#include <__clang_cuda_math_forward_declares.h> +#include <__clang_cuda_complex_builtins.h> +// Workaround for using libc++ with HIP-Clang. +// The following headers requires clang include path before standard C++ include path. +// However libc++ include path requires to be before clang include path. +// To workaround this, we pass -isystem with the parent directory of clang include +// path instead of the clang include path itself. +#include +#include +#include +#undef __CUDA__ +#pragma pop_macro("__CUDA__") +#endif // !_OPENMP || __HIP_ENABLE_CUDA_WRAPPER_FOR_OPENMP__ +#endif // !defined(__HIPCC_RTC__) +#endif // !__CLANG_HIP_RUNTIME_WRAPPER_INCLUDED__ +#endif // __HIP_CLANG_ONLY__ + +#endif // HIP_AMD_DETAIL_RUNTIME_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_runtime_pt_api.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_runtime_pt_api.h new file mode 100644 index 0000000000000000000000000000000000000000..0fb8bc2dfbbc731ce25ec0531ae4f55d872d22dc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_runtime_pt_api.h @@ -0,0 +1,196 @@ +/* +Copyright (c) 2022 - 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 + +#ifndef HIP_INCLUDE_HIP_HIP_RUNTIME_PT_API_H +#define HIP_INCLUDE_HIP_HIP_RUNTIME_PT_API_H + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) + +/// hipStreamPerThread implementation +#if defined(HIP_API_PER_THREAD_DEFAULT_STREAM) + #define __HIP_STREAM_PER_THREAD + #define __HIP_API_SPT(api) api ## _spt +#else + #define __HIP_API_SPT(api) api +#endif + +#if defined(__HIP_STREAM_PER_THREAD) + // Memory APIs + #define hipMemcpy __HIP_API_SPT(hipMemcpy) + #define hipMemcpyToSymbol __HIP_API_SPT(hipMemcpyToSymbol) + #define hipMemcpyFromSymbol __HIP_API_SPT(hipMemcpyFromSymbol) + #define hipMemcpy2D __HIP_API_SPT(hipMemcpy2D) + #define hipMemcpy2DFromArray __HIP_API_SPT(hipMemcpy2DFromArray) + #define hipMemcpy3D __HIP_API_SPT(hipMemcpy3D) + #define hipMemset __HIP_API_SPT(hipMemset) + #define hipMemset2D __HIP_API_SPT(hipMemset2D) + #define hipMemset3D __HIP_API_SPT(hipMemset3D) + #define hipMemcpyAsync __HIP_API_SPT(hipMemcpyAsync) + #define hipMemset3DAsync __HIP_API_SPT(hipMemset3DAsync) + #define hipMemset2DAsync __HIP_API_SPT(hipMemset2DAsync) + #define hipMemsetAsync __HIP_API_SPT(hipMemsetAsync) + #define hipMemcpy3DAsync __HIP_API_SPT(hipMemcpy3DAsync) + #define hipMemcpy2DAsync __HIP_API_SPT(hipMemcpy2DAsync) + #define hipMemcpyFromSymbolAsync __HIP_API_SPT(hipMemcpyFromSymbolAsync) + #define hipMemcpyToSymbolAsync __HIP_API_SPT(hipMemcpyToSymbolAsync) + #define hipMemcpyFromArray __HIP_API_SPT(hipMemcpyFromArray) + #define hipMemcpy2DToArray __HIP_API_SPT(hipMemcpy2DToArray) + #define hipMemcpy2DFromArrayAsync __HIP_API_SPT(hipMemcpy2DFromArrayAsync) + #define hipMemcpy2DToArrayAsync __HIP_API_SPT(hipMemcpy2DToArrayAsync) + + // Stream APIs + #define hipStreamSynchronize __HIP_API_SPT(hipStreamSynchronize) + #define hipStreamQuery __HIP_API_SPT(hipStreamQuery) + #define hipStreamGetFlags __HIP_API_SPT(hipStreamGetFlags) + #define hipStreamGetPriority __HIP_API_SPT(hipStreamGetPriority) + #define hipStreamWaitEvent __HIP_API_SPT(hipStreamWaitEvent) + #define hipStreamAddCallback __HIP_API_SPT(hipStreamAddCallback) + #define hipLaunchHostFunc __HIP_API_SPT(hipLaunchHostFunc) + + // Event APIs + #define hipEventRecord __HIP_API_SPT(hipEventRecord) + + // Launch APIs + #define hipLaunchKernel __HIP_API_SPT(hipLaunchKernel) + #define hipLaunchCooperativeKernel __HIP_API_SPT(hipLaunchCooperativeKernel) + + // Graph APIs + #define hipGraphLaunch __HIP_API_SPT(hipGraphLaunch) + #define hipStreamBeginCapture __HIP_API_SPT(hipStreamBeginCapture) + #define hipStreamEndCapture __HIP_API_SPT(hipStreamEndCapture) + #define hipStreamIsCapturing __HIP_API_SPT(hipStreamIsCapturing) + #define hipStreamGetCaptureInfo __HIP_API_SPT(hipStreamGetCaptureInfo) + #define hipStreamGetCaptureInfo_v2 __HIP_API_SPT(hipStreamGetCaptureInfo_v2) +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +hipError_t hipMemcpy_spt(void* dst, const void* src, size_t sizeBytes, hipMemcpyKind kind); + +hipError_t hipMemcpyToSymbol_spt(const void* symbol, const void* src, size_t sizeBytes, + size_t offset __dparm(0), + hipMemcpyKind kind __dparm(hipMemcpyHostToDevice)); + +hipError_t hipMemcpyFromSymbol_spt(void* dst, const void* symbol,size_t sizeBytes, + size_t offset __dparm(0), + hipMemcpyKind kind __dparm(hipMemcpyDeviceToHost)); + +hipError_t hipMemcpy2D_spt(void* dst, size_t dpitch, const void* src, size_t spitch, size_t width, + size_t height, hipMemcpyKind kind); + +hipError_t hipMemcpy2DFromArray_spt( void* dst, size_t dpitch, hipArray_const_t src, size_t wOffset, + size_t hOffset, size_t width, size_t height, hipMemcpyKind kind); + +hipError_t hipMemcpy3D_spt(const struct hipMemcpy3DParms* p); + +hipError_t hipMemset_spt(void* dst, int value, size_t sizeBytes); + +hipError_t hipMemsetAsync_spt(void* dst, int value, size_t sizeBytes, hipStream_t stream); + +hipError_t hipMemset2D_spt(void* dst, size_t pitch, int value, size_t width, size_t height); + +hipError_t hipMemset2DAsync_spt(void* dst, size_t pitch, int value, + size_t width, size_t height, hipStream_t stream); + +hipError_t hipMemset3DAsync_spt(hipPitchedPtr pitchedDevPtr, int value, hipExtent extent, hipStream_t stream); + +hipError_t hipMemset3D_spt(hipPitchedPtr pitchedDevPtr, int value, hipExtent extent ); + +hipError_t hipMemcpyAsync_spt(void* dst, const void* src, size_t sizeBytes, hipMemcpyKind kind, + hipStream_t stream); + +hipError_t hipMemcpy3DAsync_spt(const hipMemcpy3DParms* p, hipStream_t stream); + +hipError_t hipMemcpy2DAsync_spt(void* dst, size_t dpitch, const void* src, size_t spitch, size_t width, + size_t height, hipMemcpyKind kind, hipStream_t stream); + +hipError_t hipMemcpyFromSymbolAsync_spt(void* dst, const void* symbol, size_t sizeBytes, + size_t offset, hipMemcpyKind kind, hipStream_t stream); + +hipError_t hipMemcpyToSymbolAsync_spt(const void* symbol, const void* src, size_t sizeBytes, + size_t offset, hipMemcpyKind kind, hipStream_t stream); + +hipError_t hipMemcpyFromArray_spt(void* dst, hipArray_const_t src, size_t wOffsetSrc, size_t hOffset, + size_t count, hipMemcpyKind kind); + +hipError_t hipMemcpy2DToArray_spt(hipArray_t dst, size_t wOffset, size_t hOffset, const void* src, + size_t spitch, size_t width, size_t height, hipMemcpyKind kind); + +hipError_t hipMemcpy2DFromArrayAsync_spt(void* dst, size_t dpitch, hipArray_const_t src, + size_t wOffsetSrc, size_t hOffsetSrc, size_t width, size_t height, + hipMemcpyKind kind, hipStream_t stream); + +hipError_t hipMemcpy2DToArrayAsync_spt(hipArray_t dst, size_t wOffset, size_t hOffset, const void* src, + size_t spitch, size_t width, size_t height, hipMemcpyKind kind, + hipStream_t stream); + +hipError_t hipStreamQuery_spt(hipStream_t stream); + +hipError_t hipStreamSynchronize_spt(hipStream_t stream); + +hipError_t hipStreamGetPriority_spt(hipStream_t stream, int* priority); + +hipError_t hipStreamWaitEvent_spt(hipStream_t stream, hipEvent_t event, unsigned int flags __dparm(0)); + +hipError_t hipStreamGetFlags_spt(hipStream_t stream, unsigned int* flags); + +hipError_t hipStreamAddCallback_spt(hipStream_t stream, hipStreamCallback_t callback, void* userData, + unsigned int flags); +#ifdef __cplusplus +hipError_t hipEventRecord_spt(hipEvent_t event, hipStream_t stream = NULL); +#else +hipError_t hipEventRecord_spt(hipEvent_t event, hipStream_t stream); +#endif + +hipError_t hipLaunchCooperativeKernel_spt(const void* f, + dim3 gridDim, dim3 blockDim, + void **kernelParams, uint32_t sharedMemBytes, hipStream_t hStream); + +hipError_t hipLaunchKernel_spt(const void* function_address, + dim3 numBlocks, + dim3 dimBlocks, + void** args, + size_t sharedMemBytes, hipStream_t stream); + +hipError_t hipGraphLaunch_spt(hipGraphExec_t graphExec, hipStream_t stream); +hipError_t hipStreamBeginCapture_spt(hipStream_t stream, hipStreamCaptureMode mode); +hipError_t hipStreamEndCapture_spt(hipStream_t stream, hipGraph_t* pGraph); +hipError_t hipStreamIsCapturing_spt(hipStream_t stream, hipStreamCaptureStatus* pCaptureStatus); +hipError_t hipStreamGetCaptureInfo_spt(hipStream_t stream, hipStreamCaptureStatus* pCaptureStatus, + unsigned long long* pId); +hipError_t hipStreamGetCaptureInfo_v2_spt(hipStream_t stream, hipStreamCaptureStatus* captureStatus_out, + unsigned long long* id_out, hipGraph_t* graph_out, + const hipGraphNode_t** dependencies_out, + size_t* numDependencies_out); +hipError_t hipLaunchHostFunc_spt(hipStream_t stream, hipHostFn_t fn, void* userData); + + +#ifdef __cplusplus +} +#endif // extern "C" + +#endif //defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +#endif //HIP_INCLUDE_HIP_HIP_RUNTIME_PT_API_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_unsafe_atomics.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_unsafe_atomics.h new file mode 100644 index 0000000000000000000000000000000000000000..59841ab9b3fbb7d4b4261a24bc6903a8aedd8bd7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_unsafe_atomics.h @@ -0,0 +1,565 @@ +/* +Copyright (c) 2021 - 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. +*/ + +#pragma once + +#ifdef __cplusplus + +/** + * @brief Unsafe floating point rmw atomic add. + * + * Performs a relaxed read-modify-write floating point atomic add with + * device memory scope. Original value at \p addr is returned and + * the value of \p addr is updated to have the original value plus \p value + * + * @note This operation currently only performs different operations for + * the gfx90a target. Other devices continue to use safe atomics. + * + * It can be used to generate code that uses fast hardware floating point atomic + * operations which may handle rounding and subnormal values differently than + * non-atomic floating point operations. + * + * The operation is not always safe and can have undefined behavior unless + * following condition are met: + * + * - \p addr is at least 4 bytes aligned + * - If \p addr is a global segment address, it is in a coarse grain allocation. + * Passing in global segment addresses in fine grain allocations will result in + * undefined behavior and is not supported. + * + * @param [in,out] addr Pointer to value to be increment by \p value. + * @param [in] value Value by \p addr is to be incremented. + * @return Original value contained in \p addr. + */ +__device__ inline float unsafeAtomicAdd(float* addr, float value) { +#if defined(__gfx90a__) && \ + __has_builtin(__builtin_amdgcn_is_shared) && \ + __has_builtin(__builtin_amdgcn_is_private) && \ + __has_builtin(__builtin_amdgcn_ds_atomic_fadd_f32) && \ + __has_builtin(__builtin_amdgcn_global_atomic_fadd_f32) + if (__builtin_amdgcn_is_shared( + (const __attribute__((address_space(0))) void*)addr)) + return __builtin_amdgcn_ds_atomic_fadd_f32(addr, value); + else if (__builtin_amdgcn_is_private( + (const __attribute__((address_space(0))) void*)addr)) { + float temp = *addr; + *addr = temp + value; + return temp; + } + else + return __builtin_amdgcn_global_atomic_fadd_f32(addr, value); +#elif __has_builtin(__hip_atomic_fetch_add) + return __hip_atomic_fetch_add(addr, value, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); +#else + return __atomic_fetch_add(addr, value, __ATOMIC_RELAXED); +#endif +} + +/** + * @brief Unsafe floating point rmw atomic max. + * + * Performs a relaxed read-modify-write floating point atomic max with + * device memory scope. The original value at \p addr is returned and + * the value at \p addr is replaced by \p val if greater. + * + * @note This operation is currently identical to that performed by + * atomicMax and is included for completeness. + * + * @param [in,out] addr Pointer to value to be updated + * @param [in] val Value used to update the value at \p addr. + * @return Original value contained in \p addr. + */ +__device__ inline float unsafeAtomicMax(float* addr, float val) { + #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) { + 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) { + done = __atomic_compare_exchange_n(uaddr, &value, __float_as_uint(val), false, + __ATOMIC_RELAXED, __ATOMIC_RELAXED); + } + return __uint_as_float(value); + #endif +} + +/** + * @brief Unsafe floating point rmw atomic min. + * + * Performs a relaxed read-modify-write floating point atomic min with + * device memory scope. The original value at \p addr is returned and + * the value at \p addr is replaced by \p val if lesser. + * + * @note This operation is currently identical to that performed by + * atomicMin and is included for completeness. + * + * @param [in,out] addr Pointer to value to be updated + * @param [in] val Value used to update the value at \p addr. + * @return Original value contained in \p addr. + */ +__device__ inline float unsafeAtomicMin(float* addr, float val) { + #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) { + 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) { + done = __atomic_compare_exchange_n(uaddr, &value, __float_as_uint(val), false, + __ATOMIC_RELAXED, __ATOMIC_RELAXED); + } + return __uint_as_float(value); + #endif +} + +/** + * @brief Unsafe double precision rmw atomic add. + * + * Performs a relaxed read-modify-write double precision atomic add with + * device memory scope. Original value at \p addr is returned and + * the value of \p addr is updated to have the original value plus \p value + * + * @note This operation currently only performs different operations for + * the gfx90a target. Other devices continue to use safe atomics. + * + * It can be used to generate code that uses fast hardware floating point atomic + * operations which may handle rounding and subnormal values differently than + * non-atomic floating point operations. + * + * The operation is not always safe and can have undefined behavior unless + * following condition are met: + * + * - \p addr is at least 8 byte aligned + * - If \p addr is a global segment address, it is in a coarse grain allocation. + * Passing in global segment addresses in fine grain allocations will result in + * undefined behavior and are not supported. + * + * @param [in,out] addr Pointer to value to be updated. + * @param [in] value Value by \p addr is to be incremented. + * @return Original value contained in \p addr. + */ +__device__ inline double unsafeAtomicAdd(double* addr, double value) { +#if defined(__gfx90a__) && __has_builtin(__builtin_amdgcn_flat_atomic_fadd_f64) + return __builtin_amdgcn_flat_atomic_fadd_f64(addr, value); +#elif defined (__hip_atomic_fetch_add) + return __hip_atomic_fetch_add(addr, value, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); +#else + return __atomic_fetch_add(addr, value, __ATOMIC_RELAXED); +#endif +} + +/** + * @brief Unsafe double precision rmw atomic max. + * + * Performs a relaxed read-modify-write double precision atomic max with + * device memory scope. Original value at \p addr is returned and + * the value of \p addr is updated with \p val if greater. + * + * @note This operation currently only performs different operations for + * the gfx90a target. Other devices continue to use safe atomics. + * + * It can be used to generate code that uses fast hardware floating point atomic + * operations which may handle rounding and subnormal values differently than + * non-atomic floating point operations. + * + * The operation is not always safe and can have undefined behavior unless + * following condition are met: + * + * - \p addr is at least 8 byte aligned + * - If \p addr is a global segment address, it is in a coarse grain allocation. + * Passing in global segment addresses in fine grain allocations will result in + * undefined behavior and are not supported. + * + * @param [in,out] addr Pointer to value to be updated. + * @param [in] val Value used to updated the contents at \p addr + * @return Original value contained at \p addr. + */ +__device__ inline double unsafeAtomicMax(double* addr, double val) { +#if (defined(__gfx90a__) || defined(__gfx940__) || defined(__gfx941__) || defined(__gfx942__)) && \ + __has_builtin(__builtin_amdgcn_flat_atomic_fmax_f64) + return __builtin_amdgcn_flat_atomic_fmax_f64(addr, val); +#else + #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) { + 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) { + done = __atomic_compare_exchange_n(uaddr, &value, __double_as_longlong(val), false, + __ATOMIC_RELAXED, __ATOMIC_RELAXED); + } + return __longlong_as_double(value); + #endif +#endif +} + +/** + * @brief Unsafe double precision rmw atomic min. + * + * Performs a relaxed read-modify-write double precision atomic min with + * device memory scope. Original value at \p addr is returned and + * the value of \p addr is updated with \p val if lesser. + * + * @note This operation currently only performs different operations for + * the gfx90a target. Other devices continue to use safe atomics. + * + * It can be used to generate code that uses fast hardware floating point atomic + * operations which may handle rounding and subnormal values differently than + * non-atomic floating point operations. + * + * The operation is not always safe and can have undefined behavior unless + * following condition are met: + * + * - \p addr is at least 8 byte aligned + * - If \p addr is a global segment address, it is in a coarse grain allocation. + * Passing in global segment addresses in fine grain allocations will result in + * undefined behavior and are not supported. + * + * @param [in,out] addr Pointer to value to be updated. + * @param [in] val Value used to updated the contents at \p addr + * @return Original value contained at \p addr. + */ +__device__ inline double unsafeAtomicMin(double* addr, double val) { +#if (defined(__gfx90a__) || defined(__gfx940__) || defined(__gfx941__) || defined(__gfx942__)) && \ + __has_builtin(__builtin_amdgcn_flat_atomic_fmin_f64) + return __builtin_amdgcn_flat_atomic_fmin_f64(addr, val); +#else + #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) { + 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) { + done = __atomic_compare_exchange_n(uaddr, &value, __double_as_longlong(val), false, + __ATOMIC_RELAXED, __ATOMIC_RELAXED); + } + return __longlong_as_double(value); + #endif +#endif +} + +/** + * @brief Safe floating point rmw atomic add. + * + * Performs a relaxed read-modify-write floating point atomic add with + * device memory scope. Original value at \p addr is returned and + * the value of \p addr is updated to have the original value plus \p value + * + * @note This operation ensures that, on all targets, we produce safe atomics. + * This will be the case even when -munsafe-fp-atomics is passed into the compiler. + * + * @param [in,out] addr Pointer to value to be increment by \p value. + * @param [in] value Value by \p addr is to be incremented. + * @return Original value contained in \p addr. + */ +__device__ inline float safeAtomicAdd(float* addr, float value) { +#if defined(__gfx908__) || defined(__gfx941__) \ + || ((defined(__gfx90a__) || defined(__gfx940__) || defined(__gfx942__)) \ + && !__has_builtin(__hip_atomic_fetch_add)) + // On gfx908, we can generate unsafe FP32 atomic add that does not follow all + // IEEE rules when -munsafe-fp-atomics is passed. Do a CAS loop emulation instead. + // On gfx941, we can generate unsafe FP32 atomic add that may not always happen atomically, + // so we need to force a CAS loop emulation to ensure safety. + // On gfx90a, gfx940 and gfx942 if we do not have the __hip_atomic_fetch_add builtin, we + // need to force a CAS loop here. + float old_val; +#if __has_builtin(__hip_atomic_load) + old_val = __hip_atomic_load(addr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); +#else // !__has_builtin(__hip_atomic_load) + old_val = __uint_as_float(__atomic_load_n(reinterpret_cast(addr), __ATOMIC_RELAXED)); +#endif // __has_builtin(__hip_atomic_load) + float expected, temp; + do { + temp = expected = old_val; +#if __has_builtin(__hip_atomic_compare_exchange_strong) + __hip_atomic_compare_exchange_strong(addr, &expected, old_val + value, __ATOMIC_RELAXED, + __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); +#else // !__has_builtin(__hip_atomic_compare_exchange_strong) + __atomic_compare_exchange_n(addr, &expected, old_val + value, false, + __ATOMIC_RELAXED, __ATOMIC_RELAXED); +#endif // __has_builtin(__hip_atomic_compare_exchange_strong) + old_val = expected; + } while (__float_as_uint(temp) != __float_as_uint(old_val)); + return old_val; +#elif defined(__gfx90a__) + // On gfx90a, with the __hip_atomic_fetch_add builtin, relaxed system-scope + // atomics will produce safe CAS loops, but are otherwise not different than + // agent-scope atomics. This logic is only applicable for gfx90a, and should + // not be assumed on other architectures. + return __hip_atomic_fetch_add(addr, value, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); +#elif __has_builtin(__hip_atomic_fetch_add) + return __hip_atomic_fetch_add(addr, value, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); +#else + return __atomic_fetch_add(addr, value, __ATOMIC_RELAXED); +#endif +} + +/** + * @brief Safe floating point rmw atomic max. + * + * Performs a relaxed read-modify-write floating point atomic max with + * device memory scope. The original value at \p addr is returned and + * the value at \p addr is replaced by \p val if greater. + * + * @note This operation ensures that, on all targets, we produce safe atomics. + * This will be the case even when -munsafe-fp-atomics is passed into the compiler. + * + * @param [in,out] addr Pointer to value to be updated + * @param [in] val Value used to update the value at \p addr. + * @return Original value contained in \p addr. + */ +__device__ inline float safeAtomicMax(float* addr, float val) { + #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) { + 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) { + done = __atomic_compare_exchange_n(uaddr, &value, __float_as_uint(val), false, + __ATOMIC_RELAXED, __ATOMIC_RELAXED); + } + return __uint_as_float(value); + #endif +} + +/** + * @brief Safe floating point rmw atomic min. + * + * Performs a relaxed read-modify-write floating point atomic min with + * device memory scope. The original value at \p addr is returned and + * the value at \p addr is replaced by \p val if lesser. + * + * @note This operation ensures that, on all targets, we produce safe atomics. + * This will be the case even when -munsafe-fp-atomics is passed into the compiler. + * + * @param [in,out] addr Pointer to value to be updated + * @param [in] val Value used to update the value at \p addr. + * @return Original value contained in \p addr. + */ +__device__ inline float safeAtomicMin(float* addr, float val) { + #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) { + 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) { + done = __atomic_compare_exchange_n(uaddr, &value, __float_as_uint(val), false, + __ATOMIC_RELAXED, __ATOMIC_RELAXED); + } + return __uint_as_float(value); + #endif +} + +/** + * @brief Safe double precision rmw atomic add. + * + * Performs a relaxed read-modify-write double precision atomic add with + * device memory scope. Original value at \p addr is returned and + * the value of \p addr is updated to have the original value plus \p value + * + * @note This operation ensures that, on all targets, we produce safe atomics. + * This will be the case even when -munsafe-fp-atomics is passed into the compiler. + * + * @param [in,out] addr Pointer to value to be increment by \p value. + * @param [in] value Value by \p addr is to be incremented. + * @return Original value contained in \p addr. + */ +__device__ inline double safeAtomicAdd(double* addr, double value) { +#if defined(__gfx90a__) && __has_builtin(__hip_atomic_fetch_add) + // On gfx90a, with the __hip_atomic_fetch_add builtin, relaxed system-scope + // atomics will produce safe CAS loops, but are otherwise not different than + // agent-scope atomics. This logic is only applicable for gfx90a, and should + // not be assumed on other architectures. + return __hip_atomic_fetch_add(addr, value, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); +#elif defined(__gfx90a__) + // On gfx90a, if we do not have the __hip_atomic_fetch_add builtin, we need to + // force a CAS loop here. + double old_val; +#if __has_builtin(__hip_atomic_load) + old_val = __hip_atomic_load(addr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); +#else // !__has_builtin(__hip_atomic_load) + old_val = __longlong_as_double(__atomic_load_n(reinterpret_cast(addr), __ATOMIC_RELAXED)); +#endif // __has_builtin(__hip_atomic_load) + double expected, temp; + do { + temp = expected = old_val; +#if __has_builtin(__hip_atomic_compare_exchange_strong) + __hip_atomic_compare_exchange_strong(addr, &expected, old_val + value, __ATOMIC_RELAXED, + __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); +#else // !__has_builtin(__hip_atomic_compare_exchange_strong) + __atomic_compare_exchange_n(addr, &expected, old_val + value, false, + __ATOMIC_RELAXED, __ATOMIC_RELAXED); +#endif // __has_builtin(__hip_atomic_compare_exchange_strong) + old_val = expected; + } while (__double_as_longlong(temp) != __double_as_longlong(old_val)); + return old_val; +#else // !defined(__gfx90a__) +#if __has_builtin(__hip_atomic_fetch_add) + return __hip_atomic_fetch_add(addr, value, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); +#else // !__has_builtin(__hip_atomic_fetch_add) + return __atomic_fetch_add(addr, value, __ATOMIC_RELAXED); +#endif // __has_builtin(__hip_atomic_fetch_add) +#endif +} + +/** + * @brief Safe double precision rmw atomic max. + * + * Performs a relaxed read-modify-write double precision atomic max with + * device memory scope. Original value at \p addr is returned and + * the value of \p addr is updated with \p val if greater. + * + * @note This operation ensures that, on all targets, we produce safe atomics. + * This will be the case even when -munsafe-fp-atomics is passed into the compiler. + * + * @param [in,out] addr Pointer to value to be updated. + * @param [in] val Value used to updated the contents at \p addr + * @return Original value contained at \p addr. + */ +__device__ inline double safeAtomicMax(double* addr, double val) { + #if __has_builtin(__builtin_amdgcn_is_private) + if (__builtin_amdgcn_is_private( + (const __attribute__((address_space(0))) void*)addr)) { + double old = *addr; + *addr = __builtin_fmax(old, val); + return old; + } else { + #endif + #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) { + 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) { + done = __atomic_compare_exchange_n(uaddr, &value, __double_as_longlong(val), false, + __ATOMIC_RELAXED, __ATOMIC_RELAXED); + } + return __longlong_as_double(value); + #endif + #if __has_builtin(__builtin_amdgcn_is_private) + } + #endif +} + +/** + * @brief Safe double precision rmw atomic min. + * + * Performs a relaxed read-modify-write double precision atomic min with + * device memory scope. Original value at \p addr is returned and + * the value of \p addr is updated with \p val if lesser. + * + * @note This operation ensures that, on all targets, we produce safe atomics. + * This will be the case even when -munsafe-fp-atomics is passed into the compiler. + * + * @param [in,out] addr Pointer to value to be updated. + * @param [in] val Value used to updated the contents at \p addr + * @return Original value contained at \p addr. + */ +__device__ inline double safeAtomicMin(double* addr, double val) { + #if __has_builtin(__builtin_amdgcn_is_private) + if (__builtin_amdgcn_is_private( + (const __attribute__((address_space(0))) void*)addr)) { + double old = *addr; + *addr = __builtin_fmin(old, val); + return old; + } else { + #endif + #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) { + 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) { + done = __atomic_compare_exchange_n(uaddr, &value, __double_as_longlong(val), false, + __ATOMIC_RELAXED, __ATOMIC_RELAXED); + } + return __longlong_as_double(value); + #endif + #if __has_builtin(__builtin_amdgcn_is_private) + } + #endif +} + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_vector_types.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_vector_types.h new file mode 100644 index 0000000000000000000000000000000000000000..c4736e4743fb6ec11c3a63695bb7e94d5e89ba30 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_vector_types.h @@ -0,0 +1,2226 @@ +/* +Copyright (c) 2015 - 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 amd_detail/hip_vector_types.h + * @brief Defines the different newt vector types for HIP runtime. + */ + +#ifndef HIP_INCLUDE_HIP_AMD_DETAIL_HIP_VECTOR_TYPES_H +#define HIP_INCLUDE_HIP_AMD_DETAIL_HIP_VECTOR_TYPES_H + +#include "hip/amd_detail/host_defines.h" + +#if defined(__HIPCC_RTC__) + #define __HOST_DEVICE__ __device__ +#else + #define __HOST_DEVICE__ __host__ __device__ +#endif + +#if defined(__has_attribute) + #if __has_attribute(ext_vector_type) + #define __HIP_USE_NATIVE_VECTOR__ 1 + #define __NATIVE_VECTOR__(n, T) T __attribute__((ext_vector_type(n))) + #else + #define __NATIVE_VECTOR__(n, T) T[n] + #endif + +#if defined(__cplusplus) +#if !defined(__HIPCC_RTC__) + #include + #include + #include +#else +namespace std { +using ::size_t; + +template struct integral_constant { + static constexpr const _Tp value = __v; + typedef _Tp value_type; + typedef integral_constant type; + constexpr operator value_type() const { return value; } + constexpr value_type operator()() const { return value; } +}; +template constexpr const _Tp integral_constant<_Tp, __v>::value; + +typedef integral_constant true_type; +typedef integral_constant false_type; + +template using bool_constant = integral_constant; +typedef bool_constant true_type; +typedef bool_constant false_type; + +template struct enable_if {}; +template struct enable_if { typedef __T type; }; + +template struct true_or_false_type : public false_type {}; +template<> struct true_or_false_type : public true_type {}; + +template struct is_integral : public false_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; + +template struct is_arithmetic : public false_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; + +template struct is_floating_point : public false_type {}; +template<> struct is_floating_point : public true_type {}; +template<> struct is_floating_point : public true_type {}; +template<> struct is_floating_point : public true_type {}; + +template struct is_same : public false_type {}; +template struct is_same<__T, __T> : public true_type {}; + +template::value> + struct is_signed : public false_type {}; +template + struct is_signed<_Tp, true> : public true_or_false_type<_Tp(-1) < _Tp(0)> {}; + +template struct is_convertible + : public true_or_false_type<__is_convertible_to(_T1, _T2)> {}; + +template struct char_traits; +template> class basic_istream; +template> class basic_ostream; +typedef basic_istream istream; +typedef basic_ostream ostream; + +template struct is_scalar : public integral_constant {}; +} // Namespace std. +#endif // defined(__HIPCC_RTC__) + + namespace hip_impl { + inline + constexpr + unsigned int next_pot(unsigned int x) { + // Precondition: x > 1. + return 1u << (32u - __builtin_clz(x - 1u)); + } + } // Namespace hip_impl. + + template struct HIP_vector_base; + + template + struct HIP_vector_base { + using Native_vec_ = __NATIVE_VECTOR__(1, T); + + union { + Native_vec_ data; + struct { + T x; + }; + }; + + using value_type = T; + + __HOST_DEVICE__ + HIP_vector_base() = default; + __HOST_DEVICE__ + explicit + constexpr + HIP_vector_base(T x_) noexcept : data{x_} {} + __HOST_DEVICE__ + constexpr + HIP_vector_base(const HIP_vector_base&) = default; + __HOST_DEVICE__ + constexpr + HIP_vector_base(HIP_vector_base&&) = default; + __HOST_DEVICE__ + ~HIP_vector_base() = default; + __HOST_DEVICE__ + HIP_vector_base& operator=(const HIP_vector_base&) = default; + }; + + template + struct HIP_vector_base { + using Native_vec_ = __NATIVE_VECTOR__(2, T); + + union + #if !__has_attribute(ext_vector_type) + alignas(hip_impl::next_pot(2 * sizeof(T))) + #endif + { + Native_vec_ data; + struct { + T x; + T y; + }; + }; + + using value_type = T; + + __HOST_DEVICE__ + HIP_vector_base() = default; + __HOST_DEVICE__ + explicit + constexpr + HIP_vector_base(T x_) noexcept : data{x_, x_} {} + __HOST_DEVICE__ + constexpr + HIP_vector_base(T x_, T y_) noexcept : data{x_, y_} {} + __HOST_DEVICE__ + constexpr + HIP_vector_base(const HIP_vector_base&) = default; + __HOST_DEVICE__ + constexpr + HIP_vector_base(HIP_vector_base&&) = default; + __HOST_DEVICE__ + ~HIP_vector_base() = default; + __HOST_DEVICE__ + HIP_vector_base& operator=(const HIP_vector_base&) = default; + }; + + template + struct HIP_vector_base { + struct Native_vec_ { + T d[3]; + + __HOST_DEVICE__ + Native_vec_() = default; + + __HOST_DEVICE__ + explicit + constexpr + Native_vec_(T x_) noexcept : d{x_, x_, x_} {} + __HOST_DEVICE__ + constexpr + Native_vec_(T x_, T y_, T z_) noexcept : d{x_, y_, z_} {} + __HOST_DEVICE__ + constexpr + Native_vec_(const Native_vec_&) = default; + __HOST_DEVICE__ + constexpr + Native_vec_(Native_vec_&&) = default; + __HOST_DEVICE__ + ~Native_vec_() = default; + + __HOST_DEVICE__ + Native_vec_& operator=(const Native_vec_&) = default; + __HOST_DEVICE__ + Native_vec_& operator=(Native_vec_&&) = default; + + __HOST_DEVICE__ + T& operator[](unsigned int idx) noexcept { return d[idx]; } + __HOST_DEVICE__ + T operator[](unsigned int idx) const noexcept { return d[idx]; } + + __HOST_DEVICE__ + Native_vec_& operator+=(const Native_vec_& x_) noexcept + { + for (auto i = 0u; i != 3u; ++i) d[i] += x_.d[i]; + return *this; + } + __HOST_DEVICE__ + Native_vec_& operator-=(const Native_vec_& x_) noexcept + { + for (auto i = 0u; i != 3u; ++i) d[i] -= x_.d[i]; + return *this; + } + + __HOST_DEVICE__ + Native_vec_& operator*=(const Native_vec_& x_) noexcept + { + for (auto i = 0u; i != 3u; ++i) d[i] *= x_.d[i]; + return *this; + } + __HOST_DEVICE__ + Native_vec_& operator/=(const Native_vec_& x_) noexcept + { + for (auto i = 0u; i != 3u; ++i) d[i] /= x_.d[i]; + return *this; + } + + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + Native_vec_ operator-() const noexcept + { + auto r{*this}; + for (auto&& x : r.d) x = -x; + return r; + } + + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + Native_vec_ operator~() const noexcept + { + auto r{*this}; + for (auto&& x : r.d) x = ~x; + return r; + } + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + Native_vec_& operator%=(const Native_vec_& x_) noexcept + { + for (auto i = 0u; i != 3u; ++i) d[i] %= x_.d[i]; + return *this; + } + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + Native_vec_& operator^=(const Native_vec_& x_) noexcept + { + for (auto i = 0u; i != 3u; ++i) d[i] ^= x_.d[i]; + return *this; + } + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + Native_vec_& operator|=(const Native_vec_& x_) noexcept + { + for (auto i = 0u; i != 3u; ++i) d[i] |= x_.d[i]; + return *this; + } + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + Native_vec_& operator&=(const Native_vec_& x_) noexcept + { + for (auto i = 0u; i != 3u; ++i) d[i] &= x_.d[i]; + return *this; + } + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + Native_vec_& operator>>=(const Native_vec_& x_) noexcept + { + for (auto i = 0u; i != 3u; ++i) d[i] >>= x_.d[i]; + return *this; + } + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + Native_vec_& operator<<=(const Native_vec_& x_) noexcept + { + for (auto i = 0u; i != 3u; ++i) d[i] <<= x_.d[i]; + return *this; + } +#if defined (__INTEL_COMPILER) + typedef struct { + int values[4]; + } _Vec3_cmp; + using Vec3_cmp = _Vec3_cmp; +#else + using Vec3_cmp = int __attribute__((vector_size(4 * sizeof(int)))); +#endif //INTEL + __HOST_DEVICE__ + Vec3_cmp operator==(const Native_vec_& x_) const noexcept + { + return Vec3_cmp{d[0] == x_.d[0], d[1] == x_.d[1], d[2] == x_.d[2]}; + } + }; + + union { + Native_vec_ data; + struct { + T x; + T y; + T z; + }; + }; + + using value_type = T; + + __HOST_DEVICE__ + HIP_vector_base() = default; + __HOST_DEVICE__ + explicit + constexpr + HIP_vector_base(T x_) noexcept : data{x_, x_, x_} {} + __HOST_DEVICE__ + constexpr + HIP_vector_base(T x_, T y_, T z_) noexcept : data{x_, y_, z_} {} + __HOST_DEVICE__ + constexpr + HIP_vector_base(const HIP_vector_base&) = default; + __HOST_DEVICE__ + constexpr + HIP_vector_base(HIP_vector_base&&) = default; + __HOST_DEVICE__ + ~HIP_vector_base() = default; + + __HOST_DEVICE__ + HIP_vector_base& operator=(const HIP_vector_base&) = default; + __HOST_DEVICE__ + HIP_vector_base& operator=(HIP_vector_base&&) = default; + }; + + template + struct HIP_vector_base { + using Native_vec_ = __NATIVE_VECTOR__(4, T); + + union + #if !__has_attribute(ext_vector_type) + alignas(hip_impl::next_pot(4 * sizeof(T))) + #endif + { + Native_vec_ data; + struct { + T x; + T y; + T z; + T w; + }; + }; + + using value_type = T; + + __HOST_DEVICE__ + HIP_vector_base() = default; + __HOST_DEVICE__ + explicit + constexpr + HIP_vector_base(T x_) noexcept : data{x_, x_, x_, x_} {} + __HOST_DEVICE__ + constexpr + HIP_vector_base(T x_, T y_, T z_, T w_) noexcept : data{x_, y_, z_, w_} {} + __HOST_DEVICE__ + constexpr + HIP_vector_base(const HIP_vector_base&) = default; + __HOST_DEVICE__ + constexpr + HIP_vector_base(HIP_vector_base&&) = default; + __HOST_DEVICE__ + ~HIP_vector_base() = default; + __HOST_DEVICE__ + HIP_vector_base& operator=(const HIP_vector_base&) = default; + }; + + template + struct HIP_vector_type : public HIP_vector_base { + using HIP_vector_base::data; + using typename HIP_vector_base::Native_vec_; + + __HOST_DEVICE__ + HIP_vector_type() = default; + template< + typename U, + typename std::enable_if< + std::is_convertible::value>::type* = nullptr> + __HOST_DEVICE__ + explicit + constexpr + HIP_vector_type(U x_) noexcept + : HIP_vector_base{static_cast(x_)} + {} + template< // TODO: constrain based on type as well. + typename... Us, + typename std::enable_if< + (rank > 1) && sizeof...(Us) == rank>::type* = nullptr> + __HOST_DEVICE__ + constexpr + HIP_vector_type(Us... xs) noexcept + : HIP_vector_base{static_cast(xs)...} + {} + __HOST_DEVICE__ + constexpr + HIP_vector_type(const HIP_vector_type&) = default; + __HOST_DEVICE__ + constexpr + HIP_vector_type(HIP_vector_type&&) = default; + __HOST_DEVICE__ + ~HIP_vector_type() = default; + + __HOST_DEVICE__ + HIP_vector_type& operator=(const HIP_vector_type&) = default; + __HOST_DEVICE__ + HIP_vector_type& operator=(HIP_vector_type&&) = default; + + // Operators + __HOST_DEVICE__ + HIP_vector_type& operator++() noexcept + { + return *this += HIP_vector_type{1}; + } + __HOST_DEVICE__ + HIP_vector_type operator++(int) noexcept + { + auto tmp(*this); + ++*this; + return tmp; + } + + __HOST_DEVICE__ + HIP_vector_type& operator--() noexcept + { + return *this -= HIP_vector_type{1}; + } + __HOST_DEVICE__ + HIP_vector_type operator--(int) noexcept + { + auto tmp(*this); + --*this; + return tmp; + } + + __HOST_DEVICE__ + HIP_vector_type& operator+=(const HIP_vector_type& x) noexcept + { +#if __HIP_USE_NATIVE_VECTOR__ + data += x.data; +#else + for (auto i = 0u; i != rank; ++i) data[i] += x.data[i]; +#endif + return *this; + } + template< + typename U, + typename std::enable_if< + std::is_convertible{}>::type* = nullptr> + __HOST_DEVICE__ + HIP_vector_type& operator+=(U x) noexcept + { + return *this += HIP_vector_type{x}; + } + + __HOST_DEVICE__ + HIP_vector_type& operator-=(const HIP_vector_type& x) noexcept + { +#if __HIP_USE_NATIVE_VECTOR__ + data -= x.data; +#else + for (auto i = 0u; i != rank; ++i) data[i] -= x.data[i]; +#endif + return *this; + } + template< + typename U, + typename std::enable_if< + std::is_convertible{}>::type* = nullptr> + __HOST_DEVICE__ + HIP_vector_type& operator-=(U x) noexcept + { + return *this -= HIP_vector_type{x}; + } + + __HOST_DEVICE__ + HIP_vector_type& operator*=(const HIP_vector_type& x) noexcept + { +#if __HIP_USE_NATIVE_VECTOR__ + data *= x.data; +#else + for (auto i = 0u; i != rank; ++i) data[i] *= x.data[i]; +#endif + return *this; + } + + friend __HOST_DEVICE__ inline constexpr HIP_vector_type operator*( + HIP_vector_type x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{ x } *= y; + } + + template< + typename U, + typename std::enable_if< + std::is_convertible{}>::type* = nullptr> + __HOST_DEVICE__ + HIP_vector_type& operator*=(U x) noexcept + { + return *this *= HIP_vector_type{x}; + } + + friend __HOST_DEVICE__ inline constexpr HIP_vector_type operator/( + HIP_vector_type x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{ x } /= y; + } + + __HOST_DEVICE__ + HIP_vector_type& operator/=(const HIP_vector_type& x) noexcept + { +#if __HIP_USE_NATIVE_VECTOR__ + data /= x.data; +#else + for (auto i = 0u; i != rank; ++i) data[i] /= x.data[i]; +#endif + return *this; + } + template< + typename U, + typename std::enable_if< + std::is_convertible{}>::type* = nullptr> + __HOST_DEVICE__ + HIP_vector_type& operator/=(U x) noexcept + { + return *this /= HIP_vector_type{x}; + } + + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + HIP_vector_type operator-() const noexcept + { + auto tmp(*this); +#if __HIP_USE_NATIVE_VECTOR__ + tmp.data = -tmp.data; +#else + for (auto i = 0u; i != rank; ++i) tmp.data[i] = -tmp.data[i]; +#endif + return tmp; + } + + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + HIP_vector_type operator~() const noexcept + { + HIP_vector_type r{*this}; +#if __HIP_USE_NATIVE_VECTOR__ + r.data = ~r.data; +#else + for (auto i = 0u; i != rank; ++i) r.data[i] = ~r.data[i]; +#endif + return r; + } + + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + HIP_vector_type& operator%=(const HIP_vector_type& x) noexcept + { +#if __HIP_USE_NATIVE_VECTOR__ + data %= x.data; +#else + for (auto i = 0u; i != rank; ++i) data[i] %= x.data[i]; +#endif + return *this; + } + + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + HIP_vector_type& operator^=(const HIP_vector_type& x) noexcept + { +#if __HIP_USE_NATIVE_VECTOR__ + data ^= x.data; +#else + for (auto i = 0u; i != rank; ++i) data[i] ^= x.data[i]; +#endif + return *this; + } + + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + HIP_vector_type& operator|=(const HIP_vector_type& x) noexcept + { +#if __HIP_USE_NATIVE_VECTOR__ + data |= x.data; +#else + for (auto i = 0u; i != rank; ++i) data[i] |= x.data[i]; +#endif + return *this; + } + + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + HIP_vector_type& operator&=(const HIP_vector_type& x) noexcept + { +#if __HIP_USE_NATIVE_VECTOR__ + data &= x.data; +#else + for (auto i = 0u; i != rank; ++i) data[i] &= x.data[i]; +#endif + return *this; + } + + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + HIP_vector_type& operator>>=(const HIP_vector_type& x) noexcept + { +#if __HIP_USE_NATIVE_VECTOR__ + data >>= x.data; +#else + for (auto i = 0u; i != rank; ++i) data[i] >>= x.data[i]; +#endif + return *this; + } + + template< + typename U = T, + typename std::enable_if{}>::type* = nullptr> + __HOST_DEVICE__ + HIP_vector_type& operator<<=(const HIP_vector_type& x) noexcept + { +#if __HIP_USE_NATIVE_VECTOR__ + data <<= x.data; +#else + for (auto i = 0u; i != rank; ++i) data[i] <<= x.data[i]; +#endif + return *this; + } + }; + + template + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator+( + const HIP_vector_type& x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} += y; + } + template + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator+( + const HIP_vector_type& x, U y) noexcept + { + return HIP_vector_type{x} += HIP_vector_type{y}; + } + template + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator+( + U x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} += y; + } + + template + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator-( + const HIP_vector_type& x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} -= y; + } + template + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator-( + const HIP_vector_type& x, U y) noexcept + { + return HIP_vector_type{x} -= HIP_vector_type{y}; + } + template + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator-( + U x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} -= y; + } + + template + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator*( + const HIP_vector_type& x, U y) noexcept + { + return HIP_vector_type{x} *= HIP_vector_type{y}; + } + template + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator*( + U x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} *= y; + } + + template + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator/( + const HIP_vector_type& x, U y) noexcept + { + return HIP_vector_type{x} /= HIP_vector_type{y}; + } + template + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator/( + U x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} /= y; + } + + template + __HOST_DEVICE__ + inline + constexpr + bool _hip_compare(const V& x, const V& y, int n) noexcept + { + return + (n == -1) ? true : ((x[n] != y[n]) ? false : _hip_compare(x, y, n - 1)); + } + + template + __HOST_DEVICE__ + inline + constexpr + bool operator==( + const HIP_vector_type& x, const HIP_vector_type& y) noexcept + { + return _hip_compare(x.data, y.data, n - 1); + } + template + __HOST_DEVICE__ + inline + constexpr + bool operator==(const HIP_vector_type& x, U y) noexcept + { + return x == HIP_vector_type{y}; + } + template + __HOST_DEVICE__ + inline + constexpr + bool operator==(U x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} == y; + } + + template + __HOST_DEVICE__ + inline + constexpr + bool operator!=( + const HIP_vector_type& x, const HIP_vector_type& y) noexcept + { + return !(x == y); + } + template + __HOST_DEVICE__ + inline + constexpr + bool operator!=(const HIP_vector_type& x, U y) noexcept + { + return !(x == y); + } + template + __HOST_DEVICE__ + inline + constexpr + bool operator!=(U x, const HIP_vector_type& y) noexcept + { + return !(x == y); + } + + template< + typename T, + unsigned int n, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator%( + const HIP_vector_type& x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} %= y; + } + template< + typename T, + unsigned int n, + typename U, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator%( + const HIP_vector_type& x, U y) noexcept + { + return HIP_vector_type{x} %= HIP_vector_type{y}; + } + template< + typename T, + unsigned int n, + typename U, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator%( + U x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} %= y; + } + + template< + typename T, + unsigned int n, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator^( + const HIP_vector_type& x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} ^= y; + } + template< + typename T, + unsigned int n, + typename U, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator^( + const HIP_vector_type& x, U y) noexcept + { + return HIP_vector_type{x} ^= HIP_vector_type{y}; + } + template< + typename T, + unsigned int n, + typename U, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator^( + U x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} ^= y; + } + + template< + typename T, + unsigned int n, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator|( + const HIP_vector_type& x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} |= y; + } + template< + typename T, + unsigned int n, + typename U, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator|( + const HIP_vector_type& x, U y) noexcept + { + return HIP_vector_type{x} |= HIP_vector_type{y}; + } + template< + typename T, + unsigned int n, + typename U, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator|( + U x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} |= y; + } + + template< + typename T, + unsigned int n, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator&( + const HIP_vector_type& x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} &= y; + } + template< + typename T, + unsigned int n, + typename U, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator&( + const HIP_vector_type& x, U y) noexcept + { + return HIP_vector_type{x} &= HIP_vector_type{y}; + } + template< + typename T, + unsigned int n, + typename U, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator&( + U x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} &= y; + } + + template< + typename T, + unsigned int n, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator>>( + const HIP_vector_type& x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} >>= y; + } + template< + typename T, + unsigned int n, + typename U, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator>>( + const HIP_vector_type& x, U y) noexcept + { + return HIP_vector_type{x} >>= HIP_vector_type{y}; + } + template< + typename T, + unsigned int n, + typename U, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator>>( + U x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} >>= y; + } + + template< + typename T, + unsigned int n, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator<<( + const HIP_vector_type& x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} <<= y; + } + template< + typename T, + unsigned int n, + typename U, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator<<( + const HIP_vector_type& x, U y) noexcept + { + return HIP_vector_type{x} <<= HIP_vector_type{y}; + } + template< + typename T, + unsigned int n, + typename U, + typename std::enable_if::value>::type, + typename std::enable_if{}>* = nullptr> + __HOST_DEVICE__ + inline + constexpr + HIP_vector_type operator<<( + U x, const HIP_vector_type& y) noexcept + { + return HIP_vector_type{x} <<= y; + } + + /* + * Map HIP_vector_type to HIP_vector_type + */ + template + __forceinline__ __HOST_DEVICE__ typename std::enable_if<(rankT == 1 && rankU >= 1), + const HIP_vector_type>::type + __hipMapVector(const HIP_vector_type& u) { + return HIP_vector_type(static_cast(u.x)); + }; + + template + __forceinline__ __HOST_DEVICE__ typename std::enable_if<(rankT == 2 && rankU == 1), + const HIP_vector_type>::type + __hipMapVector(const HIP_vector_type& u) { + return HIP_vector_type (static_cast(u.x), static_cast(0)); + }; + + template + __forceinline__ __HOST_DEVICE__ typename std::enable_if<(rankT == 2 && rankU >= 2), + const HIP_vector_type>::type + __hipMapVector(const HIP_vector_type& u) { + return HIP_vector_type (static_cast(u.x), static_cast(u.y)); + }; + + template + __forceinline__ __HOST_DEVICE__ typename std::enable_if<(rankT == 4 && rankU == 1), + const HIP_vector_type>::type + __hipMapVector(const HIP_vector_type& u) { + return HIP_vector_type (static_cast(u.x), static_cast(0), + static_cast(0), static_cast(0)); + }; + + template + __forceinline__ __HOST_DEVICE__ typename std::enable_if<(rankT == 4 && rankU == 2), + const HIP_vector_type>::type + __hipMapVector(const HIP_vector_type& u) { + return HIP_vector_type(static_cast(u.x), static_cast(u.y), + static_cast(0), static_cast(0)); + }; + + template + __forceinline__ __HOST_DEVICE__ typename std::enable_if<(rankT == 4 && rankU == 4), + const HIP_vector_type>::type + __hipMapVector(const HIP_vector_type& u) { + return HIP_vector_type (static_cast(u.x), static_cast(u.y), + static_cast(u.z), static_cast(u.w)); + }; + + #define __MAKE_VECTOR_TYPE__(CUDA_name, T) \ + using CUDA_name##1 = HIP_vector_type;\ + using CUDA_name##2 = HIP_vector_type;\ + using CUDA_name##3 = HIP_vector_type;\ + using CUDA_name##4 = HIP_vector_type; +#else + #define __MAKE_VECTOR_TYPE__(CUDA_name, T) \ + typedef struct {\ + T x;\ + } CUDA_name##1;\ + typedef struct {\ + T x;\ + T y;\ + } CUDA_name##2;\ + typedef struct {\ + T x;\ + T y;\ + T z;\ + } CUDA_name##3;\ + typedef struct {\ + T x;\ + T y;\ + T z;\ + T w;\ + } CUDA_name##4; +#endif + +__MAKE_VECTOR_TYPE__(uchar, unsigned char); +__MAKE_VECTOR_TYPE__(char, char); +__MAKE_VECTOR_TYPE__(ushort, unsigned short); +__MAKE_VECTOR_TYPE__(short, short); +__MAKE_VECTOR_TYPE__(uint, unsigned int); +__MAKE_VECTOR_TYPE__(int, int); +__MAKE_VECTOR_TYPE__(ulong, unsigned long); +__MAKE_VECTOR_TYPE__(long, long); +__MAKE_VECTOR_TYPE__(ulonglong, unsigned long long); +__MAKE_VECTOR_TYPE__(longlong, long long); +__MAKE_VECTOR_TYPE__(float, float); +__MAKE_VECTOR_TYPE__(double, double); + +#else // !defined(__has_attribute) + +#if defined(_MSC_VER) +#include +#include +#include +#include + +/* +this is for compatibility with CUDA as CUDA allows accessing vector components +in C++ program with MSVC +*/ +typedef union { + struct { + char x; + }; + char data; +} char1; +typedef union { + struct { + char x; + char y; + }; + char data[2]; +} char2; +typedef union { + struct { + char x; + char y; + char z; + char w; + }; + char data[4]; +} char4; +typedef union { + struct { + char x; + char y; + char z; + }; + char data[3]; +} char3; +typedef union { + __m64 data; +} char8; +typedef union { + __m128i data; +} char16; + +typedef union { + struct { + unsigned char x; + }; + unsigned char data; +} uchar1; +typedef union { + struct { + unsigned char x; + unsigned char y; + }; + unsigned char data[2]; +} uchar2; +typedef union { + struct { + unsigned char x; + unsigned char y; + unsigned char z; + unsigned char w; + }; + unsigned char data[4]; +} uchar4; +typedef union { + struct { + unsigned char x; + unsigned char y; + unsigned char z; + }; + unsigned char data[3]; +} uchar3; +typedef union { + __m64 data; +} uchar8; +typedef union { + __m128i data; +} uchar16; + +typedef union { + struct { + short x; + }; + short data; +} short1; +typedef union { + struct { + short x; + short y; + }; + short data[2]; +} short2; +typedef union { + struct { + short x; + short y; + short z; + short w; + }; + __m64 data; +} short4; +typedef union { + struct { + short x; + short y; + short z; + }; + short data[3]; +} short3; +typedef union { + __m128i data; +} short8; +typedef union { + __m128i data[2]; +} short16; + +typedef union { + struct { + unsigned short x; + }; + unsigned short data; +} ushort1; +typedef union { + struct { + unsigned short x; + unsigned short y; + }; + unsigned short data[2]; +} ushort2; +typedef union { + struct { + unsigned short x; + unsigned short y; + unsigned short z; + unsigned short w; + }; + __m64 data; +} ushort4; +typedef union { + struct { + unsigned short x; + unsigned short y; + unsigned short z; + }; + unsigned short data[3]; +} ushort3; +typedef union { + __m128i data; +} ushort8; +typedef union { + __m128i data[2]; +} ushort16; + +typedef union { + struct { + int x; + }; + int data; +} int1; +typedef union { + struct { + int x; + int y; + }; + __m64 data; +} int2; +typedef union { + struct { + int x; + int y; + int z; + int w; + }; + __m128i data; +} int4; +typedef union { + struct { + int x; + int y; + int z; + }; + int data[3]; +} int3; +typedef union { + __m128i data[2]; +} int8; +typedef union { + __m128i data[4]; +} int16; + +typedef union { + struct { + unsigned int x; + }; + unsigned int data; +} uint1; +typedef union { + struct { + unsigned int x; + unsigned int y; + }; + __m64 data; +} uint2; +typedef union { + struct { + unsigned int x; + unsigned int y; + unsigned int z; + unsigned int w; + }; + __m128i data; +} uint4; +typedef union { + struct { + unsigned int x; + unsigned int y; + unsigned int z; + }; + unsigned int data[3]; +} uint3; +typedef union { + __m128i data[2]; +} uint8; +typedef union { + __m128i data[4]; +} uint16; + +typedef union { + struct { + int x; + }; + int data; +} long1; +typedef union { + struct { + int x; + int y; + }; + __m64 data; +} long2; +typedef union { + struct { + int x; + int y; + int z; + int w; + }; + __m128i data; +} long4; +typedef union { + struct { + int x; + int y; + int z; + }; + int data[3]; +} long3; +typedef union { + __m128i data[2]; +} long8; +typedef union { + __m128i data[4]; +} long16; + +typedef union { + struct { + unsigned int x; + }; + unsigned int data; +} ulong1; +typedef union { + struct { + unsigned int x; + unsigned int y; + }; + __m64 data; +} ulong2; +typedef union { + struct { + unsigned int x; + unsigned int y; + unsigned int z; + unsigned int w; + }; + __m128i data; +} ulong4; +typedef union { + struct { + unsigned int x; + unsigned int y; + unsigned int z; + }; + unsigned int data[3]; +} ulong3; +typedef union { + __m128i data[2]; +} ulong8; +typedef union { + __m128i data[4]; +} ulong16; + +typedef union { + struct { + long long x; + }; + __m64 data; +} longlong1; +typedef union { + struct { + long long x; + long long y; + }; + __m128i data; +} longlong2; +typedef union { + struct { + long long x; + long long y; + long long z; + long long w; + }; + __m128i data[2]; +} longlong4; +typedef union { + struct { + long long x; + long long y; + long long z; + }; + __m64 data[3]; +} longlong3; +typedef union { + __m128i data[4]; +} longlong8; +typedef union { + __m128i data[8]; +} longlong16; + +typedef union { + struct { + __m64 x; + }; + __m64 data; +} ulonglong1; +typedef union { + struct { + __m64 x; + __m64 y; + }; + __m128i data; +} ulonglong2; +typedef union { + struct { + __m64 x; + __m64 y; + __m64 z; + __m64 w; + }; + __m128i data[2]; +} ulonglong4; +typedef union { + struct { + __m64 x; + __m64 y; + __m64 z; + }; + __m64 data[3]; +} ulonglong3; +typedef union { + __m128i data[4]; +} ulonglong8; +typedef union { + __m128i data[8]; +} ulonglong16; + +typedef union { + struct { + float x; + }; + float data; +} float1; +typedef union { + struct { + float x; + float y; + }; + __m64 data; +} float2; +typedef union { + struct { + float x; + float y; + float z; + float w; + }; + __m128 data; +} float4; +typedef union { + struct { + float x; + float y; + float z; + }; + float data[3]; +} float3; +typedef union { + __m256 data; +} float8; +typedef union { + __m256 data[2]; +} float16; + +typedef union { + struct { + double x; + }; + double data; +} double1; +typedef union { + struct { + double x; + double y; + }; + __m128d data; +} double2; +typedef union { + struct { + double x; + double y; + double z; + double w; + }; + __m256d data; +} double4; +typedef union { + struct { + double x; + double y; + double z; + }; + double data[3]; +} double3; +typedef union { + __m256d data[2]; +} double8; +typedef union { + __m256d data[4]; +} double16; + +#else // !defined(_MSC_VER) + +/* +this is for compatibility with CUDA as CUDA allows accessing vector components +in C++ program with MSVC +*/ +typedef union { + struct { + char x; + }; + char data; +} char1; +typedef union { + struct { + char x; + char y; + }; + char data[2]; +} char2; +typedef union { + struct { + char x; + char y; + char z; + char w; + }; + char data[4]; +} char4; +typedef union { + char data[8]; +} char8; +typedef union { + char data[16]; +} char16; +typedef union { + struct { + char x; + char y; + char z; + }; + char data[3]; +} char3; + +typedef union { + struct { + unsigned char x; + }; + unsigned char data; +} uchar1; +typedef union { + struct { + unsigned char x; + unsigned char y; + }; + unsigned char data[2]; +} uchar2; +typedef union { + struct { + unsigned char x; + unsigned char y; + unsigned char z; + unsigned char w; + }; + unsigned char data[4]; +} uchar4; +typedef union { + unsigned char data[8]; +} uchar8; +typedef union { + unsigned char data[16]; +} uchar16; +typedef union { + struct { + unsigned char x; + unsigned char y; + unsigned char z; + }; + unsigned char data[3]; +} uchar3; + +typedef union { + struct { + short x; + }; + short data; +} short1; +typedef union { + struct { + short x; + short y; + }; + short data[2]; +} short2; +typedef union { + struct { + short x; + short y; + short z; + short w; + }; + short data[4]; +} short4; +typedef union { + short data[8]; +} short8; +typedef union { + short data[16]; +} short16; +typedef union { + struct { + short x; + short y; + short z; + }; + short data[3]; +} short3; + +typedef union { + struct { + unsigned short x; + }; + unsigned short data; +} ushort1; +typedef union { + struct { + unsigned short x; + unsigned short y; + }; + unsigned short data[2]; +} ushort2; +typedef union { + struct { + unsigned short x; + unsigned short y; + unsigned short z; + unsigned short w; + }; + unsigned short data[4]; +} ushort4; +typedef union { + unsigned short data[8]; +} ushort8; +typedef union { + unsigned short data[16]; +} ushort16; +typedef union { + struct { + unsigned short x; + unsigned short y; + unsigned short z; + }; + unsigned short data[3]; +} ushort3; + +typedef union { + struct { + int x; + }; + int data; +} int1; +typedef union { + struct { + int x; + int y; + }; + int data[2]; +} int2; +typedef union { + struct { + int x; + int y; + int z; + int w; + }; + int data[4]; +} int4; +typedef union { + int data[8]; +} int8; +typedef union { + int data[16]; +} int16; +typedef union { + struct { + int x; + int y; + int z; + }; + int data[3]; +} int3; + +typedef union { + struct { + unsigned int x; + }; + unsigned int data; +} uint1; +typedef union { + struct { + unsigned int x; + unsigned int y; + }; + unsigned int data[2]; +} uint2; +typedef union { + struct { + unsigned int x; + unsigned int y; + unsigned int z; + unsigned int w; + }; + unsigned int data[4]; +} uint4; +typedef union { + unsigned int data[8]; +} uint8; +typedef union { + unsigned int data[16]; +} uint16; +typedef union { + struct { + unsigned int x; + unsigned int y; + unsigned int z; + }; + unsigned int data[3]; +} uint3; + +typedef union { + struct { + long x; + }; + long data; +} long1; +typedef union { + struct { + long x; + long y; + }; + long data[2]; +} long2; +typedef union { + struct { + long x; + long y; + long z; + long w; + }; + long data[4]; +} long4; +typedef union { + long data[8]; +} long8; +typedef union { + long data[16]; +} long16; +typedef union { + struct { + long x; + long y; + long z; + }; + long data[3]; +} long3; + +typedef union { + struct { + unsigned long x; + }; + unsigned long data; +} ulong1; +typedef union { + struct { + unsigned long x; + unsigned long y; + }; + unsigned long data[2]; +} ulong2; +typedef union { + struct { + unsigned long x; + unsigned long y; + unsigned long z; + unsigned long w; + }; + unsigned long data[4]; +} ulong4; +typedef union { + unsigned long data[8]; +} ulong8; +typedef union { + unsigned long data[16]; +} ulong16; +typedef union { + struct { + unsigned long x; + unsigned long y; + unsigned long z; + }; + unsigned long data[3]; +} ulong3; + +typedef union { + struct { + long long x; + }; + long long data; +} longlong1; +typedef union { + struct { + long long x; + long long y; + }; + long long data[2]; +} longlong2; +typedef union { + struct { + long long x; + long long y; + long long z; + long long w; + }; + long long data[4]; +} longlong4; +typedef union { + long long data[8]; +} longlong8; +typedef union { + long long data[16]; +} longlong16; +typedef union { + struct { + long long x; + long long y; + long long z; + }; + long long data[3]; +} longlong3; + +typedef union { + struct { + unsigned long long x; + }; + unsigned long long data; +} ulonglong1; +typedef union { + struct { + unsigned long long x; + unsigned long long y; + }; + unsigned long long data[2]; +} ulonglong2; +typedef union { + struct { + unsigned long long x; + unsigned long long y; + unsigned long long z; + unsigned long long w; + }; + unsigned long long data[4]; +} ulonglong4; +typedef union { + unsigned long long data[8]; +} ulonglong8; +typedef union { + unsigned long long data[16]; +} ulonglong16; +typedef union { + struct { + unsigned long long x; + unsigned long long y; + unsigned long long z; + }; + unsigned long long data[3]; +} ulonglong3; + +typedef union { + struct { + float x; + }; + float data; +} float1; +typedef union { + struct { + float x; + float y; + }; + float data[2]; +} float2; +typedef union { + struct { + float x; + float y; + float z; + float w; + }; + float data[4]; +} float4; +typedef union { + float data[8]; +} float8; +typedef union { + float data[16]; +} float16; +typedef union { + struct { + float x; + float y; + float z; + }; + float data[3]; +} float3; + +typedef union { + struct { + double x; + }; + double data; +} double1; +typedef union { + struct { + double x; + double y; + }; + double data[2]; +} double2; +typedef union { + struct { + double x; + double y; + double z; + double w; + }; + double data[4]; +} double4; +typedef union { + double data[8]; +} double8; +typedef union { + double data[16]; +} double16; +typedef union { + struct { + double x; + double y; + double z; + }; + double data[3]; +} double3; + +#endif // defined(_MSC_VER) +#endif // defined(__has_attribute) + +#ifdef __cplusplus +#define DECLOP_MAKE_ONE_COMPONENT(comp, type) \ + static inline __HOST_DEVICE__ type make_##type(comp x) { \ + type r{x}; \ + return r; \ + } + +#define DECLOP_MAKE_TWO_COMPONENT(comp, type) \ + static inline __HOST_DEVICE__ type make_##type(comp x, comp y) { \ + type r{x, y}; \ + return r; \ + } + +#define DECLOP_MAKE_THREE_COMPONENT(comp, type) \ + static inline __HOST_DEVICE__ type make_##type(comp x, comp y, comp z) { \ + type r{x, y, z}; \ + return r; \ + } + +#define DECLOP_MAKE_FOUR_COMPONENT(comp, type) \ + static inline __HOST_DEVICE__ type make_##type(comp x, comp y, comp z, comp w) { \ + type r{x, y, z, w}; \ + return r; \ + } +#else +#define DECLOP_MAKE_ONE_COMPONENT(comp, type) \ + static inline __HOST_DEVICE__ type make_##type(comp x) { \ + type r; \ + r.x = x; \ + return r; \ + } + +#define DECLOP_MAKE_TWO_COMPONENT(comp, type) \ + static inline __HOST_DEVICE__ type make_##type(comp x, comp y) { \ + type r; \ + r.x = x; \ + r.y = y; \ + return r; \ + } + +#define DECLOP_MAKE_THREE_COMPONENT(comp, type) \ + static inline __HOST_DEVICE__ type make_##type(comp x, comp y, comp z) { \ + type r; \ + r.x = x; \ + r.y = y; \ + r.z = z; \ + return r; \ + } + +#define DECLOP_MAKE_FOUR_COMPONENT(comp, type) \ + static inline __HOST_DEVICE__ type make_##type(comp x, comp y, comp z, comp w) { \ + type r; \ + r.x = x; \ + r.y = y; \ + r.z = z; \ + r.w = w; \ + return r; \ + } +#endif + +DECLOP_MAKE_ONE_COMPONENT(unsigned char, uchar1); +DECLOP_MAKE_TWO_COMPONENT(unsigned char, uchar2); +DECLOP_MAKE_THREE_COMPONENT(unsigned char, uchar3); +DECLOP_MAKE_FOUR_COMPONENT(unsigned char, uchar4); + +DECLOP_MAKE_ONE_COMPONENT(signed char, char1); +DECLOP_MAKE_TWO_COMPONENT(signed char, char2); +DECLOP_MAKE_THREE_COMPONENT(signed char, char3); +DECLOP_MAKE_FOUR_COMPONENT(signed char, char4); + +DECLOP_MAKE_ONE_COMPONENT(unsigned short, ushort1); +DECLOP_MAKE_TWO_COMPONENT(unsigned short, ushort2); +DECLOP_MAKE_THREE_COMPONENT(unsigned short, ushort3); +DECLOP_MAKE_FOUR_COMPONENT(unsigned short, ushort4); + +DECLOP_MAKE_ONE_COMPONENT(signed short, short1); +DECLOP_MAKE_TWO_COMPONENT(signed short, short2); +DECLOP_MAKE_THREE_COMPONENT(signed short, short3); +DECLOP_MAKE_FOUR_COMPONENT(signed short, short4); + +DECLOP_MAKE_ONE_COMPONENT(unsigned int, uint1); +DECLOP_MAKE_TWO_COMPONENT(unsigned int, uint2); +DECLOP_MAKE_THREE_COMPONENT(unsigned int, uint3); +DECLOP_MAKE_FOUR_COMPONENT(unsigned int, uint4); + +DECLOP_MAKE_ONE_COMPONENT(signed int, int1); +DECLOP_MAKE_TWO_COMPONENT(signed int, int2); +DECLOP_MAKE_THREE_COMPONENT(signed int, int3); +DECLOP_MAKE_FOUR_COMPONENT(signed int, int4); + +DECLOP_MAKE_ONE_COMPONENT(float, float1); +DECLOP_MAKE_TWO_COMPONENT(float, float2); +DECLOP_MAKE_THREE_COMPONENT(float, float3); +DECLOP_MAKE_FOUR_COMPONENT(float, float4); + +DECLOP_MAKE_ONE_COMPONENT(double, double1); +DECLOP_MAKE_TWO_COMPONENT(double, double2); +DECLOP_MAKE_THREE_COMPONENT(double, double3); +DECLOP_MAKE_FOUR_COMPONENT(double, double4); + +DECLOP_MAKE_ONE_COMPONENT(unsigned long, ulong1); +DECLOP_MAKE_TWO_COMPONENT(unsigned long, ulong2); +DECLOP_MAKE_THREE_COMPONENT(unsigned long, ulong3); +DECLOP_MAKE_FOUR_COMPONENT(unsigned long, ulong4); + +DECLOP_MAKE_ONE_COMPONENT(signed long, long1); +DECLOP_MAKE_TWO_COMPONENT(signed long, long2); +DECLOP_MAKE_THREE_COMPONENT(signed long, long3); +DECLOP_MAKE_FOUR_COMPONENT(signed long, long4); + +DECLOP_MAKE_ONE_COMPONENT(unsigned long long, ulonglong1); +DECLOP_MAKE_TWO_COMPONENT(unsigned long long, ulonglong2); +DECLOP_MAKE_THREE_COMPONENT(unsigned long long, ulonglong3); +DECLOP_MAKE_FOUR_COMPONENT(unsigned long long, ulonglong4); + +DECLOP_MAKE_ONE_COMPONENT(signed long long, longlong1); +DECLOP_MAKE_TWO_COMPONENT(signed long long, longlong2); +DECLOP_MAKE_THREE_COMPONENT(signed long long, longlong3); +DECLOP_MAKE_FOUR_COMPONENT(signed long long, longlong4); + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_math_functions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_math_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..294dbf430573c54ab156fe63c70e6a8c11e67d7c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_math_functions.h @@ -0,0 +1,104 @@ +/* +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. +*/ + +#pragma once + +#if !defined(__HIPCC_RTC__) +#include "hip_fp16_math_fwd.h" +#include "amd_hip_vector_types.h" +#include "math_fwd.h" + +#include + +#include +// assert.h is only for the host version of assert. +// The device version of assert is implemented in hip/amd_detail/hip_runtime.h. +// Users should include hip_runtime.h for the device version of assert. +#if !__HIP_DEVICE_COMPILE__ +#include +#endif +#include +#include +#include +#endif // !defined(__HIPCC_RTC__) + +#if _LIBCPP_VERSION && __HIP__ +namespace std { +template <> +struct __numeric_type<_Float16> +{ + static _Float16 __test(_Float16); + + typedef _Float16 type; + static const bool value = true; +}; +} +#endif // _LIBCPP_VERSION + +#pragma push_macro("__DEVICE__") +#pragma push_macro("__RETURN_TYPE") + +#define __DEVICE__ static __device__ +#define __RETURN_TYPE bool + +// DOT FUNCTIONS +#if defined(__clang__) && defined(__HIP__) +__DEVICE__ +inline +int amd_mixed_dot(short2 a, short2 b, int c, bool saturate) { + return __ockl_sdot2(a.data, b.data, c, saturate); +} +__DEVICE__ +inline +uint amd_mixed_dot(ushort2 a, ushort2 b, uint c, bool saturate) { + return __ockl_udot2(a.data, b.data, c, saturate); +} +__DEVICE__ +inline +int amd_mixed_dot(char4 a, char4 b, int c, bool saturate) { + return __ockl_sdot4(a.data, b.data, c, saturate); +} +__DEVICE__ +inline +uint amd_mixed_dot(uchar4 a, uchar4 b, uint c, bool saturate) { + return __ockl_udot4(a.data, b.data, c, saturate); +} +__DEVICE__ +inline +int amd_mixed_dot(int a, int b, int c, bool saturate) { + return __ockl_sdot8(a, b, c, saturate); +} +__DEVICE__ +inline +uint amd_mixed_dot(uint a, uint b, uint c, bool saturate) { + return __ockl_udot8(a, b, c, saturate); +} +#endif + +#pragma pop_macro("__DEVICE__") +#pragma pop_macro("__RETURN_TYPE") +// For backward compatibility. +// There are HIP applications e.g. TensorFlow, expecting __HIP_ARCH_* macros +// defined after including math_functions.h. +#if !defined(__HIPCC_RTC__) +#include +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_surface_functions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_surface_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..556988a8e76a8c43dcbfa7fa275d8069e4b085b3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_surface_functions.h @@ -0,0 +1,244 @@ +/* +Copyright (c) 2018 - 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_SURFACE_FUNCTIONS_H +#define HIP_INCLUDE_HIP_AMD_DETAIL_SURFACE_FUNCTIONS_H + +#if defined(__cplusplus) + +#if !defined(__HIPCC_RTC__) +#include +#include +#include +#include +#endif + +#if defined(__HIPCC_RTC__) +#define __HOST_DEVICE__ __device__ +#else +#define __HOST_DEVICE__ __host__ __device__ +#endif + +#define __HIP_SURFACE_OBJECT_PARAMETERS_INIT \ + unsigned int ADDRESS_SPACE_CONSTANT* i = (unsigned int ADDRESS_SPACE_CONSTANT*)surfObj; + +// CUDA is using byte address, need map to pixel address for HIP +static __HOST_DEVICE__ __forceinline__ int __hipGetPixelAddr(int x, int format, int order) { + /* + * use below format index to generate format LUT + typedef enum { + HSA_EXT_IMAGE_CHANNEL_TYPE_SNORM_INT8 = 0, + HSA_EXT_IMAGE_CHANNEL_TYPE_SNORM_INT16 = 1, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_INT8 = 2, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_INT16 = 3, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_INT24 = 4, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_SHORT_555 = 5, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_SHORT_565 = 6, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_SHORT_101010 = 7, + HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT8 = 8, + HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT16 = 9, + HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT32 = 10, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT8 = 11, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT16 = 12, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT32 = 13, + HSA_EXT_IMAGE_CHANNEL_TYPE_HALF_FLOAT = 14, + HSA_EXT_IMAGE_CHANNEL_TYPE_FLOAT = 15 + } hsa_ext_image_channel_type_t; + */ + static const int FormatLUT[] = { 0, 1, 0, 1, 3, 1, 1, 1, 0, 1, 2, 0, 1, 2, 1, 2 }; + x = FormatLUT[format] == 3 ? x / FormatLUT[format] : x >> FormatLUT[format]; + + /* + * use below order index to generate order LUT + typedef enum { + HSA_EXT_IMAGE_CHANNEL_ORDER_A = 0, + HSA_EXT_IMAGE_CHANNEL_ORDER_R = 1, + HSA_EXT_IMAGE_CHANNEL_ORDER_RX = 2, + HSA_EXT_IMAGE_CHANNEL_ORDER_RG = 3, + HSA_EXT_IMAGE_CHANNEL_ORDER_RGX = 4, + HSA_EXT_IMAGE_CHANNEL_ORDER_RA = 5, + HSA_EXT_IMAGE_CHANNEL_ORDER_RGB = 6, + HSA_EXT_IMAGE_CHANNEL_ORDER_RGBX = 7, + HSA_EXT_IMAGE_CHANNEL_ORDER_RGBA = 8, + HSA_EXT_IMAGE_CHANNEL_ORDER_BGRA = 9, + HSA_EXT_IMAGE_CHANNEL_ORDER_ARGB = 10, + HSA_EXT_IMAGE_CHANNEL_ORDER_ABGR = 11, + HSA_EXT_IMAGE_CHANNEL_ORDER_SRGB = 12, + HSA_EXT_IMAGE_CHANNEL_ORDER_SRGBX = 13, + HSA_EXT_IMAGE_CHANNEL_ORDER_SRGBA = 14, + HSA_EXT_IMAGE_CHANNEL_ORDER_SBGRA = 15, + HSA_EXT_IMAGE_CHANNEL_ORDER_INTENSITY = 16, + HSA_EXT_IMAGE_CHANNEL_ORDER_LUMINANCE = 17, + HSA_EXT_IMAGE_CHANNEL_ORDER_DEPTH = 18, + HSA_EXT_IMAGE_CHANNEL_ORDER_DEPTH_STENCIL = 19 + } hsa_ext_image_channel_order_t; + */ + static const int OrderLUT[] = { 0, 0, 1, 1, 3, 1, 3, 2, 2, 2, 2, 2, 3, 2, 2, 2, 0, 0, 0, 0 }; + return x = OrderLUT[order] == 3 ? x / OrderLUT[order] : x >> OrderLUT[order]; +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void surf1Dread(T* data, hipSurfaceObject_t surfObj, int x, + int boundaryMode = hipBoundaryModeZero) { + __HIP_SURFACE_OBJECT_PARAMETERS_INIT + x = __hipGetPixelAddr(x, __ockl_image_channel_data_type_1D(i), __ockl_image_channel_order_1D(i)); + auto tmp = __ockl_image_load_1D(i, x); + *data = __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void surf1Dwrite(T data, hipSurfaceObject_t surfObj, int x) { + __HIP_SURFACE_OBJECT_PARAMETERS_INIT + x = __hipGetPixelAddr(x, __ockl_image_channel_data_type_1D(i), __ockl_image_channel_order_1D(i)); + auto tmp = __hipMapTo(data); + __ockl_image_store_1D(i, x, tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void surf2Dread(T* data, hipSurfaceObject_t surfObj, int x, int y) { + __HIP_SURFACE_OBJECT_PARAMETERS_INIT + x = __hipGetPixelAddr(x, __ockl_image_channel_data_type_2D(i), __ockl_image_channel_order_2D(i)); + auto tmp = __ockl_image_load_2D(i, int2(x, y).data); + *data = __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void surf2Dwrite(T data, hipSurfaceObject_t surfObj, int x, int y) { + __HIP_SURFACE_OBJECT_PARAMETERS_INIT + x = __hipGetPixelAddr(x, __ockl_image_channel_data_type_2D(i), __ockl_image_channel_order_2D(i)); + auto tmp = __hipMapTo(data); + __ockl_image_store_2D(i, int2(x, y).data, tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void surf3Dread(T* data, hipSurfaceObject_t surfObj, int x, int y, int z) { + __HIP_SURFACE_OBJECT_PARAMETERS_INIT + x = __hipGetPixelAddr(x, __ockl_image_channel_data_type_3D(i), __ockl_image_channel_order_3D(i)); + auto tmp = __ockl_image_load_3D(i, int4(x, y, z, 0).data); + *data = __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void surf3Dwrite(T data, hipSurfaceObject_t surfObj, int x, int y, int z) { + __HIP_SURFACE_OBJECT_PARAMETERS_INIT + x = __hipGetPixelAddr(x, __ockl_image_channel_data_type_3D(i), __ockl_image_channel_order_3D(i)); + auto tmp = __hipMapTo(data); + __ockl_image_store_3D(i, int4(x, y, z, 0).data, tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void surf1DLayeredread(T* data, hipSurfaceObject_t surfObj, int x, int layer) { + __HIP_SURFACE_OBJECT_PARAMETERS_INIT + x = __hipGetPixelAddr(x, __ockl_image_channel_data_type_1D(i), __ockl_image_channel_order_1D(i)); + auto tmp = __ockl_image_load_lod_1D(i, x, layer); + *data = __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void surf1DLayeredwrite(T data, hipSurfaceObject_t surfObj, int x, int layer) { + __HIP_SURFACE_OBJECT_PARAMETERS_INIT + x = __hipGetPixelAddr(x, __ockl_image_channel_data_type_1D(i), __ockl_image_channel_order_1D(i)); + auto tmp = __hipMapTo(data); + __ockl_image_store_lod_1D(i, x, layer, tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void surf2DLayeredread(T* data, hipSurfaceObject_t surfObj, int x, int y, int layer) { + __HIP_SURFACE_OBJECT_PARAMETERS_INIT + x = __hipGetPixelAddr(x, __ockl_image_channel_data_type_2D(i), __ockl_image_channel_order_2D(i)); + auto tmp = __ockl_image_load_lod_2D(i, int2(x, y).data, layer); + *data = __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void surf2DLayeredwrite(T data, hipSurfaceObject_t surfObj, int x, int y, int layer) { + __HIP_SURFACE_OBJECT_PARAMETERS_INIT + x = __hipGetPixelAddr(x, __ockl_image_channel_data_type_2D(i), __ockl_image_channel_order_2D(i)); + auto tmp = __hipMapTo(data); + __ockl_image_store_lod_2D(i, int2(x, y).data, layer, tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void surfCubemapread(T* data, hipSurfaceObject_t surfObj, int x, int y, int face) { + __HIP_SURFACE_OBJECT_PARAMETERS_INIT + x = __hipGetPixelAddr(x, __ockl_image_channel_data_type_2D(i), __ockl_image_channel_order_2D(i)); + auto tmp = __ockl_image_load_CM(i, int2(x, y).data, face); + *data = __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void surfCubemapwrite(T data, hipSurfaceObject_t surfObj, int x, int y, int face) { + __HIP_SURFACE_OBJECT_PARAMETERS_INIT + x = __hipGetPixelAddr(x, __ockl_image_channel_data_type_2D(i), __ockl_image_channel_order_2D(i)); + auto tmp = __hipMapTo(data); + __ockl_image_store_CM(i, int2(x, y).data, face, tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void surfCubemapLayeredread(T* data, hipSurfaceObject_t surfObj, int x, int y, int face, + int layer) { + __HIP_SURFACE_OBJECT_PARAMETERS_INIT + x = __hipGetPixelAddr(x, __ockl_image_channel_data_type_2D(i), __ockl_image_channel_order_2D(i)); + auto tmp = __ockl_image_load_lod_CM(i, int2(x, y).data, face, layer); + *data = __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void surfCubemapLayeredwrite(T* data, hipSurfaceObject_t surfObj, int x, int y, int face, + int layer) { + __HIP_SURFACE_OBJECT_PARAMETERS_INIT + x = __hipGetPixelAddr(x, __ockl_image_channel_data_type_2D(i), __ockl_image_channel_order_2D(i)); + auto tmp = __hipMapTo(data); + __ockl_image_store_lod_CM(i, int2(x, y).data, face, layer, tmp); +} + +#endif + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_warp_functions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_warp_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..98f8896cd91d3c1440564d30750f7d1dcb0b6581 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_warp_functions.h @@ -0,0 +1,538 @@ +/* +Copyright (c) 2022 - 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_WARP_FUNCTIONS_H +#define HIP_INCLUDE_HIP_AMD_DETAIL_WARP_FUNCTIONS_H + +__device__ static inline unsigned __hip_ds_bpermute(int index, unsigned src) { + union { int i; unsigned u; float f; } tmp; tmp.u = src; + tmp.i = __builtin_amdgcn_ds_bpermute(index, tmp.i); + return tmp.u; +} + +__device__ static inline float __hip_ds_bpermutef(int index, float src) { + union { int i; unsigned u; float f; } tmp; tmp.f = src; + tmp.i = __builtin_amdgcn_ds_bpermute(index, tmp.i); + return tmp.f; +} + +__device__ static inline unsigned __hip_ds_permute(int index, unsigned src) { + union { int i; unsigned u; float f; } tmp; tmp.u = src; + tmp.i = __builtin_amdgcn_ds_permute(index, tmp.i); + return tmp.u; +} + +__device__ static inline float __hip_ds_permutef(int index, float src) { + union { int i; unsigned u; float f; } tmp; tmp.f = src; + tmp.i = __builtin_amdgcn_ds_permute(index, tmp.i); + return tmp.f; +} + +#define __hip_ds_swizzle(src, pattern) __hip_ds_swizzle_N<(pattern)>((src)) +#define __hip_ds_swizzlef(src, pattern) __hip_ds_swizzlef_N<(pattern)>((src)) + +template +__device__ static inline unsigned __hip_ds_swizzle_N(unsigned int src) { + union { int i; unsigned u; float f; } tmp; tmp.u = src; + tmp.i = __builtin_amdgcn_ds_swizzle(tmp.i, pattern); + return tmp.u; +} + +template +__device__ static inline float __hip_ds_swizzlef_N(float src) { + union { int i; unsigned u; float f; } tmp; tmp.f = src; + tmp.i = __builtin_amdgcn_ds_swizzle(tmp.i, pattern); + return tmp.f; +} + +#define __hip_move_dpp(src, dpp_ctrl, row_mask, bank_mask, bound_ctrl) \ + __hip_move_dpp_N<(dpp_ctrl), (row_mask), (bank_mask), (bound_ctrl)>((src)) + +template +__device__ static inline int __hip_move_dpp_N(int src) { + return __builtin_amdgcn_mov_dpp(src, dpp_ctrl, row_mask, bank_mask, + bound_ctrl); +} + +static constexpr int warpSize = __AMDGCN_WAVEFRONT_SIZE; + +// warp vote function __all __any __ballot +__device__ +inline +int __all(int predicate) { + return __ockl_wfall_i32(predicate); +} + +__device__ +inline +int __any(int predicate) { + return __ockl_wfany_i32(predicate); +} + +// XXX from llvm/include/llvm/IR/InstrTypes.h +#define ICMP_NE 33 + +__device__ +inline +unsigned long long int __ballot(int predicate) { + return __builtin_amdgcn_uicmp(predicate, 0, ICMP_NE); +} + +__device__ +inline +unsigned long long int __ballot64(int predicate) { + return __builtin_amdgcn_uicmp(predicate, 0, ICMP_NE); +} + +// See amd_warp_sync_functions.h for an explanation of this preprocessor flag. +#ifdef HIP_ENABLE_WARP_SYNC_BUILTINS +// Since threads in a wave do not make independent progress, __activemask() +// always returns the exact active mask, i.e, all active threads in the wave. +__device__ +inline +unsigned long long __activemask() { + return __ballot(true); +} +#endif // HIP_ENABLE_WARP_SYNC_BUILTINS + +__device__ static inline unsigned int __lane_id() { + return __builtin_amdgcn_mbcnt_hi( + -1, __builtin_amdgcn_mbcnt_lo(-1, 0)); +} + +__device__ +inline +int __shfl(int var, int src_lane, int width = warpSize) { + int self = __lane_id(); + int index = (src_lane & (width - 1)) + (self & ~(width-1)); + return __builtin_amdgcn_ds_bpermute(index<<2, var); +} +__device__ +inline +unsigned int __shfl(unsigned int var, int src_lane, int width = warpSize) { + union { int i; unsigned u; float f; } tmp; tmp.u = var; + tmp.i = __shfl(tmp.i, src_lane, width); + return tmp.u; +} +__device__ +inline +float __shfl(float var, int src_lane, int width = warpSize) { + union { int i; unsigned u; float f; } tmp; tmp.f = var; + tmp.i = __shfl(tmp.i, src_lane, width); + return tmp.f; +} +__device__ +inline +double __shfl(double var, int src_lane, int width = warpSize) { + static_assert(sizeof(double) == 2 * sizeof(int), ""); + static_assert(sizeof(double) == sizeof(uint64_t), ""); + + int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl(tmp[0], src_lane, width); + tmp[1] = __shfl(tmp[1], src_lane, width); + + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + double tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; +} +__device__ +inline +long __shfl(long var, int src_lane, int width = warpSize) +{ + #ifndef _MSC_VER + static_assert(sizeof(long) == 2 * sizeof(int), ""); + static_assert(sizeof(long) == sizeof(uint64_t), ""); + + int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl(tmp[0], src_lane, width); + tmp[1] = __shfl(tmp[1], src_lane, width); + + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; + #else + static_assert(sizeof(long) == sizeof(int), ""); + return static_cast(__shfl(static_cast(var), src_lane, width)); + #endif +} +__device__ +inline +unsigned long __shfl(unsigned long var, int src_lane, int width = warpSize) { + #ifndef _MSC_VER + static_assert(sizeof(unsigned long) == 2 * sizeof(unsigned int), ""); + static_assert(sizeof(unsigned long) == sizeof(uint64_t), ""); + + unsigned int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl(tmp[0], src_lane, width); + tmp[1] = __shfl(tmp[1], src_lane, width); + + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + unsigned long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; + #else + static_assert(sizeof(unsigned long) == sizeof(unsigned int), ""); + return static_cast(__shfl(static_cast(var), src_lane, width)); + #endif +} +__device__ +inline +long long __shfl(long long var, int src_lane, int width = warpSize) +{ + static_assert(sizeof(long long) == 2 * sizeof(int), ""); + static_assert(sizeof(long long) == sizeof(uint64_t), ""); + + int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl(tmp[0], src_lane, width); + tmp[1] = __shfl(tmp[1], src_lane, width); + + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + long long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; +} +__device__ +inline +unsigned long long __shfl(unsigned long long var, int src_lane, int width = warpSize) { + static_assert(sizeof(unsigned long long) == 2 * sizeof(unsigned int), ""); + static_assert(sizeof(unsigned long long) == sizeof(uint64_t), ""); + + unsigned int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl(tmp[0], src_lane, width); + tmp[1] = __shfl(tmp[1], src_lane, width); + + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + unsigned long long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; +} + +__device__ +inline +int __shfl_up(int var, unsigned int lane_delta, int width = warpSize) { + int self = __lane_id(); + int index = self - lane_delta; + index = (index < (self & ~(width-1)))?self:index; + return __builtin_amdgcn_ds_bpermute(index<<2, var); +} +__device__ +inline +unsigned int __shfl_up(unsigned int var, unsigned int lane_delta, int width = warpSize) { + union { int i; unsigned u; float f; } tmp; tmp.u = var; + tmp.i = __shfl_up(tmp.i, lane_delta, width); + return tmp.u; +} +__device__ +inline +float __shfl_up(float var, unsigned int lane_delta, int width = warpSize) { + union { int i; unsigned u; float f; } tmp; tmp.f = var; + tmp.i = __shfl_up(tmp.i, lane_delta, width); + return tmp.f; +} +__device__ +inline +double __shfl_up(double var, unsigned int lane_delta, int width = warpSize) { + static_assert(sizeof(double) == 2 * sizeof(int), ""); + static_assert(sizeof(double) == sizeof(uint64_t), ""); + + int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl_up(tmp[0], lane_delta, width); + tmp[1] = __shfl_up(tmp[1], lane_delta, width); + + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + double tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; +} +__device__ +inline +long __shfl_up(long var, unsigned int lane_delta, int width = warpSize) +{ + #ifndef _MSC_VER + static_assert(sizeof(long) == 2 * sizeof(int), ""); + static_assert(sizeof(long) == sizeof(uint64_t), ""); + + int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl_up(tmp[0], lane_delta, width); + tmp[1] = __shfl_up(tmp[1], lane_delta, width); + + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; + #else + static_assert(sizeof(long) == sizeof(int), ""); + return static_cast(__shfl_up(static_cast(var), lane_delta, width)); + #endif +} + +__device__ +inline +unsigned long __shfl_up(unsigned long var, unsigned int lane_delta, int width = warpSize) +{ + #ifndef _MSC_VER + static_assert(sizeof(unsigned long) == 2 * sizeof(unsigned int), ""); + static_assert(sizeof(unsigned long) == sizeof(uint64_t), ""); + + unsigned int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl_up(tmp[0], lane_delta, width); + tmp[1] = __shfl_up(tmp[1], lane_delta, width); + + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + unsigned long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; + #else + static_assert(sizeof(unsigned long) == sizeof(unsigned int), ""); + return static_cast(__shfl_up(static_cast(var), lane_delta, width)); + #endif +} + +__device__ +inline +long long __shfl_up(long long var, unsigned int lane_delta, int width = warpSize) +{ + static_assert(sizeof(long long) == 2 * sizeof(int), ""); + static_assert(sizeof(long long) == sizeof(uint64_t), ""); + int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl_up(tmp[0], lane_delta, width); + tmp[1] = __shfl_up(tmp[1], lane_delta, width); + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + long long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; +} + +__device__ +inline +unsigned long long __shfl_up(unsigned long long var, unsigned int lane_delta, int width = warpSize) +{ + static_assert(sizeof(unsigned long long) == 2 * sizeof(unsigned int), ""); + static_assert(sizeof(unsigned long long) == sizeof(uint64_t), ""); + unsigned int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl_up(tmp[0], lane_delta, width); + tmp[1] = __shfl_up(tmp[1], lane_delta, width); + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + unsigned long long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; +} + +__device__ +inline +int __shfl_down(int var, unsigned int lane_delta, int width = warpSize) { + int self = __lane_id(); + int index = self + lane_delta; + index = (int)((self&(width-1))+lane_delta) >= width?self:index; + return __builtin_amdgcn_ds_bpermute(index<<2, var); +} +__device__ +inline +unsigned int __shfl_down(unsigned int var, unsigned int lane_delta, int width = warpSize) { + union { int i; unsigned u; float f; } tmp; tmp.u = var; + tmp.i = __shfl_down(tmp.i, lane_delta, width); + return tmp.u; +} +__device__ +inline +float __shfl_down(float var, unsigned int lane_delta, int width = warpSize) { + union { int i; unsigned u; float f; } tmp; tmp.f = var; + tmp.i = __shfl_down(tmp.i, lane_delta, width); + return tmp.f; +} +__device__ +inline +double __shfl_down(double var, unsigned int lane_delta, int width = warpSize) { + static_assert(sizeof(double) == 2 * sizeof(int), ""); + static_assert(sizeof(double) == sizeof(uint64_t), ""); + + int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl_down(tmp[0], lane_delta, width); + tmp[1] = __shfl_down(tmp[1], lane_delta, width); + + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + double tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; +} +__device__ +inline +long __shfl_down(long var, unsigned int lane_delta, int width = warpSize) +{ + #ifndef _MSC_VER + static_assert(sizeof(long) == 2 * sizeof(int), ""); + static_assert(sizeof(long) == sizeof(uint64_t), ""); + + int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl_down(tmp[0], lane_delta, width); + tmp[1] = __shfl_down(tmp[1], lane_delta, width); + + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; + #else + static_assert(sizeof(long) == sizeof(int), ""); + return static_cast(__shfl_down(static_cast(var), lane_delta, width)); + #endif +} +__device__ +inline +unsigned long __shfl_down(unsigned long var, unsigned int lane_delta, int width = warpSize) +{ + #ifndef _MSC_VER + static_assert(sizeof(unsigned long) == 2 * sizeof(unsigned int), ""); + static_assert(sizeof(unsigned long) == sizeof(uint64_t), ""); + + unsigned int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl_down(tmp[0], lane_delta, width); + tmp[1] = __shfl_down(tmp[1], lane_delta, width); + + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + unsigned long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; + #else + static_assert(sizeof(unsigned long) == sizeof(unsigned int), ""); + return static_cast(__shfl_down(static_cast(var), lane_delta, width)); + #endif +} +__device__ +inline +long long __shfl_down(long long var, unsigned int lane_delta, int width = warpSize) +{ + static_assert(sizeof(long long) == 2 * sizeof(int), ""); + static_assert(sizeof(long long) == sizeof(uint64_t), ""); + int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl_down(tmp[0], lane_delta, width); + tmp[1] = __shfl_down(tmp[1], lane_delta, width); + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + long long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; +} +__device__ +inline +unsigned long long __shfl_down(unsigned long long var, unsigned int lane_delta, int width = warpSize) +{ + static_assert(sizeof(unsigned long long) == 2 * sizeof(unsigned int), ""); + static_assert(sizeof(unsigned long long) == sizeof(uint64_t), ""); + unsigned int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl_down(tmp[0], lane_delta, width); + tmp[1] = __shfl_down(tmp[1], lane_delta, width); + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + unsigned long long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; +} + +__device__ +inline +int __shfl_xor(int var, int lane_mask, int width = warpSize) { + int self = __lane_id(); + int index = self^lane_mask; + index = index >= ((self+width)&~(width-1))?self:index; + return __builtin_amdgcn_ds_bpermute(index<<2, var); +} +__device__ +inline +unsigned int __shfl_xor(unsigned int var, int lane_mask, int width = warpSize) { + union { int i; unsigned u; float f; } tmp; tmp.u = var; + tmp.i = __shfl_xor(tmp.i, lane_mask, width); + return tmp.u; +} +__device__ +inline +float __shfl_xor(float var, int lane_mask, int width = warpSize) { + union { int i; unsigned u; float f; } tmp; tmp.f = var; + tmp.i = __shfl_xor(tmp.i, lane_mask, width); + return tmp.f; +} +__device__ +inline +double __shfl_xor(double var, int lane_mask, int width = warpSize) { + static_assert(sizeof(double) == 2 * sizeof(int), ""); + static_assert(sizeof(double) == sizeof(uint64_t), ""); + + int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl_xor(tmp[0], lane_mask, width); + tmp[1] = __shfl_xor(tmp[1], lane_mask, width); + + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + double tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; +} +__device__ +inline +long __shfl_xor(long var, int lane_mask, int width = warpSize) +{ + #ifndef _MSC_VER + static_assert(sizeof(long) == 2 * sizeof(int), ""); + static_assert(sizeof(long) == sizeof(uint64_t), ""); + + int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl_xor(tmp[0], lane_mask, width); + tmp[1] = __shfl_xor(tmp[1], lane_mask, width); + + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; + #else + static_assert(sizeof(long) == sizeof(int), ""); + return static_cast(__shfl_xor(static_cast(var), lane_mask, width)); + #endif +} +__device__ +inline +unsigned long __shfl_xor(unsigned long var, int lane_mask, int width = warpSize) +{ + #ifndef _MSC_VER + static_assert(sizeof(unsigned long) == 2 * sizeof(unsigned int), ""); + static_assert(sizeof(unsigned long) == sizeof(uint64_t), ""); + + unsigned int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl_xor(tmp[0], lane_mask, width); + tmp[1] = __shfl_xor(tmp[1], lane_mask, width); + + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + unsigned long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; + #else + static_assert(sizeof(unsigned long) == sizeof(unsigned int), ""); + return static_cast(__shfl_xor(static_cast(var), lane_mask, width)); + #endif +} +__device__ +inline +long long __shfl_xor(long long var, int lane_mask, int width = warpSize) +{ + static_assert(sizeof(long long) == 2 * sizeof(int), ""); + static_assert(sizeof(long long) == sizeof(uint64_t), ""); + int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl_xor(tmp[0], lane_mask, width); + tmp[1] = __shfl_xor(tmp[1], lane_mask, width); + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + long long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; +} +__device__ +inline +unsigned long long __shfl_xor(unsigned long long var, int lane_mask, int width = warpSize) +{ + static_assert(sizeof(unsigned long long) == 2 * sizeof(unsigned int), ""); + static_assert(sizeof(unsigned long long) == sizeof(uint64_t), ""); + unsigned int tmp[2]; __builtin_memcpy(tmp, &var, sizeof(tmp)); + tmp[0] = __shfl_xor(tmp[0], lane_mask, width); + tmp[1] = __shfl_xor(tmp[1], lane_mask, width); + uint64_t tmp0 = (static_cast(tmp[1]) << 32ull) | static_cast(tmp[0]); + unsigned long long tmp1; __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0)); + return tmp1; +} + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_warp_sync_functions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_warp_sync_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..8ef0b2e1d73ee7a710bece0a036f185cdc4e697c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_warp_sync_functions.h @@ -0,0 +1,288 @@ +/* +Copyright (c) 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. +*/ + +#pragma once + +// Warp sync builtins (with explicit mask argument) introduced in ROCm 6.2 as a +// preview to allow end-users to adapt to the new interface involving 64-bit +// masks. These are disabled by default, and can be enabled by setting the macro +// below. The builtins will be enabled unconditionally in ROCm 6.3. +// +// This arrangement also applies to the __activemask() builtin defined in +// amd_warp_functions.h. +#ifdef HIP_ENABLE_WARP_SYNC_BUILTINS + +#if !defined(__HIPCC_RTC__) +#include "amd_warp_functions.h" +#include "hip_assert.h" +#endif + +template +__device__ inline +T __hip_readfirstlane(T val) { + // In theory, behaviour is undefined when reading from a union member other + // than the member that was last assigned to, but it works in practice because + // we rely on the compiler to do the reasonable thing. + union { + unsigned long long l; + T d; + } u; + u.d = val; + // NOTE: The builtin returns int, so we first cast it to unsigned int and only + // then extend it to 64 bits. + unsigned long long lower = (unsigned)__builtin_amdgcn_readfirstlane(u.l); + unsigned long long upper = + (unsigned)__builtin_amdgcn_readfirstlane(u.l >> 32); + u.l = (upper << 32) | lower; + return u.d; +} + +// When compiling for wave32 mode, ignore the upper half of the 64-bit mask. +#define __hip_adjust_mask_for_wave32(MASK) \ + do { \ + if (warpSize == 32) MASK &= 0xFFFFFFFF; \ + } while (0) + +// We use a macro to expand each builtin into a waterfall that implements the +// mask semantics: +// +// 1. The mask argument may be divergent. +// 2. Each active thread must have its own bit set in its own mask value. +// 3. For a given mask value, all threads that are mentioned in the mask must +// execute the same static instance of the builtin with the same mask. +// 4. The union of all mask values supplied at a static instance must be equal +// to the activemask at the program point. +// +// Thus, the mask argument partitions the set of currently active threads in the +// wave into disjoint subsets that cover all active threads. +// +// Implementation notes: +// --------------------- +// +// We implement this as a waterfall loop that executes the builtin for each +// subset separately. The return value is a divergent value across the active +// threads. The value for inactive threads is defined by each builtin +// separately. +// +// As long as every mask value is non-zero, we don't need to check if a lane +// specifies itself in the mask; that is done by the later assertion where all +// chosen lanes must be in the chosen mask. + +#define __hip_check_mask(MASK) \ + do { \ + __hip_assert(MASK && "mask must be non-zero"); \ + bool done = false; \ + while (__any(!done)) { \ + if (!done) { \ + auto chosen_mask = __hip_readfirstlane(MASK); \ + if (MASK == chosen_mask) { \ + __hip_assert(MASK == __ballot(true) && \ + "all threads specified in the mask" \ + " must execute the same operation with the same mask"); \ + done = true; \ + } \ + } \ + } \ + } while(0) + +#define __hip_do_sync(RETVAL, FUNC, MASK, ...) \ + do { \ + __hip_assert(MASK && "mask must be non-zero"); \ + bool done = false; \ + while (__any(!done)) { \ + if (!done) { \ + auto chosen_mask = __hip_readfirstlane(MASK); \ + if (MASK == chosen_mask) { \ + __hip_assert(MASK == __ballot(true) && \ + "all threads specified in the mask" \ + " must execute the same operation with the same mask"); \ + RETVAL = FUNC(__VA_ARGS__); \ + done = true; \ + } \ + } \ + } \ + } while(0) + +// __all_sync, __any_sync, __ballot_sync + +template +__device__ inline +unsigned long long __ballot_sync(MaskT mask, int predicate) { + static_assert( + __hip_internal::is_integral::value && sizeof(MaskT) == 8, + "The mask must be a 64-bit integer. " + "Implicitly promoting a smaller integer is almost always an error."); + __hip_adjust_mask_for_wave32(mask); + __hip_check_mask(mask); + return __ballot(predicate) & mask; +} + +template +__device__ inline +int __all_sync(MaskT mask, int predicate) { + static_assert( + __hip_internal::is_integral::value && sizeof(MaskT) == 8, + "The mask must be a 64-bit integer. " + "Implicitly promoting a smaller integer is almost always an error."); + __hip_adjust_mask_for_wave32(mask); + return __ballot_sync(mask, predicate) == mask; +} + +template +__device__ inline +int __any_sync(MaskT mask, int predicate) { + static_assert( + __hip_internal::is_integral::value && sizeof(MaskT) == 8, + "The mask must be a 64-bit integer. " + "Implicitly promoting a smaller integer is almost always an error."); + __hip_adjust_mask_for_wave32(mask); + return __ballot_sync(mask, predicate) != 0; +} + +// __match_any, __match_all and sync variants + +template +__device__ inline +unsigned long long __match_any(T value) { + static_assert( + (__hip_internal::is_integral::value || __hip_internal::is_floating_point::value) && + (sizeof(T) == 4 || sizeof(T) == 8), + "T can be int, unsigned int, long, unsigned long, long long, unsigned " + "long long, float or double."); + bool done = false; + unsigned long long retval = 0; + + while (__any(!done)) { + if (!done) { + T chosen = __hip_readfirstlane(value); + if (chosen == value) { + retval = __activemask(); + done = true; + } + } + } + + return retval; +} + +template +__device__ inline +unsigned long long __match_any_sync(MaskT mask, T value) { + static_assert( + __hip_internal::is_integral::value && sizeof(MaskT) == 8, + "The mask must be a 64-bit integer. " + "Implicitly promoting a smaller integer is almost always an error."); + __hip_adjust_mask_for_wave32(mask); + __hip_check_mask(mask); + return __match_any(value) & mask; +} + +template +__device__ inline +unsigned long long __match_all(T value, int* pred) { + static_assert( + (__hip_internal::is_integral::value || __hip_internal::is_floating_point::value) && + (sizeof(T) == 4 || sizeof(T) == 8), + "T can be int, unsigned int, long, unsigned long, long long, unsigned " + "long long, float or double."); + T first = __hip_readfirstlane(value); + if (__all(first == value)) { + *pred = true; + return __activemask(); + } else { + *pred = false; + return 0; + } +} + +template +__device__ inline +unsigned long long __match_all_sync(MaskT mask, T value, int* pred) { + static_assert( + __hip_internal::is_integral::value && sizeof(MaskT) == 8, + "The mask must be a 64-bit integer. " + "Implicitly promoting a smaller integer is almost always an error."); + MaskT retval = 0; + __hip_adjust_mask_for_wave32(mask); + __hip_do_sync(retval, __match_all, mask, value, pred); + return retval; +} + +// various variants of shfl + +template +__device__ inline +T __shfl_sync(MaskT mask, T var, int srcLane, + int width = __AMDGCN_WAVEFRONT_SIZE) { + static_assert( + __hip_internal::is_integral::value && sizeof(MaskT) == 8, + "The mask must be a 64-bit integer. " + "Implicitly promoting a smaller integer is almost always an error."); + __hip_adjust_mask_for_wave32(mask); + __hip_check_mask(mask); + return __shfl(var, srcLane, width); +} + +template +__device__ inline +T __shfl_up_sync(MaskT mask, T var, unsigned int delta, + int width = __AMDGCN_WAVEFRONT_SIZE) { + static_assert( + __hip_internal::is_integral::value && sizeof(MaskT) == 8, + "The mask must be a 64-bit integer. " + "Implicitly promoting a smaller integer is almost always an error."); + __hip_adjust_mask_for_wave32(mask); + __hip_check_mask(mask); + return __shfl_up(var, delta, width); +} + +template +__device__ inline +T __shfl_down_sync(MaskT mask, T var, unsigned int delta, + int width = __AMDGCN_WAVEFRONT_SIZE) { + static_assert( + __hip_internal::is_integral::value && sizeof(MaskT) == 8, + "The mask must be a 64-bit integer. " + "Implicitly promoting a smaller integer is almost always an error."); + __hip_adjust_mask_for_wave32(mask); + __hip_check_mask(mask); + return __shfl_down(var, delta, width); +} + +template +__device__ inline +T __shfl_xor_sync(MaskT mask, T var, int laneMask, + int width = __AMDGCN_WAVEFRONT_SIZE) { + static_assert( + __hip_internal::is_integral::value && sizeof(MaskT) == 8, + "The mask must be a 64-bit integer. " + "Implicitly promoting a smaller integer is almost always an error."); + __hip_adjust_mask_for_wave32(mask); + __hip_check_mask(mask); + return __shfl_xor(var, laneMask, width); +} + +#undef __hip_do_sync +#undef __hip_check_mask +#undef __hip_adjust_mask_for_wave32 + +#endif // HIP_ENABLE_WARP_SYNC_BUILTINS diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/concepts.hpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/concepts.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6aa8d56c2b8d0e017492fdb23eeed7ddd446a877 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/concepts.hpp @@ -0,0 +1,30 @@ +/* +Copyright (c) 2015 - 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. +*/ + +#pragma once + +namespace hip_impl // Documentation only. +{ +#define requires(...) + +#define FunctionalProcedure typename +} // namespace hip_impl diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/device_library_decls.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/device_library_decls.h new file mode 100644 index 0000000000000000000000000000000000000000..edc4692c838ee37ced0c35fe1561c73cd73a49a9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/device_library_decls.h @@ -0,0 +1,133 @@ +/* +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/device_library_decls.h + * @brief Contains declarations for types and functions in device library. + * Uses int64_t and uint64_t instead of long, long long, unsigned + * long and unsigned long long types for device library API + * declarations. + */ + +#ifndef HIP_INCLUDE_HIP_AMD_DETAIL_DEVICE_LIBRARY_DECLS_H +#define HIP_INCLUDE_HIP_AMD_DETAIL_DEVICE_LIBRARY_DECLS_H + +#if !defined(__HIPCC_RTC__) +#include "hip/amd_detail/host_defines.h" +#endif + +typedef unsigned char uchar; +typedef unsigned short ushort; +typedef unsigned int uint; +typedef unsigned long ulong; +typedef unsigned long long ullong; + +extern "C" __device__ __attribute__((const)) bool __ockl_wfany_i32(int); +extern "C" __device__ __attribute__((const)) bool __ockl_wfall_i32(int); +extern "C" __device__ uint __ockl_activelane_u32(void); + +extern "C" __device__ __attribute__((const)) uint __ockl_mul24_u32(uint, uint); +extern "C" __device__ __attribute__((const)) int __ockl_mul24_i32(int, int); +extern "C" __device__ __attribute__((const)) uint __ockl_mul_hi_u32(uint, uint); +extern "C" __device__ __attribute__((const)) int __ockl_mul_hi_i32(int, int); +extern "C" __device__ __attribute__((const)) uint __ockl_sadd_u32(uint, uint, uint); + +extern "C" __device__ __attribute__((const)) uchar __ockl_clz_u8(uchar); +extern "C" __device__ __attribute__((const)) ushort __ockl_clz_u16(ushort); +extern "C" __device__ __attribute__((const)) uint __ockl_clz_u32(uint); +extern "C" __device__ __attribute__((const)) uint64_t __ockl_clz_u64(uint64_t); + +extern "C" __device__ __attribute__((const)) float __ocml_floor_f32(float); +extern "C" __device__ __attribute__((const)) float __ocml_rint_f32(float); +extern "C" __device__ __attribute__((const)) float __ocml_ceil_f32(float); +extern "C" __device__ __attribute__((const)) float __ocml_trunc_f32(float); + +extern "C" __device__ __attribute__((const)) float __ocml_fmin_f32(float, float); +extern "C" __device__ __attribute__((const)) float __ocml_fmax_f32(float, float); + +extern "C" __device__ __attribute__((const)) float __ocml_cvtrtn_f32_f64(double); +extern "C" __device__ __attribute__((const)) float __ocml_cvtrtp_f32_f64(double); +extern "C" __device__ __attribute__((const)) float __ocml_cvtrtz_f32_f64(double); + +extern "C" __device__ __attribute__((const)) _Float16 __ocml_cvtrtn_f16_f32(float); +extern "C" __device__ __attribute__((const)) _Float16 __ocml_cvtrtp_f16_f32(float); +extern "C" __device__ __attribute__((const)) _Float16 __ocml_cvtrtz_f16_f32(float); + +extern "C" __device__ __attribute__((const)) float __ocml_cvtrtn_f32_s32(int); +extern "C" __device__ __attribute__((const)) float __ocml_cvtrtp_f32_s32(int); +extern "C" __device__ __attribute__((const)) float __ocml_cvtrtz_f32_s32(int); +extern "C" __device__ __attribute__((const)) float __ocml_cvtrtn_f32_u32(uint32_t); +extern "C" __device__ __attribute__((const)) float __ocml_cvtrtp_f32_u32(uint32_t); +extern "C" __device__ __attribute__((const)) float __ocml_cvtrtz_f32_u32(uint32_t); +extern "C" __device__ __attribute__((const)) float __ocml_cvtrtn_f32_s64(int64_t); +extern "C" __device__ __attribute__((const)) float __ocml_cvtrtp_f32_s64(int64_t); +extern "C" __device__ __attribute__((const)) float __ocml_cvtrtz_f32_s64(int64_t); +extern "C" __device__ __attribute__((const)) float __ocml_cvtrtn_f32_u64(uint64_t); +extern "C" __device__ __attribute__((const)) float __ocml_cvtrtp_f32_u64(uint64_t); +extern "C" __device__ __attribute__((const)) float __ocml_cvtrtz_f32_u64(uint64_t); +extern "C" __device__ __attribute__((const)) double __ocml_cvtrtn_f64_s64(int64_t); +extern "C" __device__ __attribute__((const)) double __ocml_cvtrtp_f64_s64(int64_t); +extern "C" __device__ __attribute__((const)) double __ocml_cvtrtz_f64_s64(int64_t); +extern "C" __device__ __attribute__((const)) double __ocml_cvtrtn_f64_u64(uint64_t); +extern "C" __device__ __attribute__((const)) double __ocml_cvtrtp_f64_u64(uint64_t); +extern "C" __device__ __attribute__((const)) double __ocml_cvtrtz_f64_u64(uint64_t); + +extern "C" __device__ __attribute__((convergent)) void __ockl_gws_init(uint nwm1, uint rid); +extern "C" __device__ __attribute__((convergent)) void __ockl_gws_barrier(uint nwm1, uint rid); + +extern "C" __device__ __attribute__((const)) uint32_t __ockl_lane_u32(); +extern "C" __device__ __attribute__((const)) int __ockl_grid_is_valid(void); +extern "C" __device__ __attribute__((convergent)) void __ockl_grid_sync(void); +extern "C" __device__ __attribute__((const)) uint __ockl_multi_grid_num_grids(void); +extern "C" __device__ __attribute__((const)) uint __ockl_multi_grid_grid_rank(void); +extern "C" __device__ __attribute__((const)) uint __ockl_multi_grid_size(void); +extern "C" __device__ __attribute__((const)) uint __ockl_multi_grid_thread_rank(void); +extern "C" __device__ __attribute__((const)) int __ockl_multi_grid_is_valid(void); +extern "C" __device__ __attribute__((convergent)) void __ockl_multi_grid_sync(void); + +extern "C" __device__ void __ockl_atomic_add_noret_f32(float*, float); + +extern "C" __device__ __attribute__((convergent)) int __ockl_wgred_add_i32(int a); +extern "C" __device__ __attribute__((convergent)) int __ockl_wgred_and_i32(int a); +extern "C" __device__ __attribute__((convergent)) int __ockl_wgred_or_i32(int a); + +extern "C" __device__ uint64_t __ockl_fprintf_stderr_begin(); +extern "C" __device__ uint64_t __ockl_fprintf_append_args(uint64_t msg_desc, uint32_t num_args, + uint64_t value0, uint64_t value1, + uint64_t value2, uint64_t value3, + uint64_t value4, uint64_t value5, + uint64_t value6, uint32_t is_last); +extern "C" __device__ uint64_t __ockl_fprintf_append_string_n(uint64_t msg_desc, const char* data, + uint64_t length, uint32_t is_last); + +// Introduce local address space +#define __local __attribute__((address_space(3))) + +#ifdef __HIP_DEVICE_COMPILE__ +__device__ inline static __local void* __to_local(unsigned x) { return (__local void*)x; } +#endif //__HIP_DEVICE_COMPILE__ + +// Using hip.amdgcn.bc - sync threads +#define __CLK_LOCAL_MEM_FENCE 0x01 +typedef unsigned __cl_mem_fence_flags; + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/functional_grid_launch.hpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/functional_grid_launch.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6f2857de46d8d9ffc4f92aa9375234a8aadf6294 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/functional_grid_launch.hpp @@ -0,0 +1,218 @@ +/* +Copyright (c) 2015 - 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. +*/ + +#pragma once + +#include "concepts.hpp" +#include "helpers.hpp" +#include "program_state.hpp" +#include "hip_runtime_api.h" + +#include +#include +#include +#include +#include +#include + +hipError_t ihipExtLaunchMultiKernelMultiDevice(hipLaunchParams* launchParamsList, int numDevices, + unsigned int flags, hip_impl::program_state& ps); + +hipError_t hipLaunchCooperativeKernel(const void* f, dim3 gridDim, + dim3 blockDim, void** args, + size_t sharedMem, hipStream_t stream, + hip_impl::program_state& ps); + +hipError_t hipLaunchCooperativeKernelMultiDevice(hipLaunchParams* launchParamsList, + int numDevices, + unsigned int flags, + hip_impl::program_state& ps); + +#pragma GCC visibility push(hidden) + +namespace hip_impl { +template {}>::type* = nullptr> +inline T round_up_to_next_multiple_nonnegative(T x, T y) { + T tmp = x + y - 1; + return tmp - tmp % y; +} + +template < + std::size_t n, + typename... Ts, + typename std::enable_if::type* = nullptr> +inline hip_impl::kernarg make_kernarg( + const std::tuple&, + const kernargs_size_align&, + hip_impl::kernarg kernarg) { + return kernarg; +} + +template < + std::size_t n, + typename... Ts, + typename std::enable_if::type* = nullptr> +inline hip_impl::kernarg make_kernarg( + const std::tuple& formals, + const kernargs_size_align& size_align, + hip_impl::kernarg kernarg) { + using T = typename std::tuple_element>::type; + + static_assert( + !std::is_reference{}, + "A __global__ function cannot have a reference as one of its " + "arguments."); + #if defined(HIP_STRICT) + static_assert( + std::is_trivially_copyable{}, + "Only TriviallyCopyable types can be arguments to a __global__ " + "function"); + #endif + + kernarg.resize(round_up_to_next_multiple_nonnegative( + kernarg.size(), size_align.alignment(n)) + size_align.size(n)); + + std::memcpy( + kernarg.data() + kernarg.size() - size_align.size(n), + &std::get(formals), + size_align.size(n)); + return make_kernarg(formals, size_align, std::move(kernarg)); +} + +template +inline hip_impl::kernarg make_kernarg( + void (*kernel)(Formals...), std::tuple actuals) { + static_assert(sizeof...(Formals) == sizeof...(Actuals), + "The count of formal arguments must match the count of actuals."); + + if (sizeof...(Formals) == 0) return {}; + + std::tuple to_formals{std::move(actuals)}; + hip_impl::kernarg kernarg; + kernarg.reserve(sizeof(to_formals)); + + auto& ps = hip_impl::get_program_state(); + return make_kernarg<0>(to_formals, + ps.get_kernargs_size_align( + reinterpret_cast(kernel)), + std::move(kernarg)); +} + + +HIP_INTERNAL_EXPORTED_API hsa_agent_t target_agent(hipStream_t stream); + +inline +__attribute__((visibility("hidden"))) +void hipLaunchKernelGGLImpl( + std::uintptr_t function_address, + const dim3& numBlocks, + const dim3& dimBlocks, + std::uint32_t sharedMemBytes, + hipStream_t stream, + void** kernarg) { + + const auto& kd = hip_impl::get_program_state().kernel_descriptor(function_address, + target_agent(stream)); + + hipModuleLaunchKernel(kd, numBlocks.x, numBlocks.y, numBlocks.z, + dimBlocks.x, dimBlocks.y, dimBlocks.z, sharedMemBytes, + stream, nullptr, kernarg); +} +} // Namespace hip_impl. + + +template +inline +hipError_t hipOccupancyMaxPotentialBlockSize(int* gridSize, int* blockSize, + T kernel, size_t dynSharedMemPerBlk = 0, int blockSizeLimit = 0) { + + using namespace hip_impl; + + hip_impl::hip_init(); + auto f = get_program_state().kernel_descriptor(reinterpret_cast(kernel), + target_agent(0)); + + return hipModuleOccupancyMaxPotentialBlockSize(gridSize, blockSize, f, + dynSharedMemPerBlk, blockSizeLimit); +} + +template +inline +hipError_t hipOccupancyMaxPotentialBlockSizeWithFlags(int* gridSize, int* blockSize, + T kernel, size_t dynSharedMemPerBlk = 0, int blockSizeLimit = 0, unsigned int flags = 0 ) { + + using namespace hip_impl; + + hip_impl::hip_init(); + if(flags != hipOccupancyDefault) return hipErrorNotSupported; + auto f = get_program_state().kernel_descriptor(reinterpret_cast(kernel), + target_agent(0)); + + return hipModuleOccupancyMaxPotentialBlockSize(gridSize, blockSize, f, + dynSharedMemPerBlk, blockSizeLimit); +} + +template +inline +void hipLaunchKernelGGL(F kernel, const dim3& numBlocks, const dim3& dimBlocks, + std::uint32_t sharedMemBytes, hipStream_t stream, + Args... args) { + hip_impl::hip_init(); + auto kernarg = hip_impl::make_kernarg(kernel, std::tuple{std::move(args)...}); + std::size_t kernarg_size = kernarg.size(); + + void* config[]{ + HIP_LAUNCH_PARAM_BUFFER_POINTER, + kernarg.data(), + HIP_LAUNCH_PARAM_BUFFER_SIZE, + &kernarg_size, + HIP_LAUNCH_PARAM_END}; + + hip_impl::hipLaunchKernelGGLImpl(reinterpret_cast(kernel), + numBlocks, dimBlocks, sharedMemBytes, + stream, &config[0]); +} + +template +inline +__attribute__((visibility("hidden"))) +hipError_t hipLaunchCooperativeKernel(F f, dim3 gridDim, dim3 blockDim, + void** args, size_t sharedMem, + hipStream_t stream) { + hip_impl::hip_init(); + auto& ps = hip_impl::get_program_state(); + return hipLaunchCooperativeKernel(reinterpret_cast(f), gridDim, + blockDim, args, sharedMem, stream, ps); +} + +inline +__attribute__((visibility("hidden"))) +hipError_t hipLaunchCooperativeKernelMultiDevice(hipLaunchParams* launchParamsList, + int numDevices, + unsigned int flags) { + + hip_impl::hip_init(); + auto& ps = hip_impl::get_program_state(); + return hipLaunchCooperativeKernelMultiDevice(launchParamsList, numDevices, flags, ps); +} + +#pragma GCC visibility pop diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/grid_launch.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/grid_launch.h new file mode 100644 index 0000000000000000000000000000000000000000..22841a5657083dbef747f4b008c9e3ee197dd2c1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/grid_launch.h @@ -0,0 +1,67 @@ +#pragma once + +#include + +#include + +#define GRID_LAUNCH_VERSION 20 + +// Extern definitions +namespace hc{ +class completion_future; +class accelerator_view; +} + + +// 3 dim structure for groups and grids. +typedef struct gl_dim3 +{ + int x,y,z; + gl_dim3(uint32_t _x=1, uint32_t _y=1, uint32_t _z=1) : x(_x), y(_y), z(_z) {}; +} gl_dim3; + +typedef enum gl_barrier_bit { + barrier_bit_queue_default, + barrier_bit_none, + barrier_bit_wait, +} gl_barrier_bit; + + +// grid_launch_parm contains information used to launch the kernel. +typedef struct grid_launch_parm +{ + //! Grid dimensions + gl_dim3 grid_dim; + + //! Group dimensions + gl_dim3 group_dim; + + //! Amount of dynamic group memory to use with the kernel launch. + //! This memory is in addition to the amount used statically in the kernel. + unsigned int dynamic_group_mem_bytes; + + //! Control setting of barrier bit on per-packet basis: + //! See gl_barrier_bit description. + //! Placeholder, is not used to control packet dispatch yet + enum gl_barrier_bit barrier_bit; + + //! Value of packet fences to apply to launch. + //! The correspond to the value of bits 9:14 in the AQL packet, + //! see HSA_PACKET_HEADER_ACQUIRE_FENCE_SCOPE and hsa_fence_scope_t. + unsigned int launch_fence; + + //! Pointer to the accelerator_view where the kernel should execute. + //! If NULL, the default view on the default accelerator is used. + hc::accelerator_view *av; + + //! Pointer to the completion_future used to track the status of the command. + //! If NULL, the command does not write status. In this case, + //! synchronization can be enforced with queue-level waits or + //! waiting on younger commands. + hc::completion_future *cf; + + grid_launch_parm() = default; +} grid_launch_parm; + + +extern void init_grid_launch(grid_launch_parm *gl); diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/grid_launch.hpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/grid_launch.hpp new file mode 100644 index 0000000000000000000000000000000000000000..04ce7e03664bce142fe3f081d44f8d677ebce5a5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/grid_launch.hpp @@ -0,0 +1,50 @@ +#pragma once + +#include "grid_launch.h" +#include "hc.hpp" + +class grid_launch_parm_cxx : public grid_launch_parm +{ +public: + grid_launch_parm_cxx() = default; + + // customized serialization: don't need av and cf in kernel + __attribute__((annotate("serialize"))) + void __cxxamp_serialize(Kalmar::Serialize& s) const { + s.Append(sizeof(int), &grid_dim.x); + s.Append(sizeof(int), &grid_dim.y); + s.Append(sizeof(int), &grid_dim.z); + s.Append(sizeof(int), &group_dim.x); + s.Append(sizeof(int), &group_dim.y); + s.Append(sizeof(int), &group_dim.z); + } + + __attribute__((annotate("user_deserialize"))) + grid_launch_parm_cxx(int grid_dim_x, int grid_dim_y, int grid_dim_z, + int group_dim_x, int group_dim_y, int group_dim_z) { + grid_dim.x = grid_dim_x; + grid_dim.y = grid_dim_y; + grid_dim.z = grid_dim_z; + group_dim.x = group_dim_x; + group_dim.y = group_dim_y; + group_dim.z = group_dim_z; + } +}; + + +extern inline void grid_launch_init(grid_launch_parm *lp) { + lp->grid_dim.x = lp->grid_dim.y = lp->grid_dim.z = 1; + + lp->group_dim.x = lp->group_dim.y = lp->group_dim.z = 1; + + lp->dynamic_group_mem_bytes = 0; + + lp->barrier_bit = barrier_bit_queue_default; + lp->launch_fence = -1; + + // TODO - set to NULL? + static hc::accelerator_view av = hc::accelerator().get_default_view(); + lp->av = &av; + lp->cf = NULL; +} + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/grid_launch_GGL.hpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/grid_launch_GGL.hpp new file mode 100644 index 0000000000000000000000000000000000000000..df5949d7d00b135f6b4f2be7af45653568b388c7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/grid_launch_GGL.hpp @@ -0,0 +1,26 @@ +/* +Copyright (c) 2015 - 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. +*/ +#pragma once + +#if GENERIC_GRID_LAUNCH == 1 +#include "macro_based_grid_launch.hpp" +#endif // GENERIC_GRID_LAUNCH \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/helpers.hpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/helpers.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5f7935c1ec83b092ad595b3c3b5456a5d7e89f21 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/helpers.hpp @@ -0,0 +1,137 @@ +/* +Copyright (c) 2015 - 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. +*/ + +#pragma once +#include "concepts.hpp" + +#include // For std::conditional, std::decay, std::enable_if, + // std::false_type, std result_of and std::true_type. +#include // For std::declval. + +#ifdef __has_include // Check if __has_include is present +# if __has_include() // Check for version header +# include +# if defined(__cpp_lib_is_invocable) && !defined(HIP_HAS_INVOCABLE) +# define HIP_HAS_INVOCABLE __cpp_lib_is_invocable +# endif +# if defined(__cpp_lib_result_of_sfinae) && !defined(HIP_HAS_RESULT_OF_SFINAE) +# define HIP_HAS_RESULT_OF_SFINAE __cpp_lib_result_of_sfinae +# endif +# endif +#endif + +#ifndef HIP_HAS_INVOCABLE +#define HIP_HAS_INVOCABLE 0 +#endif + +#ifndef HIP_HAS_RESULT_OF_SFINAE +#define HIP_HAS_RESULT_OF_SFINAE 0 +#endif + +namespace std { // TODO: these should be removed as soon as possible. +#if (__cplusplus < 201406L) +#if (__cplusplus < 201402L) +template +using enable_if_t = typename enable_if::type; +template +using conditional_t = typename conditional::type; +template +using decay_t = typename decay::type; +template +using result_of_t = typename result_of::type; +template +using remove_reference_t = typename remove_reference::type; +#endif +#endif +} // namespace std + +namespace hip_impl { +template +using void_t_ = void; + +#if HIP_HAS_INVOCABLE +template +struct is_callable_impl; + +template +struct is_callable_impl : std::is_invocable {}; +#elif HIP_HAS_RESULT_OF_SFINAE +template +struct is_callable_impl : std::false_type {}; + +template +struct is_callable_impl::type > > : std::true_type {}; +#else +template +auto simple_invoke(T Base::*pmd, Derived&& ref) +-> decltype(static_cast(ref).*pmd); + +template +auto simple_invoke(PMD&& pmd, Pointer&& ptr) +-> decltype((*static_cast(ptr)).*static_cast(pmd)); + +template +auto simple_invoke(T Base::*pmd, const std::reference_wrapper& ref) +-> decltype(ref.get().*pmd); + +template +auto simple_invoke(T Base::*pmf, Derived&& ref, Args&&... args) +-> decltype((static_cast(ref).*pmf)(static_cast(args)...)); + +template +auto simple_invoke(PMF&& pmf, Pointer&& ptr, Args&&... args) +-> decltype(((*static_cast(ptr)).*static_cast(pmf))(static_cast(args)...)); + +template +auto simple_invoke(T Base::*pmf, const std::reference_wrapper& ref, Args&&... args) +-> decltype((ref.get().*pmf)(static_cast(args)...)); + +template +auto simple_invoke(F&& f, Ts&&... xs) +-> decltype(f(static_cast(xs)...)); + +template +struct is_callable_impl : std::false_type {}; + +template +struct is_callable_impl(), std::declval()...))> > + : std::true_type {}; + +#endif + +template +struct is_callable : is_callable_impl {}; + +#define count_macro_args_impl_hip_(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, \ + _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, \ + _26, _27, _28, _29, _30, _31, _n, ...) \ + _n +#define count_macro_args_hip_(...) \ + count_macro_args_impl_hip_(, ##__VA_ARGS__, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, \ + 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, \ + 0) + +#define overloaded_macro_expand_hip_(macro, arg_cnt) macro##arg_cnt +#define overload_macro_impl_hip_(macro, arg_cnt) overloaded_macro_expand_hip_(macro, arg_cnt) +#define overload_macro_hip_(macro, ...) \ + overload_macro_impl_hip_(macro, count_macro_args_hip_(__VA_ARGS__))(__VA_ARGS__) +} // namespace hip_impl diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_api_trace.hpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_api_trace.hpp new file mode 100644 index 0000000000000000000000000000000000000000..768c62e0985799905e2ab9681ec7b6fac4cd7892 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_api_trace.hpp @@ -0,0 +1,1446 @@ +/* + Copyright (c) 2023 - 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. + */ +#pragma once + +#include + +// Define some version macros for the API table. Use similar naming conventions to HSA-runtime +// (MAJOR and STEP versions). Three groups at this time: +// +// (A) HIP_API_TABLE_* defines for versioning for API table structure +// (B) HIP_RUNTIME_API_TABLE_* defines for versioning the HipDispatchTable struct +// (C) HIP_COMPILER_API_TABLE_* defines for versioning the HipCompilerDispatchTable struct +// +// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! IMPORTANT !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +// +// 1. When new functions are added to the API table, always add the new function pointer to the +// end of the table and increment the dispatch table's step version number. NEVER re-arrange +// the order of the member variables in a dispatch table. This will break the ABI. +// 2. In dire circumstances, if the type of an existing member variable in a dispatch +// table has be changed because a data type has been changed/removed, increment the dispatch +// table's major version number. If the function pointer type can no longer be declared, DO +// NOT REMOVE IT! Make the function pointer type void* and have it always be set to a nullptr. +// +// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +// +// The major version number should (ideally) never need to be incremented. +// - Increment the HIP_API_TABLE_MAJOR_VERSION for fundamental changes to the API table structs. +// - Increment the HIP_RUNTIME_API_TABLE_MAJOR_VERSION for fundamental changes to the +// HipDispatchTable struct, such as a *change* to type/name an existing member variable. DO NOT +// REMOVE IT. +// - Increment the HIP_COMPILER_API_TABLE_MAJOR_VERSION for fundamental changes to the +// HipCompilerDispatchTable struct, such as a *change* to type/name an existing member variable. +// DO NOT REMOVE IT. +#define HIP_API_TABLE_MAJOR_VERSION 0 +#define HIP_COMPILER_API_TABLE_MAJOR_VERSION 0 +#define HIP_RUNTIME_API_TABLE_MAJOR_VERSION 0 + +// The step version number should be changed whenever the size of the API table struct(s) change. +// - Increment the HIP_API_TABLE_STEP_VERSION when/if new API table structs are added +// - Increment the HIP_RUNTIME_API_TABLE_STEP_VERSION when new runtime API functions are added +// - Increment the HIP_COMPILER_API_TABLE_STEP_VERSION when new compiler API functions are added +// - Reset any of the *_STEP_VERSION defines to zero if the corresponding *_MAJOR_VERSION increases +#define HIP_API_TABLE_STEP_VERSION 0 +#define HIP_COMPILER_API_TABLE_STEP_VERSION 0 +#define HIP_RUNTIME_API_TABLE_STEP_VERSION 3 + +// HIP API interface +typedef hipError_t (*t___hipPopCallConfiguration)(dim3* gridDim, dim3* blockDim, size_t* sharedMem, + hipStream_t* stream); +typedef hipError_t (*t___hipPushCallConfiguration)(dim3 gridDim, dim3 blockDim, size_t sharedMem, + hipStream_t stream); +typedef void** (*t___hipRegisterFatBinary)(const void* data); +typedef void (*t___hipRegisterFunction)(void** modules, const void* hostFunction, + char* deviceFunction, const char* deviceName, + unsigned int threadLimit, uint3* tid, uint3* bid, + dim3* blockDim, dim3* gridDim, int* wSize); +typedef void (*t___hipRegisterManagedVar)(void* hipModule, void** pointer, void* init_value, + const char* name, size_t size, unsigned align); +typedef void (*t___hipRegisterSurface)(void** modules, void* var, char* hostVar, + char* deviceVar, int type, int ext); +typedef void (*t___hipRegisterTexture)(void** modules, void* var, char* hostVar, + char* deviceVar, int type, int norm, int ext); +typedef void (*t___hipRegisterVar)(void** modules, void* var, char* hostVar, + char* deviceVar, int ext, size_t size, int constant, int global); +typedef void (*t___hipUnregisterFatBinary)(void** modules); + +typedef const char* (*t_hipApiName)(uint32_t id); +typedef hipError_t (*t_hipArray3DCreate)(hipArray_t* array, + const HIP_ARRAY3D_DESCRIPTOR* pAllocateArray); +typedef hipError_t (*t_hipArray3DGetDescriptor)(HIP_ARRAY3D_DESCRIPTOR* pArrayDescriptor, + hipArray_t array); +typedef hipError_t (*t_hipArrayCreate)(hipArray_t* pHandle, + const HIP_ARRAY_DESCRIPTOR* pAllocateArray); +typedef hipError_t (*t_hipArrayDestroy)(hipArray_t array); +typedef hipError_t (*t_hipArrayGetDescriptor)(HIP_ARRAY_DESCRIPTOR* pArrayDescriptor, + hipArray_t array); +typedef hipError_t (*t_hipArrayGetInfo)(hipChannelFormatDesc* desc, hipExtent* extent, + unsigned int* flags, hipArray_t array); +typedef hipError_t (*t_hipBindTexture)(size_t* offset, const textureReference* tex, + const void* devPtr, const hipChannelFormatDesc* desc, + size_t size); +typedef hipError_t (*t_hipBindTexture2D)(size_t* offset, const textureReference* tex, + const void* devPtr, const hipChannelFormatDesc* desc, + size_t width, size_t height, size_t pitch); +typedef hipError_t (*t_hipBindTextureToArray)(const textureReference* tex, hipArray_const_t array, + const hipChannelFormatDesc* desc); +typedef hipError_t (*t_hipBindTextureToMipmappedArray)(const textureReference* tex, + hipMipmappedArray_const_t mipmappedArray, + const hipChannelFormatDesc* desc); +typedef hipError_t (*t_hipChooseDevice)(int* device, const hipDeviceProp_t* prop); +typedef hipError_t (*t_hipChooseDeviceR0000)(int* device, const hipDeviceProp_tR0000* properties); +typedef hipError_t (*t_hipConfigureCall)(dim3 gridDim, dim3 blockDim, size_t sharedMem, + hipStream_t stream); +typedef hipError_t (*t_hipCreateSurfaceObject)(hipSurfaceObject_t* pSurfObject, + const hipResourceDesc* pResDesc); +typedef hipError_t (*t_hipCreateTextureObject)(hipTextureObject_t* pTexObject, + const hipResourceDesc* pResDesc, + const hipTextureDesc* pTexDesc, + const struct hipResourceViewDesc* pResViewDesc); +typedef hipError_t (*t_hipCtxCreate)(hipCtx_t* ctx, unsigned int flags, hipDevice_t device); +typedef hipError_t (*t_hipCtxDestroy)(hipCtx_t ctx); +typedef hipError_t (*t_hipCtxDisablePeerAccess)(hipCtx_t peerCtx); +typedef hipError_t (*t_hipCtxEnablePeerAccess)(hipCtx_t peerCtx, unsigned int flags); +typedef hipError_t (*t_hipCtxGetApiVersion)(hipCtx_t ctx, int* apiVersion); +typedef hipError_t (*t_hipCtxGetCacheConfig)(hipFuncCache_t* cacheConfig); +typedef hipError_t (*t_hipCtxGetCurrent)(hipCtx_t* ctx); +typedef hipError_t (*t_hipCtxGetDevice)(hipDevice_t* device); +typedef hipError_t (*t_hipCtxGetFlags)(unsigned int* flags); +typedef hipError_t (*t_hipCtxGetSharedMemConfig)(hipSharedMemConfig* pConfig); +typedef hipError_t (*t_hipCtxPopCurrent)(hipCtx_t* ctx); +typedef hipError_t (*t_hipCtxPushCurrent)(hipCtx_t ctx); +typedef hipError_t (*t_hipCtxSetCacheConfig)(hipFuncCache_t cacheConfig); +typedef hipError_t (*t_hipCtxSetCurrent)(hipCtx_t ctx); +typedef hipError_t (*t_hipCtxSetSharedMemConfig)(hipSharedMemConfig config); +typedef hipError_t (*t_hipCtxSynchronize)(void); +typedef hipError_t (*t_hipDestroyExternalMemory)(hipExternalMemory_t extMem); +typedef hipError_t (*t_hipDestroyExternalSemaphore)(hipExternalSemaphore_t extSem); +typedef hipError_t (*t_hipDestroySurfaceObject)(hipSurfaceObject_t surfaceObject); +typedef hipError_t (*t_hipDestroyTextureObject)(hipTextureObject_t textureObject); +typedef hipError_t (*t_hipDeviceCanAccessPeer)(int* canAccessPeer, int deviceId, int peerDeviceId); +typedef hipError_t (*t_hipDeviceComputeCapability)(int* major, int* minor, hipDevice_t device); +typedef hipError_t (*t_hipDeviceDisablePeerAccess)(int peerDeviceId); +typedef hipError_t (*t_hipDeviceEnablePeerAccess)(int peerDeviceId, unsigned int flags); +typedef hipError_t (*t_hipDeviceGet)(hipDevice_t* device, int ordinal); +typedef hipError_t (*t_hipDeviceGetAttribute)(int* pi, hipDeviceAttribute_t attr, int deviceId); +typedef hipError_t (*t_hipDeviceGetByPCIBusId)(int* device, const char* pciBusId); +typedef hipError_t (*t_hipDeviceGetCacheConfig)(hipFuncCache_t* cacheConfig); +typedef hipError_t (*t_hipDeviceGetDefaultMemPool)(hipMemPool_t* mem_pool, int device); +typedef hipError_t (*t_hipDeviceGetGraphMemAttribute)(int device, hipGraphMemAttributeType attr, + void* value); +typedef hipError_t (*t_hipDeviceGetLimit)(size_t* pValue, enum hipLimit_t limit); +typedef hipError_t (*t_hipDeviceGetMemPool)(hipMemPool_t* mem_pool, int device); +typedef hipError_t (*t_hipDeviceGetName)(char* name, int len, hipDevice_t device); +typedef hipError_t (*t_hipDeviceGetP2PAttribute)(int* value, hipDeviceP2PAttr attr, int srcDevice, + int dstDevice); +typedef hipError_t (*t_hipDeviceGetPCIBusId)(char* pciBusId, int len, int device); +typedef hipError_t (*t_hipDeviceGetSharedMemConfig)(hipSharedMemConfig* pConfig); +typedef hipError_t (*t_hipDeviceGetStreamPriorityRange)(int* leastPriority, int* greatestPriority); +typedef hipError_t (*t_hipDeviceGetUuid)(hipUUID* uuid, hipDevice_t device); +typedef hipError_t (*t_hipDeviceGraphMemTrim)(int device); +typedef hipError_t (*t_hipDevicePrimaryCtxGetState)(hipDevice_t dev, unsigned int* flags, + int* active); +typedef hipError_t (*t_hipDevicePrimaryCtxRelease)(hipDevice_t dev); +typedef hipError_t (*t_hipDevicePrimaryCtxReset)(hipDevice_t dev); +typedef hipError_t (*t_hipDevicePrimaryCtxRetain)(hipCtx_t* pctx, hipDevice_t dev); +typedef hipError_t (*t_hipDevicePrimaryCtxSetFlags)(hipDevice_t dev, unsigned int flags); +typedef hipError_t (*t_hipDeviceReset)(void); +typedef hipError_t (*t_hipDeviceSetCacheConfig)(hipFuncCache_t cacheConfig); +typedef hipError_t (*t_hipDeviceSetGraphMemAttribute)(int device, hipGraphMemAttributeType attr, + void* value); +typedef hipError_t (*t_hipDeviceSetLimit)(enum hipLimit_t limit, size_t value); +typedef hipError_t (*t_hipDeviceSetMemPool)(int device, hipMemPool_t mem_pool); +typedef hipError_t (*t_hipDeviceSetSharedMemConfig)(hipSharedMemConfig config); +typedef hipError_t (*t_hipDeviceSynchronize)(void); +typedef hipError_t (*t_hipDeviceTotalMem)(size_t* bytes, hipDevice_t device); +typedef hipError_t (*t_hipDriverGetVersion)(int* driverVersion); +typedef hipError_t (*t_hipDrvGetErrorName)(hipError_t hipError, const char** errorString); +typedef hipError_t (*t_hipDrvGetErrorString)(hipError_t hipError, const char** errorString); +typedef hipError_t (*t_hipDrvGraphAddMemcpyNode)(hipGraphNode_t* phGraphNode, hipGraph_t hGraph, + const hipGraphNode_t* dependencies, + size_t numDependencies, + const HIP_MEMCPY3D* copyParams, hipCtx_t ctx); +typedef hipError_t (*t_hipDrvMemcpy2DUnaligned)(const hip_Memcpy2D* pCopy); +typedef hipError_t (*t_hipDrvMemcpy3D)(const HIP_MEMCPY3D* pCopy); +typedef hipError_t (*t_hipDrvMemcpy3DAsync)(const HIP_MEMCPY3D* pCopy, hipStream_t stream); +typedef hipError_t (*t_hipDrvPointerGetAttributes)(unsigned int numAttributes, + hipPointer_attribute* attributes, void** data, + hipDeviceptr_t ptr); +typedef hipError_t (*t_hipEventCreate)(hipEvent_t* event); +typedef hipError_t (*t_hipEventCreateWithFlags)(hipEvent_t* event, unsigned flags); +typedef hipError_t (*t_hipEventDestroy)(hipEvent_t event); +typedef hipError_t (*t_hipEventElapsedTime)(float* ms, hipEvent_t start, hipEvent_t stop); +typedef hipError_t (*t_hipEventQuery)(hipEvent_t event); +typedef hipError_t (*t_hipEventRecord)(hipEvent_t event, hipStream_t stream); +typedef hipError_t (*t_hipEventSynchronize)(hipEvent_t event); +typedef hipError_t (*t_hipExtGetLinkTypeAndHopCount)(int device1, int device2, uint32_t* linktype, + uint32_t* hopcount); +typedef hipError_t (*t_hipExtLaunchKernel)(const void* function_address, dim3 numBlocks, + dim3 dimBlocks, void** args, size_t sharedMemBytes, + hipStream_t stream, hipEvent_t startEvent, + hipEvent_t stopEvent, int flags); +typedef hipError_t (*t_hipExtLaunchMultiKernelMultiDevice)(hipLaunchParams* launchParamsList, + int numDevices, unsigned int flags); +typedef hipError_t (*t_hipExtMallocWithFlags)(void** ptr, size_t sizeBytes, unsigned int flags); +typedef hipError_t (*t_hipExtStreamCreateWithCUMask)(hipStream_t* stream, uint32_t cuMaskSize, + const uint32_t* cuMask); +typedef hipError_t (*t_hipExtStreamGetCUMask)(hipStream_t stream, uint32_t cuMaskSize, + uint32_t* cuMask); +typedef hipError_t (*t_hipExternalMemoryGetMappedBuffer)( + void** devPtr, hipExternalMemory_t extMem, const hipExternalMemoryBufferDesc* bufferDesc); +typedef hipError_t (*t_hipFree)(void* ptr); +typedef hipError_t (*t_hipFreeArray)(hipArray_t array); +typedef hipError_t (*t_hipFreeAsync)(void* dev_ptr, hipStream_t stream); +typedef hipError_t (*t_hipFreeHost)(void* ptr); +typedef hipError_t (*t_hipFreeMipmappedArray)(hipMipmappedArray_t mipmappedArray); +typedef hipError_t (*t_hipFuncGetAttribute)(int* value, hipFunction_attribute attrib, + hipFunction_t hfunc); +typedef hipError_t (*t_hipFuncGetAttributes)(struct hipFuncAttributes* attr, const void* func); +typedef hipError_t (*t_hipFuncSetAttribute)(const void* func, hipFuncAttribute attr, int value); +typedef hipError_t (*t_hipFuncSetCacheConfig)(const void* func, hipFuncCache_t config); +typedef hipError_t (*t_hipFuncSetSharedMemConfig)(const void* func, hipSharedMemConfig config); +typedef hipError_t (*t_hipGLGetDevices)(unsigned int* pHipDeviceCount, int* pHipDevices, + unsigned int hipDeviceCount, hipGLDeviceList deviceList); +typedef hipError_t (*t_hipGetChannelDesc)(hipChannelFormatDesc* desc, hipArray_const_t array); +typedef hipError_t (*t_hipGetDevice)(int* deviceId); +typedef hipError_t (*t_hipGetDeviceCount)(int* count); +typedef hipError_t (*t_hipGetDeviceFlags)(unsigned int* flags); +typedef hipError_t (*t_hipGetDevicePropertiesR0600)(hipDeviceProp_tR0600* prop, int device); +typedef hipError_t (*t_hipGetDevicePropertiesR0000)(hipDeviceProp_tR0000* prop, int device); +typedef const char* (*t_hipGetErrorName)(hipError_t hip_error); +typedef const char* (*t_hipGetErrorString)(hipError_t hipError); +typedef hipError_t (*t_hipGetLastError)(void); +typedef hipError_t (*t_hipGetMipmappedArrayLevel)(hipArray_t* levelArray, + hipMipmappedArray_const_t mipmappedArray, + unsigned int level); +typedef hipError_t (*t_hipGetSymbolAddress)(void** devPtr, const void* symbol); +typedef hipError_t (*t_hipGetSymbolSize)(size_t* size, const void* symbol); +typedef hipError_t (*t_hipGetTextureAlignmentOffset)(size_t* offset, + const textureReference* texref); +typedef hipError_t (*t_hipGetTextureObjectResourceDesc)(hipResourceDesc* pResDesc, + hipTextureObject_t textureObject); +typedef hipError_t (*t_hipGetTextureObjectResourceViewDesc)( + struct hipResourceViewDesc* pResViewDesc, hipTextureObject_t textureObject); +typedef hipError_t (*t_hipGetTextureObjectTextureDesc)(hipTextureDesc* pTexDesc, + hipTextureObject_t textureObject); +typedef hipError_t (*t_hipGetTextureReference)(const textureReference** texref, const void* symbol); +typedef hipError_t (*t_hipGraphAddChildGraphNode)(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, hipGraph_t childGraph); +typedef hipError_t (*t_hipGraphAddDependencies)(hipGraph_t graph, const hipGraphNode_t* from, + const hipGraphNode_t* to, size_t numDependencies); +typedef hipError_t (*t_hipGraphAddEmptyNode)(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies); +typedef hipError_t (*t_hipGraphAddEventRecordNode)(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, hipEvent_t event); +typedef hipError_t (*t_hipGraphAddEventWaitNode)(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, hipEvent_t event); +typedef hipError_t (*t_hipGraphAddHostNode)(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, + const hipHostNodeParams* pNodeParams); +typedef hipError_t (*t_hipGraphAddKernelNode)(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, + const hipKernelNodeParams* pNodeParams); +typedef hipError_t (*t_hipGraphAddMemAllocNode)(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, + hipMemAllocNodeParams* pNodeParams); +typedef hipError_t (*t_hipGraphAddMemFreeNode)(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, void* dev_ptr); +typedef hipError_t (*t_hipGraphAddMemcpyNode)(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, + const hipMemcpy3DParms* pCopyParams); +typedef hipError_t (*t_hipGraphAddMemcpyNode1D)(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, void* dst, const void* src, + size_t count, hipMemcpyKind kind); +typedef hipError_t (*t_hipGraphAddMemcpyNodeFromSymbol)(hipGraphNode_t* pGraphNode, + hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, void* dst, + const void* symbol, size_t count, + size_t offset, hipMemcpyKind kind); +typedef hipError_t (*t_hipGraphAddMemcpyNodeToSymbol)(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, const void* symbol, + const void* src, size_t count, size_t offset, + hipMemcpyKind kind); +typedef hipError_t (*t_hipGraphAddMemsetNode)(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, + const hipMemsetParams* pMemsetParams); + +typedef hipError_t (*t_hipGraphChildGraphNodeGetGraph)(hipGraphNode_t node, hipGraph_t* pGraph); +typedef hipError_t (*t_hipGraphClone)(hipGraph_t* pGraphClone, hipGraph_t originalGraph); +typedef hipError_t (*t_hipGraphCreate)(hipGraph_t* pGraph, unsigned int flags); +typedef hipError_t (*t_hipGraphDebugDotPrint)(hipGraph_t graph, const char* path, + unsigned int flags); +typedef hipError_t (*t_hipGraphDestroy)(hipGraph_t graph); +typedef hipError_t (*t_hipGraphDestroyNode)(hipGraphNode_t node); +typedef hipError_t (*t_hipGraphEventRecordNodeGetEvent)(hipGraphNode_t node, hipEvent_t* event_out); +typedef hipError_t (*t_hipGraphEventRecordNodeSetEvent)(hipGraphNode_t node, hipEvent_t event); +typedef hipError_t (*t_hipGraphEventWaitNodeGetEvent)(hipGraphNode_t node, hipEvent_t* event_out); +typedef hipError_t (*t_hipGraphEventWaitNodeSetEvent)(hipGraphNode_t node, hipEvent_t event); +typedef hipError_t (*t_hipGraphExecChildGraphNodeSetParams)(hipGraphExec_t hGraphExec, + hipGraphNode_t node, + hipGraph_t childGraph); +typedef hipError_t (*t_hipGraphExecDestroy)(hipGraphExec_t graphExec); +typedef hipError_t (*t_hipGraphExecEventRecordNodeSetEvent)(hipGraphExec_t hGraphExec, + hipGraphNode_t hNode, hipEvent_t event); +typedef hipError_t (*t_hipGraphExecEventWaitNodeSetEvent)(hipGraphExec_t hGraphExec, + hipGraphNode_t hNode, hipEvent_t event); +typedef hipError_t (*t_hipGraphExecHostNodeSetParams)(hipGraphExec_t hGraphExec, + hipGraphNode_t node, + const hipHostNodeParams* pNodeParams); +typedef hipError_t (*t_hipGraphExecKernelNodeSetParams)(hipGraphExec_t hGraphExec, + hipGraphNode_t node, + const hipKernelNodeParams* pNodeParams); +typedef hipError_t (*t_hipGraphExecMemcpyNodeSetParams)(hipGraphExec_t hGraphExec, + hipGraphNode_t node, + hipMemcpy3DParms* pNodeParams); +typedef hipError_t (*t_hipGraphExecMemcpyNodeSetParams1D)(hipGraphExec_t hGraphExec, + hipGraphNode_t node, void* dst, + const void* src, size_t count, + hipMemcpyKind kind); +typedef hipError_t (*t_hipGraphExecMemcpyNodeSetParamsFromSymbol)(hipGraphExec_t hGraphExec, + hipGraphNode_t node, void* dst, + const void* symbol, size_t count, + size_t offset, + hipMemcpyKind kind); +typedef hipError_t (*t_hipGraphExecMemcpyNodeSetParamsToSymbol)(hipGraphExec_t hGraphExec, + hipGraphNode_t node, + const void* symbol, const void* src, + size_t count, size_t offset, + hipMemcpyKind kind); +typedef hipError_t (*t_hipGraphExecMemsetNodeSetParams)(hipGraphExec_t hGraphExec, + hipGraphNode_t node, + const hipMemsetParams* pNodeParams); +typedef hipError_t (*t_hipGraphExecUpdate)(hipGraphExec_t hGraphExec, hipGraph_t hGraph, + hipGraphNode_t* hErrorNode_out, + hipGraphExecUpdateResult* updateResult_out); +typedef hipError_t (*t_hipGraphGetEdges)(hipGraph_t graph, hipGraphNode_t* from, hipGraphNode_t* to, + size_t* numEdges); +typedef hipError_t (*t_hipGraphGetNodes)(hipGraph_t graph, hipGraphNode_t* nodes, size_t* numNodes); +typedef hipError_t (*t_hipGraphGetRootNodes)(hipGraph_t graph, hipGraphNode_t* pRootNodes, + size_t* pNumRootNodes); +typedef hipError_t (*t_hipGraphHostNodeGetParams)(hipGraphNode_t node, + hipHostNodeParams* pNodeParams); +typedef hipError_t (*t_hipGraphHostNodeSetParams)(hipGraphNode_t node, + const hipHostNodeParams* pNodeParams); +typedef hipError_t (*t_hipGraphInstantiate)(hipGraphExec_t* pGraphExec, hipGraph_t graph, + hipGraphNode_t* pErrorNode, char* pLogBuffer, + size_t bufferSize); +typedef hipError_t (*t_hipGraphInstantiateWithFlags)(hipGraphExec_t* pGraphExec, hipGraph_t graph, + unsigned long long flags); +typedef hipError_t (*t_hipGraphKernelNodeCopyAttributes)(hipGraphNode_t hSrc, hipGraphNode_t hDst); +typedef hipError_t (*t_hipGraphKernelNodeGetAttribute)(hipGraphNode_t hNode, + hipKernelNodeAttrID attr, + hipKernelNodeAttrValue* value); +typedef hipError_t (*t_hipGraphKernelNodeGetParams)(hipGraphNode_t node, + hipKernelNodeParams* pNodeParams); +typedef hipError_t (*t_hipGraphKernelNodeSetAttribute)(hipGraphNode_t hNode, + hipKernelNodeAttrID attr, + const hipKernelNodeAttrValue* value); +typedef hipError_t (*t_hipGraphKernelNodeSetParams)(hipGraphNode_t node, + const hipKernelNodeParams* pNodeParams); +typedef hipError_t (*t_hipGraphLaunch)(hipGraphExec_t graphExec, hipStream_t stream); +typedef hipError_t (*t_hipGraphMemAllocNodeGetParams)(hipGraphNode_t node, + hipMemAllocNodeParams* pNodeParams); +typedef hipError_t (*t_hipGraphMemFreeNodeGetParams)(hipGraphNode_t node, void* dev_ptr); +typedef hipError_t (*t_hipGraphMemcpyNodeGetParams)(hipGraphNode_t node, + hipMemcpy3DParms* pNodeParams); +typedef hipError_t (*t_hipGraphMemcpyNodeSetParams)(hipGraphNode_t node, + const hipMemcpy3DParms* pNodeParams); +typedef hipError_t (*t_hipGraphMemcpyNodeSetParams1D)(hipGraphNode_t node, void* dst, + const void* src, size_t count, + hipMemcpyKind kind); +typedef hipError_t (*t_hipGraphMemcpyNodeSetParamsFromSymbol)(hipGraphNode_t node, void* dst, + const void* symbol, size_t count, + size_t offset, hipMemcpyKind kind); +typedef hipError_t (*t_hipGraphMemcpyNodeSetParamsToSymbol)(hipGraphNode_t node, const void* symbol, + const void* src, size_t count, + size_t offset, hipMemcpyKind kind); +typedef hipError_t (*t_hipGraphMemsetNodeGetParams)(hipGraphNode_t node, + hipMemsetParams* pNodeParams); +typedef hipError_t (*t_hipGraphMemsetNodeSetParams)(hipGraphNode_t node, + const hipMemsetParams* pNodeParams); +typedef hipError_t (*t_hipGraphNodeFindInClone)(hipGraphNode_t* pNode, hipGraphNode_t originalNode, + hipGraph_t clonedGraph); +typedef hipError_t (*t_hipGraphNodeGetDependencies)(hipGraphNode_t node, + hipGraphNode_t* pDependencies, + size_t* pNumDependencies); +typedef hipError_t (*t_hipGraphNodeGetDependentNodes)(hipGraphNode_t node, + hipGraphNode_t* pDependentNodes, + size_t* pNumDependentNodes); +typedef hipError_t (*t_hipGraphNodeGetEnabled)(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, + unsigned int* isEnabled); +typedef hipError_t (*t_hipGraphNodeGetType)(hipGraphNode_t node, hipGraphNodeType* pType); +typedef hipError_t (*t_hipGraphNodeSetEnabled)(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, + unsigned int isEnabled); +typedef hipError_t (*t_hipGraphReleaseUserObject)(hipGraph_t graph, hipUserObject_t object, + unsigned int count); +typedef hipError_t (*t_hipGraphRemoveDependencies)(hipGraph_t graph, const hipGraphNode_t* from, + const hipGraphNode_t* to, + size_t numDependencies); +typedef hipError_t (*t_hipGraphRetainUserObject)(hipGraph_t graph, hipUserObject_t object, + unsigned int count, unsigned int flags); +typedef hipError_t (*t_hipGraphUpload)(hipGraphExec_t graphExec, hipStream_t stream); +typedef hipError_t (*t_hipGraphicsGLRegisterBuffer)(hipGraphicsResource** resource, GLuint buffer, + unsigned int flags); +typedef hipError_t (*t_hipGraphicsGLRegisterImage)(hipGraphicsResource** resource, GLuint image, + GLenum target, unsigned int flags); +typedef hipError_t (*t_hipGraphicsMapResources)(int count, hipGraphicsResource_t* resources, + hipStream_t stream); +typedef hipError_t (*t_hipGraphicsResourceGetMappedPointer)(void** devPtr, size_t* size, + hipGraphicsResource_t resource); +typedef hipError_t (*t_hipGraphicsSubResourceGetMappedArray)(hipArray_t* array, + hipGraphicsResource_t resource, + unsigned int arrayIndex, + unsigned int mipLevel); +typedef hipError_t (*t_hipGraphicsUnmapResources)(int count, hipGraphicsResource_t* resources, + hipStream_t stream); +typedef hipError_t (*t_hipGraphicsUnregisterResource)(hipGraphicsResource_t resource); +typedef hipError_t (*t_hipHostAlloc)(void** ptr, size_t size, unsigned int flags); +typedef hipError_t (*t_hipHostFree)(void* ptr); +typedef hipError_t (*t_hipHostGetDevicePointer)(void** devPtr, void* hstPtr, unsigned int flags); +typedef hipError_t (*t_hipHostGetFlags)(unsigned int* flagsPtr, void* hostPtr); +typedef hipError_t (*t_hipHostMalloc)(void** ptr, size_t size, unsigned int flags); +typedef hipError_t (*t_hipHostRegister)(void* hostPtr, size_t sizeBytes, unsigned int flags); +typedef hipError_t (*t_hipHostUnregister)(void* hostPtr); +typedef hipError_t (*t_hipImportExternalMemory)(hipExternalMemory_t* extMem_out, + const hipExternalMemoryHandleDesc* memHandleDesc); +typedef hipError_t (*t_hipImportExternalSemaphore)( + hipExternalSemaphore_t* extSem_out, const hipExternalSemaphoreHandleDesc* semHandleDesc); +typedef hipError_t (*t_hipInit)(unsigned int flags); +typedef hipError_t (*t_hipIpcCloseMemHandle)(void* devPtr); +typedef hipError_t (*t_hipIpcGetEventHandle)(hipIpcEventHandle_t* handle, hipEvent_t event); +typedef hipError_t (*t_hipIpcGetMemHandle)(hipIpcMemHandle_t* handle, void* devPtr); +typedef hipError_t (*t_hipIpcOpenEventHandle)(hipEvent_t* event, hipIpcEventHandle_t handle); +typedef hipError_t (*t_hipIpcOpenMemHandle)(void** devPtr, hipIpcMemHandle_t handle, + unsigned int flags); +typedef const char* (*t_hipKernelNameRef)(const hipFunction_t f); +typedef const char* (*t_hipKernelNameRefByPtr)(const void* hostFunction, hipStream_t stream); +typedef hipError_t (*t_hipLaunchByPtr)(const void* func); +typedef hipError_t (*t_hipLaunchCooperativeKernel)(const void* f, dim3 gridDim, dim3 blockDimX, + void** kernelParams, unsigned int sharedMemBytes, + hipStream_t stream); +typedef hipError_t (*t_hipLaunchCooperativeKernelMultiDevice)(hipLaunchParams* launchParamsList, + int numDevices, unsigned int flags); +typedef hipError_t (*t_hipLaunchHostFunc)(hipStream_t stream, hipHostFn_t fn, void* userData); +typedef hipError_t (*t_hipLaunchKernel)(const void* function_address, dim3 numBlocks, + dim3 dimBlocks, void** args, size_t sharedMemBytes, + hipStream_t stream); +typedef hipError_t (*t_hipMalloc)(void** ptr, size_t size); +typedef hipError_t (*t_hipMalloc3D)(hipPitchedPtr* pitchedDevPtr, hipExtent extent); +typedef hipError_t (*t_hipMalloc3DArray)(hipArray_t* array, const struct hipChannelFormatDesc* desc, + struct hipExtent extent, unsigned int flags); +typedef hipError_t (*t_hipMallocArray)(hipArray_t* array, const hipChannelFormatDesc* desc, + size_t width, size_t height, unsigned int flags); +typedef hipError_t (*t_hipMallocAsync)(void** dev_ptr, size_t size, hipStream_t stream); +typedef hipError_t (*t_hipMallocFromPoolAsync)(void** dev_ptr, size_t size, hipMemPool_t mem_pool, + hipStream_t stream); +typedef hipError_t (*t_hipMallocHost)(void** ptr, size_t size); +typedef hipError_t (*t_hipMallocManaged)(void** dev_ptr, size_t size, unsigned int flags); +typedef hipError_t (*t_hipMallocMipmappedArray)(hipMipmappedArray_t* mipmappedArray, + const struct hipChannelFormatDesc* desc, + struct hipExtent extent, unsigned int numLevels, + unsigned int flags); +typedef hipError_t (*t_hipMallocPitch)(void** ptr, size_t* pitch, size_t width, size_t height); +typedef hipError_t (*t_hipMemAddressFree)(void* devPtr, size_t size); +typedef hipError_t (*t_hipMemAddressReserve)(void** ptr, size_t size, size_t alignment, void* addr, + unsigned long long flags); +typedef hipError_t (*t_hipMemAdvise)(const void* dev_ptr, size_t count, hipMemoryAdvise advice, + int device); +typedef hipError_t (*t_hipMemAllocHost)(void** ptr, size_t size); +typedef hipError_t (*t_hipMemAllocPitch)(hipDeviceptr_t* dptr, size_t* pitch, size_t widthInBytes, + size_t height, unsigned int elementSizeBytes); +typedef hipError_t (*t_hipMemCreate)(hipMemGenericAllocationHandle_t* handle, size_t size, + const hipMemAllocationProp* prop, unsigned long long flags); +typedef hipError_t (*t_hipMemExportToShareableHandle)(void* shareableHandle, + hipMemGenericAllocationHandle_t handle, + hipMemAllocationHandleType handleType, + unsigned long long flags); +typedef hipError_t (*t_hipMemGetAccess)(unsigned long long* flags, const hipMemLocation* location, + void* ptr); +typedef hipError_t (*t_hipMemGetAddressRange)(hipDeviceptr_t* pbase, size_t* psize, + hipDeviceptr_t dptr); +typedef hipError_t (*t_hipMemGetAllocationGranularity)(size_t* granularity, + const hipMemAllocationProp* prop, + hipMemAllocationGranularity_flags option); +typedef hipError_t (*t_hipMemGetAllocationPropertiesFromHandle)( + hipMemAllocationProp* prop, hipMemGenericAllocationHandle_t handle); +typedef hipError_t (*t_hipMemGetInfo)(size_t* free, size_t* total); +typedef hipError_t (*t_hipMemImportFromShareableHandle)(hipMemGenericAllocationHandle_t* handle, + void* osHandle, + hipMemAllocationHandleType shHandleType); +typedef hipError_t (*t_hipMemMap)(void* ptr, size_t size, size_t offset, + hipMemGenericAllocationHandle_t handle, unsigned long long flags); +typedef hipError_t (*t_hipMemMapArrayAsync)(hipArrayMapInfo* mapInfoList, unsigned int count, + hipStream_t stream); +typedef hipError_t (*t_hipMemPoolCreate)(hipMemPool_t* mem_pool, const hipMemPoolProps* pool_props); +typedef hipError_t (*t_hipMemPoolDestroy)(hipMemPool_t mem_pool); +typedef hipError_t (*t_hipMemPoolExportPointer)(hipMemPoolPtrExportData* export_data, + void* dev_ptr); +typedef hipError_t (*t_hipMemPoolExportToShareableHandle)(void* shared_handle, + hipMemPool_t mem_pool, + hipMemAllocationHandleType handle_type, + unsigned int flags); +typedef hipError_t (*t_hipMemPoolGetAccess)(hipMemAccessFlags* flags, hipMemPool_t mem_pool, + hipMemLocation* location); +typedef hipError_t (*t_hipMemPoolGetAttribute)(hipMemPool_t mem_pool, hipMemPoolAttr attr, + void* value); +typedef hipError_t (*t_hipMemPoolImportFromShareableHandle)(hipMemPool_t* mem_pool, + void* shared_handle, + hipMemAllocationHandleType handle_type, + unsigned int flags); +typedef hipError_t (*t_hipMemPoolImportPointer)(void** dev_ptr, hipMemPool_t mem_pool, + hipMemPoolPtrExportData* export_data); +typedef hipError_t (*t_hipMemPoolSetAccess)(hipMemPool_t mem_pool, + const hipMemAccessDesc* desc_list, size_t count); +typedef hipError_t (*t_hipMemPoolSetAttribute)(hipMemPool_t mem_pool, hipMemPoolAttr attr, + void* value); +typedef hipError_t (*t_hipMemPoolTrimTo)(hipMemPool_t mem_pool, size_t min_bytes_to_hold); +typedef hipError_t (*t_hipMemPrefetchAsync)(const void* dev_ptr, size_t count, int device, + hipStream_t stream); +typedef hipError_t (*t_hipMemPtrGetInfo)(void* ptr, size_t* size); +typedef hipError_t (*t_hipMemRangeGetAttribute)(void* data, size_t data_size, + hipMemRangeAttribute attribute, const void* dev_ptr, + size_t count); +typedef hipError_t (*t_hipMemRangeGetAttributes)(void** data, size_t* data_sizes, + hipMemRangeAttribute* attributes, + size_t num_attributes, const void* dev_ptr, + size_t count); +typedef hipError_t (*t_hipMemRelease)(hipMemGenericAllocationHandle_t handle); +typedef hipError_t (*t_hipMemRetainAllocationHandle)(hipMemGenericAllocationHandle_t* handle, + void* addr); +typedef hipError_t (*t_hipMemSetAccess)(void* ptr, size_t size, const hipMemAccessDesc* desc, + size_t count); +typedef hipError_t (*t_hipMemUnmap)(void* ptr, size_t size); +typedef hipError_t (*t_hipMemcpy)(void* dst, const void* src, size_t sizeBytes, hipMemcpyKind kind); +typedef hipError_t (*t_hipMemcpy2D)(void* dst, size_t dpitch, const void* src, size_t spitch, + size_t width, size_t height, hipMemcpyKind kind); +typedef hipError_t (*t_hipMemcpy2DAsync)(void* dst, size_t dpitch, const void* src, size_t spitch, + size_t width, size_t height, hipMemcpyKind kind, + hipStream_t stream); +typedef hipError_t (*t_hipMemcpy2DFromArray)(void* dst, size_t dpitch, hipArray_const_t src, + size_t wOffset, size_t hOffset, size_t width, + size_t height, hipMemcpyKind kind); +typedef hipError_t (*t_hipMemcpy2DFromArrayAsync)(void* dst, size_t dpitch, hipArray_const_t src, + size_t wOffset, size_t hOffset, size_t width, + size_t height, hipMemcpyKind kind, + hipStream_t stream); +typedef hipError_t (*t_hipMemcpy2DToArray)(hipArray_t dst, size_t wOffset, size_t hOffset, + const void* src, size_t spitch, size_t width, + size_t height, hipMemcpyKind kind); +typedef hipError_t (*t_hipMemcpy2DToArrayAsync)(hipArray_t dst, size_t wOffset, size_t hOffset, + const void* src, size_t spitch, size_t width, + size_t height, hipMemcpyKind kind, + hipStream_t stream); +typedef hipError_t (*t_hipMemcpy3D)(const struct hipMemcpy3DParms* p); +typedef hipError_t (*t_hipMemcpy3DAsync)(const struct hipMemcpy3DParms* p, hipStream_t stream); +typedef hipError_t (*t_hipMemcpyAsync)(void* dst, const void* src, size_t sizeBytes, + hipMemcpyKind kind, hipStream_t stream); +typedef hipError_t (*t_hipMemcpyAtoH)(void* dst, hipArray_t srcArray, size_t srcOffset, + size_t count); +typedef hipError_t (*t_hipMemcpyDtoD)(hipDeviceptr_t dst, hipDeviceptr_t src, size_t sizeBytes); +typedef hipError_t (*t_hipMemcpyDtoDAsync)(hipDeviceptr_t dst, hipDeviceptr_t src, size_t sizeBytes, + hipStream_t stream); +typedef hipError_t (*t_hipMemcpyDtoH)(void* dst, hipDeviceptr_t src, size_t sizeBytes); +typedef hipError_t (*t_hipMemcpyDtoHAsync)(void* dst, hipDeviceptr_t src, size_t sizeBytes, + hipStream_t stream); +typedef hipError_t (*t_hipMemcpyFromArray)(void* dst, hipArray_const_t srcArray, size_t wOffset, + size_t hOffset, size_t count, hipMemcpyKind kind); +typedef hipError_t (*t_hipMemcpyFromSymbol)(void* dst, const void* symbol, size_t sizeBytes, + size_t offset, hipMemcpyKind kind); +typedef hipError_t (*t_hipMemcpyFromSymbolAsync)(void* dst, const void* symbol, size_t sizeBytes, + size_t offset, hipMemcpyKind kind, + hipStream_t stream); +typedef hipError_t (*t_hipMemcpyHtoA)(hipArray_t dstArray, size_t dstOffset, const void* srcHost, + size_t count); +typedef hipError_t (*t_hipMemcpyHtoD)(hipDeviceptr_t dst, void* src, size_t sizeBytes); +typedef hipError_t (*t_hipMemcpyHtoDAsync)(hipDeviceptr_t dst, void* src, size_t sizeBytes, + hipStream_t stream); +typedef hipError_t (*t_hipMemcpyParam2D)(const hip_Memcpy2D* pCopy); +typedef hipError_t (*t_hipMemcpyParam2DAsync)(const hip_Memcpy2D* pCopy, hipStream_t stream); +typedef hipError_t (*t_hipMemcpyPeer)(void* dst, int dstDeviceId, const void* src, int srcDeviceId, + size_t sizeBytes); +typedef hipError_t (*t_hipMemcpyPeerAsync)(void* dst, int dstDeviceId, const void* src, + int srcDevice, size_t sizeBytes, hipStream_t stream); +typedef hipError_t (*t_hipMemcpyToArray)(hipArray_t dst, size_t wOffset, size_t hOffset, + const void* src, size_t count, hipMemcpyKind kind); +typedef hipError_t (*t_hipMemcpyToSymbol)(const void* symbol, const void* src, size_t sizeBytes, + size_t offset, hipMemcpyKind kind); +typedef hipError_t (*t_hipMemcpyToSymbolAsync)(const void* symbol, const void* src, + size_t sizeBytes, size_t offset, hipMemcpyKind kind, + hipStream_t stream); +typedef hipError_t (*t_hipMemcpyWithStream)(void* dst, const void* src, size_t sizeBytes, + hipMemcpyKind kind, hipStream_t stream); +typedef hipError_t (*t_hipMemset)(void* dst, int value, size_t sizeBytes); +typedef hipError_t (*t_hipMemset2D)(void* dst, size_t pitch, int value, size_t width, + size_t height); +typedef hipError_t (*t_hipMemset2DAsync)(void* dst, size_t pitch, int value, size_t width, + size_t height, hipStream_t stream); +typedef hipError_t (*t_hipMemset3D)(hipPitchedPtr pitchedDevPtr, int value, hipExtent extent); +typedef hipError_t (*t_hipMemset3DAsync)(hipPitchedPtr pitchedDevPtr, int value, hipExtent extent, + hipStream_t stream); +typedef hipError_t (*t_hipMemsetAsync)(void* dst, int value, size_t sizeBytes, hipStream_t stream); +typedef hipError_t (*t_hipMemsetD16)(hipDeviceptr_t dest, unsigned short value, size_t count); +typedef hipError_t (*t_hipMemsetD16Async)(hipDeviceptr_t dest, unsigned short value, size_t count, + hipStream_t stream); +typedef hipError_t (*t_hipMemsetD32)(hipDeviceptr_t dest, int value, size_t count); +typedef hipError_t (*t_hipMemsetD32Async)(hipDeviceptr_t dst, int value, size_t count, + hipStream_t stream); +typedef hipError_t (*t_hipMemsetD8)(hipDeviceptr_t dest, unsigned char value, size_t count); +typedef hipError_t (*t_hipMemsetD8Async)(hipDeviceptr_t dest, unsigned char value, size_t count, + hipStream_t stream); +typedef hipError_t (*t_hipMipmappedArrayCreate)(hipMipmappedArray_t* pHandle, + HIP_ARRAY3D_DESCRIPTOR* pMipmappedArrayDesc, + unsigned int numMipmapLevels); +typedef hipError_t (*t_hipMipmappedArrayDestroy)(hipMipmappedArray_t hMipmappedArray); +typedef hipError_t (*t_hipMipmappedArrayGetLevel)(hipArray_t* pLevelArray, + hipMipmappedArray_t hMipMappedArray, + unsigned int level); +typedef hipError_t (*t_hipModuleGetFunction)(hipFunction_t* function, hipModule_t module, + const char* kname); +typedef hipError_t (*t_hipModuleGetGlobal)(hipDeviceptr_t* dptr, size_t* bytes, hipModule_t hmod, + const char* name); +typedef hipError_t (*t_hipModuleGetTexRef)(textureReference** texRef, hipModule_t hmod, + const char* name); +typedef hipError_t (*t_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); +typedef hipError_t (*t_hipModuleLaunchCooperativeKernelMultiDevice)( + hipFunctionLaunchParams* launchParamsList, unsigned int numDevices, unsigned int flags); +typedef hipError_t (*t_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); +typedef hipError_t (*t_hipModuleLoad)(hipModule_t* module, const char* fname); +typedef hipError_t (*t_hipModuleLoadData)(hipModule_t* module, const void* image); +typedef hipError_t (*t_hipModuleLoadDataEx)(hipModule_t* module, const void* image, + unsigned int numOptions, hipJitOption* options, + void** optionValues); +typedef hipError_t (*t_hipModuleOccupancyMaxActiveBlocksPerMultiprocessor)( + int* numBlocks, hipFunction_t f, int blockSize, size_t dynSharedMemPerBlk); +typedef hipError_t (*t_hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags)( + int* numBlocks, hipFunction_t f, int blockSize, size_t dynSharedMemPerBlk, unsigned int flags); +typedef hipError_t (*t_hipModuleOccupancyMaxPotentialBlockSize)(int* gridSize, int* blockSize, + hipFunction_t f, + size_t dynSharedMemPerBlk, + int blockSizeLimit); +typedef hipError_t (*t_hipModuleOccupancyMaxPotentialBlockSizeWithFlags)( + int* gridSize, int* blockSize, hipFunction_t f, size_t dynSharedMemPerBlk, int blockSizeLimit, + unsigned int flags); +typedef hipError_t (*t_hipModuleUnload)(hipModule_t module); +typedef hipError_t (*t_hipOccupancyMaxActiveBlocksPerMultiprocessor)(int* numBlocks, const void* f, + int blockSize, + size_t dynSharedMemPerBlk); +typedef hipError_t (*t_hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags)( + int* numBlocks, const void* f, int blockSize, size_t dynSharedMemPerBlk, unsigned int flags); +typedef hipError_t (*t_hipOccupancyMaxPotentialBlockSize)(int* gridSize, int* blockSize, + const void* f, size_t dynSharedMemPerBlk, + int blockSizeLimit); +typedef hipError_t (*t_hipPeekAtLastError)(void); +typedef hipError_t (*t_hipPointerGetAttribute)(void* data, hipPointer_attribute attribute, + hipDeviceptr_t ptr); +typedef hipError_t (*t_hipPointerGetAttributes)(hipPointerAttribute_t* attributes, const void* ptr); +typedef hipError_t (*t_hipPointerSetAttribute)(const void* value, hipPointer_attribute attribute, + hipDeviceptr_t ptr); +typedef hipError_t (*t_hipProfilerStart)(); +typedef hipError_t (*t_hipProfilerStop)(); +typedef hipError_t (*t_hipRuntimeGetVersion)(int* runtimeVersion); +typedef hipError_t (*t_hipSetDevice)(int deviceId); +typedef hipError_t (*t_hipSetDeviceFlags)(unsigned flags); +typedef hipError_t (*t_hipSetupArgument)(const void* arg, size_t size, size_t offset); +typedef hipError_t (*t_hipSignalExternalSemaphoresAsync)( + const hipExternalSemaphore_t* extSemArray, const hipExternalSemaphoreSignalParams* paramsArray, + unsigned int numExtSems, hipStream_t stream); +typedef hipError_t (*t_hipStreamAddCallback)(hipStream_t stream, hipStreamCallback_t callback, + void* userData, unsigned int flags); +typedef hipError_t (*t_hipStreamAttachMemAsync)(hipStream_t stream, void* dev_ptr, size_t length, + unsigned int flags); +typedef hipError_t (*t_hipStreamBeginCapture)(hipStream_t stream, hipStreamCaptureMode mode); +typedef hipError_t (*t_hipStreamCreate)(hipStream_t* stream); +typedef hipError_t (*t_hipStreamCreateWithFlags)(hipStream_t* stream, unsigned int flags); +typedef hipError_t (*t_hipStreamCreateWithPriority)(hipStream_t* stream, unsigned int flags, + int priority); +typedef hipError_t (*t_hipStreamDestroy)(hipStream_t stream); +typedef hipError_t (*t_hipStreamEndCapture)(hipStream_t stream, hipGraph_t* pGraph); +typedef hipError_t (*t_hipStreamGetCaptureInfo)(hipStream_t stream, + hipStreamCaptureStatus* pCaptureStatus, + unsigned long long* pId); +typedef hipError_t (*t_hipStreamGetCaptureInfo_v2)( + hipStream_t stream, hipStreamCaptureStatus* captureStatus_out, unsigned long long* id_out, + hipGraph_t* graph_out, const hipGraphNode_t** dependencies_out, size_t* numDependencies_out); +typedef hipError_t (*t_hipStreamGetDevice)(hipStream_t stream, hipDevice_t* device); +typedef hipError_t (*t_hipStreamGetFlags)(hipStream_t stream, unsigned int* flags); +typedef hipError_t (*t_hipStreamGetPriority)(hipStream_t stream, int* priority); +typedef hipError_t (*t_hipStreamIsCapturing)(hipStream_t stream, + hipStreamCaptureStatus* pCaptureStatus); +typedef hipError_t (*t_hipStreamQuery)(hipStream_t stream); +typedef hipError_t (*t_hipStreamSynchronize)(hipStream_t stream); +typedef hipError_t (*t_hipStreamUpdateCaptureDependencies)(hipStream_t stream, + hipGraphNode_t* dependencies, + size_t numDependencies, + unsigned int flags); +typedef hipError_t (*t_hipStreamWaitEvent)(hipStream_t stream, hipEvent_t event, + unsigned int flags); +typedef hipError_t (*t_hipStreamWaitValue32)(hipStream_t stream, void* ptr, uint32_t value, + unsigned int flags, uint32_t mask); +typedef hipError_t (*t_hipStreamWaitValue64)(hipStream_t stream, void* ptr, uint64_t value, + unsigned int flags, uint64_t mask); +typedef hipError_t (*t_hipStreamWriteValue32)(hipStream_t stream, void* ptr, uint32_t value, + unsigned int flags); +typedef hipError_t (*t_hipStreamWriteValue64)(hipStream_t stream, void* ptr, uint64_t value, + unsigned int flags); +typedef hipError_t (*t_hipTexObjectCreate)(hipTextureObject_t* pTexObject, + const HIP_RESOURCE_DESC* pResDesc, + const HIP_TEXTURE_DESC* pTexDesc, + const HIP_RESOURCE_VIEW_DESC* pResViewDesc); +typedef hipError_t (*t_hipTexObjectDestroy)(hipTextureObject_t texObject); +typedef hipError_t (*t_hipTexObjectGetResourceDesc)(HIP_RESOURCE_DESC* pResDesc, + hipTextureObject_t texObject); +typedef hipError_t (*t_hipTexObjectGetResourceViewDesc)(HIP_RESOURCE_VIEW_DESC* pResViewDesc, + hipTextureObject_t texObject); +typedef hipError_t (*t_hipTexObjectGetTextureDesc)(HIP_TEXTURE_DESC* pTexDesc, + hipTextureObject_t texObject); +typedef hipError_t (*t_hipTexRefGetAddress)(hipDeviceptr_t* dev_ptr, + const textureReference* texRef); +typedef hipError_t (*t_hipTexRefGetAddressMode)(enum hipTextureAddressMode* pam, + const textureReference* texRef, int dim); +typedef hipError_t (*t_hipTexRefGetFilterMode)(enum hipTextureFilterMode* pfm, + const textureReference* texRef); +typedef hipError_t (*t_hipTexRefGetFlags)(unsigned int* pFlags, const textureReference* texRef); +typedef hipError_t (*t_hipTexRefGetFormat)(hipArray_Format* pFormat, int* pNumChannels, + const textureReference* texRef); +typedef hipError_t (*t_hipTexRefGetMaxAnisotropy)(int* pmaxAnsio, const textureReference* texRef); +typedef hipError_t (*t_hipTexRefGetMipMappedArray)(hipMipmappedArray_t* pArray, + const textureReference* texRef); +typedef hipError_t (*t_hipTexRefGetMipmapFilterMode)(enum hipTextureFilterMode* pfm, + const textureReference* texRef); +typedef hipError_t (*t_hipTexRefGetMipmapLevelBias)(float* pbias, const textureReference* texRef); +typedef hipError_t (*t_hipTexRefGetMipmapLevelClamp)(float* pminMipmapLevelClamp, + float* pmaxMipmapLevelClamp, + const textureReference* texRef); +typedef hipError_t (*t_hipTexRefSetAddress)(size_t* ByteOffset, textureReference* texRef, + hipDeviceptr_t dptr, size_t bytes); +typedef hipError_t (*t_hipTexRefSetAddress2D)(textureReference* texRef, + const HIP_ARRAY_DESCRIPTOR* desc, hipDeviceptr_t dptr, + size_t Pitch); +typedef hipError_t (*t_hipTexRefSetAddressMode)(textureReference* texRef, int dim, + enum hipTextureAddressMode am); +typedef hipError_t (*t_hipTexRefSetArray)(textureReference* tex, hipArray_const_t array, + unsigned int flags); +typedef hipError_t (*t_hipTexRefSetBorderColor)(textureReference* texRef, float* pBorderColor); +typedef hipError_t (*t_hipTexRefSetFilterMode)(textureReference* texRef, + enum hipTextureFilterMode fm); +typedef hipError_t (*t_hipTexRefSetFlags)(textureReference* texRef, unsigned int Flags); +typedef hipError_t (*t_hipTexRefSetFormat)(textureReference* texRef, hipArray_Format fmt, + int NumPackedComponents); +typedef hipError_t (*t_hipTexRefSetMaxAnisotropy)(textureReference* texRef, unsigned int maxAniso); +typedef hipError_t (*t_hipTexRefSetMipmapFilterMode)(textureReference* texRef, + enum hipTextureFilterMode fm); +typedef hipError_t (*t_hipTexRefSetMipmapLevelBias)(textureReference* texRef, float bias); +typedef hipError_t (*t_hipTexRefSetMipmapLevelClamp)(textureReference* texRef, + float minMipMapLevelClamp, + float maxMipMapLevelClamp); +typedef hipError_t (*t_hipTexRefSetMipmappedArray)(textureReference* texRef, + struct hipMipmappedArray* mipmappedArray, + unsigned int Flags); +typedef hipError_t (*t_hipThreadExchangeStreamCaptureMode)(hipStreamCaptureMode* mode); +typedef hipError_t (*t_hipUnbindTexture)(const textureReference* tex); +typedef hipError_t (*t_hipUserObjectCreate)(hipUserObject_t* object_out, void* ptr, + hipHostFn_t destroy, unsigned int initialRefcount, + unsigned int flags); +typedef hipError_t (*t_hipUserObjectRelease)(hipUserObject_t object, unsigned int count); +typedef hipError_t (*t_hipUserObjectRetain)(hipUserObject_t object, unsigned int count); +typedef hipError_t (*t_hipWaitExternalSemaphoresAsync)( + const hipExternalSemaphore_t* extSemArray, const hipExternalSemaphoreWaitParams* paramsArray, + unsigned int numExtSems, hipStream_t stream); + +typedef hipError_t (*t_hipMemcpy_spt)(void* dst, const void* src, size_t sizeBytes, + hipMemcpyKind kind); + +typedef hipError_t (*t_hipMemcpyToSymbol_spt)(const void* symbol, const void* src, size_t sizeBytes, + size_t offset, hipMemcpyKind kind); + +typedef hipError_t (*t_hipMemcpyFromSymbol_spt)(void* dst, const void* symbol, size_t sizeBytes, + size_t offset, hipMemcpyKind kind); + +typedef hipError_t (*t_hipMemcpy2D_spt)(void* dst, size_t dpitch, const void* src, size_t spitch, + size_t width, size_t height, hipMemcpyKind kind); + +typedef hipError_t (*t_hipMemcpy2DFromArray_spt)(void* dst, size_t dpitch, hipArray_const_t src, + size_t wOffset, size_t hOffset, size_t width, + size_t height, hipMemcpyKind kind); + +typedef hipError_t (*t_hipMemcpy3D_spt)(const struct hipMemcpy3DParms* p); + +typedef hipError_t (*t_hipMemset_spt)(void* dst, int value, size_t sizeBytes); + +typedef hipError_t (*t_hipMemsetAsync_spt)(void* dst, int value, size_t sizeBytes, + hipStream_t stream); + +typedef hipError_t (*t_hipMemset2D_spt)(void* dst, size_t pitch, int value, size_t width, + size_t height); + +typedef hipError_t (*t_hipMemset2DAsync_spt)(void* dst, size_t pitch, int value, size_t width, + size_t height, hipStream_t stream); + +typedef hipError_t (*t_hipMemset3DAsync_spt)(hipPitchedPtr pitchedDevPtr, int value, + hipExtent extent, hipStream_t stream); + +typedef hipError_t (*t_hipMemset3D_spt)(hipPitchedPtr pitchedDevPtr, int value, hipExtent extent); + +typedef hipError_t (*t_hipMemcpyAsync_spt)(void* dst, const void* src, size_t sizeBytes, + hipMemcpyKind kind, hipStream_t stream); + +typedef hipError_t (*t_hipMemcpy3DAsync_spt)(const hipMemcpy3DParms* p, hipStream_t stream); + +typedef hipError_t (*t_hipMemcpy2DAsync_spt)(void* dst, size_t dpitch, const void* src, + size_t spitch, size_t width, size_t height, + hipMemcpyKind kind, hipStream_t stream); + +typedef hipError_t (*t_hipMemcpyFromSymbolAsync_spt)(void* dst, const void* symbol, + size_t sizeBytes, size_t offset, + hipMemcpyKind kind, hipStream_t stream); + +typedef hipError_t (*t_hipMemcpyToSymbolAsync_spt)(const void* symbol, const void* src, + size_t sizeBytes, size_t offset, + hipMemcpyKind kind, hipStream_t stream); + +typedef hipError_t (*t_hipMemcpyFromArray_spt)(void* dst, hipArray_const_t src, size_t wOffsetSrc, + size_t hOffset, size_t count, hipMemcpyKind kind); + +typedef hipError_t (*t_hipMemcpy2DToArray_spt)(hipArray_t dst, size_t wOffset, size_t hOffset, + const void* src, size_t spitch, size_t width, + size_t height, hipMemcpyKind kind); + +typedef hipError_t (*t_hipMemcpy2DFromArrayAsync_spt)(void* dst, size_t dpitch, + hipArray_const_t src, size_t wOffsetSrc, + size_t hOffsetSrc, size_t width, + size_t height, hipMemcpyKind kind, + hipStream_t stream); + +typedef hipError_t (*t_hipMemcpy2DToArrayAsync_spt)(hipArray_t dst, size_t wOffset, size_t hOffset, + const void* src, size_t spitch, size_t width, + size_t height, hipMemcpyKind kind, + hipStream_t stream); + +typedef hipError_t (*t_hipStreamQuery_spt)(hipStream_t stream); + +typedef hipError_t (*t_hipStreamSynchronize_spt)(hipStream_t stream); + +typedef hipError_t (*t_hipStreamGetPriority_spt)(hipStream_t stream, int* priority); + +typedef hipError_t (*t_hipStreamWaitEvent_spt)(hipStream_t stream, hipEvent_t event, + unsigned int flags); + +typedef hipError_t (*t_hipStreamGetFlags_spt)(hipStream_t stream, unsigned int* flags); + +typedef hipError_t (*t_hipStreamAddCallback_spt)(hipStream_t stream, hipStreamCallback_t callback, + void* userData, unsigned int flags); +typedef hipError_t (*t_hipEventRecord_spt)(hipEvent_t event, hipStream_t stream); +typedef hipError_t (*t_hipLaunchCooperativeKernel_spt)(const void* f, dim3 gridDim, dim3 blockDim, + void** kernelParams, uint32_t sharedMemBytes, + hipStream_t hStream); + +typedef hipError_t (*t_hipLaunchKernel_spt)(const void* function_address, dim3 numBlocks, + dim3 dimBlocks, void** args, size_t sharedMemBytes, + hipStream_t stream); + +typedef hipError_t (*t_hipGraphLaunch_spt)(hipGraphExec_t graphExec, hipStream_t stream); +typedef hipError_t (*t_hipStreamBeginCapture_spt)(hipStream_t stream, hipStreamCaptureMode mode); +typedef hipError_t (*t_hipStreamEndCapture_spt)(hipStream_t stream, hipGraph_t* pGraph); +typedef hipError_t (*t_hipStreamIsCapturing_spt)(hipStream_t stream, + hipStreamCaptureStatus* pCaptureStatus); +typedef hipError_t (*t_hipStreamGetCaptureInfo_spt)(hipStream_t stream, + hipStreamCaptureStatus* pCaptureStatus, + unsigned long long* pId); +typedef hipError_t (*t_hipStreamGetCaptureInfo_v2_spt)( + hipStream_t stream, hipStreamCaptureStatus* captureStatus_out, unsigned long long* id_out, + hipGraph_t* graph_out, const hipGraphNode_t** dependencies_out, size_t* numDependencies_out); +typedef hipError_t (*t_hipLaunchHostFunc_spt)(hipStream_t stream, hipHostFn_t fn, void* userData); +typedef hipChannelFormatDesc (*t_hipCreateChannelDesc)(int x, int y, int z, int w, + hipChannelFormatKind f); +typedef hipError_t (*t_hipExtModuleLaunchKernel)(hipFunction_t f, uint32_t globalWorkSizeX, + uint32_t globalWorkSizeY, uint32_t globalWorkSizeZ, + uint32_t localWorkSizeX, uint32_t localWorkSizeY, + uint32_t localWorkSizeZ, size_t sharedMemBytes, + hipStream_t hStream, void** kernelParams, + void** extra, hipEvent_t startEvent, + hipEvent_t stopEvent, uint32_t flags); +typedef hipError_t (*t_hipHccModuleLaunchKernel)(hipFunction_t f, uint32_t globalWorkSizeX, + uint32_t globalWorkSizeY, uint32_t globalWorkSizeZ, + uint32_t localWorkSizeX, uint32_t localWorkSizeY, + uint32_t localWorkSizeZ, size_t sharedMemBytes, + hipStream_t hStream, void** kernelParams, + void** extra, hipEvent_t startEvent, + hipEvent_t stopEvent); +typedef int (*t_hipGetStreamDeviceId)(hipStream_t stream); +typedef hipError_t (*t_hipDrvGraphAddMemsetNode)(hipGraphNode_t* phGraphNode, hipGraph_t hGraph, + const hipGraphNode_t* dependencies, size_t numDependencies, + const HIP_MEMSET_NODE_PARAMS* memsetParams, hipCtx_t ctx); +typedef hipError_t (*t_hipGraphAddExternalSemaphoresWaitNode)(hipGraphNode_t* pGraphNode, + hipGraph_t graph, const hipGraphNode_t* pDependencies, + size_t numDependencies, + const hipExternalSemaphoreWaitNodeParams* nodeParams); +typedef hipError_t (*t_hipGraphAddExternalSemaphoresSignalNode)(hipGraphNode_t* pGraphNode, + hipGraph_t graph, const hipGraphNode_t* pDependencies, + size_t numDependencies, + const hipExternalSemaphoreSignalNodeParams* nodeParams); +typedef hipError_t (*t_hipGraphExternalSemaphoresSignalNodeSetParams)(hipGraphNode_t hNode, + const hipExternalSemaphoreSignalNodeParams* nodeParams); +typedef hipError_t (*t_hipGraphExternalSemaphoresWaitNodeSetParams)(hipGraphNode_t hNode, + const hipExternalSemaphoreWaitNodeParams* nodeParams); +typedef hipError_t (*t_hipGraphExternalSemaphoresSignalNodeGetParams)(hipGraphNode_t hNode, + hipExternalSemaphoreSignalNodeParams* params_out); +typedef hipError_t (*t_hipGraphExternalSemaphoresWaitNodeGetParams)(hipGraphNode_t hNode, + hipExternalSemaphoreWaitNodeParams* params_out); +typedef hipError_t (*t_hipGraphExecExternalSemaphoresSignalNodeSetParams)(hipGraphExec_t hGraphExec, + hipGraphNode_t hNode, + const hipExternalSemaphoreSignalNodeParams* nodeParams); +typedef hipError_t (*t_hipGraphExecExternalSemaphoresWaitNodeSetParams)(hipGraphExec_t hGraphExec, + hipGraphNode_t hNode, + const hipExternalSemaphoreWaitNodeParams* nodeParams); +typedef hipError_t (*t_hipGraphAddNode)(hipGraphNode_t *pGraphNode, hipGraph_t graph, + const hipGraphNode_t *pDependencies, size_t numDependencies, + hipGraphNodeParams *nodeParams); +typedef hipError_t (*t_hipGraphInstantiateWithParams)(hipGraphExec_t* pGraphExec, hipGraph_t graph, + hipGraphInstantiateParams* instantiateParams); +typedef hipError_t (*t_hipExtGetLastError)(); +typedef hipError_t (*t_hipTexRefGetBorderColor)(float* pBorderColor, + const textureReference* texRef); +typedef hipError_t (*t_hipTexRefGetArray)(hipArray_t* pArray, const textureReference* texRef); + +typedef hipError_t (*t_hipTexRefGetBorderColor)(float* pBorderColor, + const textureReference* texRef); +typedef hipError_t (*t_hipTexRefGetArray)(hipArray_t* pArray, const textureReference* texRef); +typedef hipError_t (*t_hipGetProcAddress)(const char* symbol, void** pfn, int hipVersion, uint64_t flags, + hipDriverProcAddressQueryResult* symbolStatus); +typedef hipError_t (*t_hipStreamBeginCaptureToGraph)(hipStream_t stream, hipGraph_t graph, + const hipGraphNode_t* dependencies, + const hipGraphEdgeData* dependencyData, + size_t numDependencies, + hipStreamCaptureMode mode); +typedef hipError_t (*t_hipGetFuncBySymbol)(hipFunction_t* functionPtr, const void* symbolPtr); +typedef hipError_t (*t_hipSetValidDevices)(int* device_arr, int len); +typedef hipError_t (*t_hipMemcpyAtoD)(hipDeviceptr_t dstDevice, hipArray_t srcArray, + size_t srcOffset, size_t ByteCount); +typedef hipError_t (*t_hipMemcpyDtoA)(hipArray_t dstArray, size_t dstOffset, + hipDeviceptr_t srcDevice, size_t ByteCount); +typedef hipError_t (*t_hipMemcpyAtoA)(hipArray_t dstArray, size_t dstOffset, hipArray_t srcArray, + size_t srcOffset, size_t ByteCount); +typedef hipError_t (*t_hipMemcpyAtoHAsync)(void* dstHost, hipArray_t srcArray, size_t srcOffset, + size_t ByteCount, hipStream_t stream); +typedef hipError_t (*t_hipMemcpyHtoAAsync)(hipArray_t dstArray, size_t dstOffset, + const void* srcHost, size_t ByteCount, + hipStream_t stream); +typedef hipError_t (*t_hipMemcpy2DArrayToArray)(hipArray_t dst, size_t wOffsetDst, + size_t hOffsetDst, hipArray_const_t src, + size_t wOffsetSrc, size_t hOffsetSrc, size_t width, + size_t height, hipMemcpyKind kind); + +// HIP Compiler dispatch table +struct HipCompilerDispatchTable { + size_t size; + t___hipPopCallConfiguration __hipPopCallConfiguration_fn; + t___hipPushCallConfiguration __hipPushCallConfiguration_fn; + t___hipRegisterFatBinary __hipRegisterFatBinary_fn; + t___hipRegisterFunction __hipRegisterFunction_fn; + t___hipRegisterManagedVar __hipRegisterManagedVar_fn; + t___hipRegisterSurface __hipRegisterSurface_fn; + t___hipRegisterTexture __hipRegisterTexture_fn; + t___hipRegisterVar __hipRegisterVar_fn; + t___hipUnregisterFatBinary __hipUnregisterFatBinary_fn; +}; + +// HIP API dispatch table +struct HipDispatchTable { + size_t size; + t_hipApiName hipApiName_fn; + t_hipArray3DCreate hipArray3DCreate_fn; + t_hipArray3DGetDescriptor hipArray3DGetDescriptor_fn; + t_hipArrayCreate hipArrayCreate_fn; + t_hipArrayDestroy hipArrayDestroy_fn; + t_hipArrayGetDescriptor hipArrayGetDescriptor_fn; + t_hipArrayGetInfo hipArrayGetInfo_fn; + t_hipBindTexture hipBindTexture_fn; + t_hipBindTexture2D hipBindTexture2D_fn; + t_hipBindTextureToArray hipBindTextureToArray_fn; + t_hipBindTextureToMipmappedArray hipBindTextureToMipmappedArray_fn; + t_hipChooseDevice hipChooseDevice_fn; + t_hipChooseDeviceR0000 hipChooseDeviceR0000_fn; + t_hipConfigureCall hipConfigureCall_fn; + t_hipCreateSurfaceObject hipCreateSurfaceObject_fn; + t_hipCreateTextureObject hipCreateTextureObject_fn; + t_hipCtxCreate hipCtxCreate_fn; + t_hipCtxDestroy hipCtxDestroy_fn; + t_hipCtxDisablePeerAccess hipCtxDisablePeerAccess_fn; + t_hipCtxEnablePeerAccess hipCtxEnablePeerAccess_fn; + t_hipCtxGetApiVersion hipCtxGetApiVersion_fn; + t_hipCtxGetCacheConfig hipCtxGetCacheConfig_fn; + t_hipCtxGetCurrent hipCtxGetCurrent_fn; + t_hipCtxGetDevice hipCtxGetDevice_fn; + t_hipCtxGetFlags hipCtxGetFlags_fn; + t_hipCtxGetSharedMemConfig hipCtxGetSharedMemConfig_fn; + t_hipCtxPopCurrent hipCtxPopCurrent_fn; + t_hipCtxPushCurrent hipCtxPushCurrent_fn; + t_hipCtxSetCacheConfig hipCtxSetCacheConfig_fn; + t_hipCtxSetCurrent hipCtxSetCurrent_fn; + t_hipCtxSetSharedMemConfig hipCtxSetSharedMemConfig_fn; + t_hipCtxSynchronize hipCtxSynchronize_fn; + t_hipDestroyExternalMemory hipDestroyExternalMemory_fn; + t_hipDestroyExternalSemaphore hipDestroyExternalSemaphore_fn; + t_hipDestroySurfaceObject hipDestroySurfaceObject_fn; + t_hipDestroyTextureObject hipDestroyTextureObject_fn; + t_hipDeviceCanAccessPeer hipDeviceCanAccessPeer_fn; + t_hipDeviceComputeCapability hipDeviceComputeCapability_fn; + t_hipDeviceDisablePeerAccess hipDeviceDisablePeerAccess_fn; + t_hipDeviceEnablePeerAccess hipDeviceEnablePeerAccess_fn; + t_hipDeviceGet hipDeviceGet_fn; + t_hipDeviceGetAttribute hipDeviceGetAttribute_fn; + t_hipDeviceGetByPCIBusId hipDeviceGetByPCIBusId_fn; + t_hipDeviceGetCacheConfig hipDeviceGetCacheConfig_fn; + t_hipDeviceGetDefaultMemPool hipDeviceGetDefaultMemPool_fn; + t_hipDeviceGetGraphMemAttribute hipDeviceGetGraphMemAttribute_fn; + t_hipDeviceGetLimit hipDeviceGetLimit_fn; + t_hipDeviceGetMemPool hipDeviceGetMemPool_fn; + t_hipDeviceGetName hipDeviceGetName_fn; + t_hipDeviceGetP2PAttribute hipDeviceGetP2PAttribute_fn; + t_hipDeviceGetPCIBusId hipDeviceGetPCIBusId_fn; + t_hipDeviceGetSharedMemConfig hipDeviceGetSharedMemConfig_fn; + t_hipDeviceGetStreamPriorityRange hipDeviceGetStreamPriorityRange_fn; + t_hipDeviceGetUuid hipDeviceGetUuid_fn; + t_hipDeviceGraphMemTrim hipDeviceGraphMemTrim_fn; + t_hipDevicePrimaryCtxGetState hipDevicePrimaryCtxGetState_fn; + t_hipDevicePrimaryCtxRelease hipDevicePrimaryCtxRelease_fn; + t_hipDevicePrimaryCtxReset hipDevicePrimaryCtxReset_fn; + t_hipDevicePrimaryCtxRetain hipDevicePrimaryCtxRetain_fn; + t_hipDevicePrimaryCtxSetFlags hipDevicePrimaryCtxSetFlags_fn; + t_hipDeviceReset hipDeviceReset_fn; + t_hipDeviceSetCacheConfig hipDeviceSetCacheConfig_fn; + t_hipDeviceSetGraphMemAttribute hipDeviceSetGraphMemAttribute_fn; + t_hipDeviceSetLimit hipDeviceSetLimit_fn; + t_hipDeviceSetMemPool hipDeviceSetMemPool_fn; + t_hipDeviceSetSharedMemConfig hipDeviceSetSharedMemConfig_fn; + t_hipDeviceSynchronize hipDeviceSynchronize_fn; + t_hipDeviceTotalMem hipDeviceTotalMem_fn; + t_hipDriverGetVersion hipDriverGetVersion_fn; + t_hipDrvGetErrorName hipDrvGetErrorName_fn; + t_hipDrvGetErrorString hipDrvGetErrorString_fn; + t_hipDrvGraphAddMemcpyNode hipDrvGraphAddMemcpyNode_fn; + t_hipDrvMemcpy2DUnaligned hipDrvMemcpy2DUnaligned_fn; + t_hipDrvMemcpy3D hipDrvMemcpy3D_fn; + t_hipDrvMemcpy3DAsync hipDrvMemcpy3DAsync_fn; + t_hipDrvPointerGetAttributes hipDrvPointerGetAttributes_fn; + t_hipEventCreate hipEventCreate_fn; + t_hipEventCreateWithFlags hipEventCreateWithFlags_fn; + t_hipEventDestroy hipEventDestroy_fn; + t_hipEventElapsedTime hipEventElapsedTime_fn; + t_hipEventQuery hipEventQuery_fn; + t_hipEventRecord hipEventRecord_fn; + t_hipEventSynchronize hipEventSynchronize_fn; + t_hipExtGetLinkTypeAndHopCount hipExtGetLinkTypeAndHopCount_fn; + t_hipExtLaunchKernel hipExtLaunchKernel_fn; + t_hipExtLaunchMultiKernelMultiDevice hipExtLaunchMultiKernelMultiDevice_fn; + t_hipExtMallocWithFlags hipExtMallocWithFlags_fn; + t_hipExtStreamCreateWithCUMask hipExtStreamCreateWithCUMask_fn; + t_hipExtStreamGetCUMask hipExtStreamGetCUMask_fn; + t_hipExternalMemoryGetMappedBuffer hipExternalMemoryGetMappedBuffer_fn; + t_hipFree hipFree_fn; + t_hipFreeArray hipFreeArray_fn; + t_hipFreeAsync hipFreeAsync_fn; + t_hipFreeHost hipFreeHost_fn; + t_hipFreeMipmappedArray hipFreeMipmappedArray_fn; + t_hipFuncGetAttribute hipFuncGetAttribute_fn; + t_hipFuncGetAttributes hipFuncGetAttributes_fn; + t_hipFuncSetAttribute hipFuncSetAttribute_fn; + t_hipFuncSetCacheConfig hipFuncSetCacheConfig_fn; + t_hipFuncSetSharedMemConfig hipFuncSetSharedMemConfig_fn; + t_hipGLGetDevices hipGLGetDevices_fn; + t_hipGetChannelDesc hipGetChannelDesc_fn; + t_hipGetDevice hipGetDevice_fn; + t_hipGetDeviceCount hipGetDeviceCount_fn; + t_hipGetDeviceFlags hipGetDeviceFlags_fn; + t_hipGetDevicePropertiesR0600 hipGetDevicePropertiesR0600_fn; + t_hipGetDevicePropertiesR0000 hipGetDevicePropertiesR0000_fn; + t_hipGetErrorName hipGetErrorName_fn; + t_hipGetErrorString hipGetErrorString_fn; + t_hipGetLastError hipGetLastError_fn; + t_hipGetMipmappedArrayLevel hipGetMipmappedArrayLevel_fn; + t_hipGetSymbolAddress hipGetSymbolAddress_fn; + t_hipGetSymbolSize hipGetSymbolSize_fn; + t_hipGetTextureAlignmentOffset hipGetTextureAlignmentOffset_fn; + t_hipGetTextureObjectResourceDesc hipGetTextureObjectResourceDesc_fn; + t_hipGetTextureObjectResourceViewDesc hipGetTextureObjectResourceViewDesc_fn; + t_hipGetTextureObjectTextureDesc hipGetTextureObjectTextureDesc_fn; + t_hipGetTextureReference hipGetTextureReference_fn; + t_hipGraphAddChildGraphNode hipGraphAddChildGraphNode_fn; + t_hipGraphAddDependencies hipGraphAddDependencies_fn; + t_hipGraphAddEmptyNode hipGraphAddEmptyNode_fn; + t_hipGraphAddEventRecordNode hipGraphAddEventRecordNode_fn; + t_hipGraphAddEventWaitNode hipGraphAddEventWaitNode_fn; + t_hipGraphAddHostNode hipGraphAddHostNode_fn; + t_hipGraphAddKernelNode hipGraphAddKernelNode_fn; + t_hipGraphAddMemAllocNode hipGraphAddMemAllocNode_fn; + t_hipGraphAddMemFreeNode hipGraphAddMemFreeNode_fn; + t_hipGraphAddMemcpyNode hipGraphAddMemcpyNode_fn; + t_hipGraphAddMemcpyNode1D hipGraphAddMemcpyNode1D_fn; + t_hipGraphAddMemcpyNodeFromSymbol hipGraphAddMemcpyNodeFromSymbol_fn; + t_hipGraphAddMemcpyNodeToSymbol hipGraphAddMemcpyNodeToSymbol_fn; + t_hipGraphAddMemsetNode hipGraphAddMemsetNode_fn; + t_hipGraphChildGraphNodeGetGraph hipGraphChildGraphNodeGetGraph_fn; + t_hipGraphClone hipGraphClone_fn; + t_hipGraphCreate hipGraphCreate_fn; + t_hipGraphDebugDotPrint hipGraphDebugDotPrint_fn; + t_hipGraphDestroy hipGraphDestroy_fn; + t_hipGraphDestroyNode hipGraphDestroyNode_fn; + t_hipGraphEventRecordNodeGetEvent hipGraphEventRecordNodeGetEvent_fn; + t_hipGraphEventRecordNodeSetEvent hipGraphEventRecordNodeSetEvent_fn; + t_hipGraphEventWaitNodeGetEvent hipGraphEventWaitNodeGetEvent_fn; + t_hipGraphEventWaitNodeSetEvent hipGraphEventWaitNodeSetEvent_fn; + t_hipGraphExecChildGraphNodeSetParams hipGraphExecChildGraphNodeSetParams_fn; + t_hipGraphExecDestroy hipGraphExecDestroy_fn; + t_hipGraphExecEventRecordNodeSetEvent hipGraphExecEventRecordNodeSetEvent_fn; + t_hipGraphExecEventWaitNodeSetEvent hipGraphExecEventWaitNodeSetEvent_fn; + t_hipGraphExecHostNodeSetParams hipGraphExecHostNodeSetParams_fn; + t_hipGraphExecKernelNodeSetParams hipGraphExecKernelNodeSetParams_fn; + t_hipGraphExecMemcpyNodeSetParams hipGraphExecMemcpyNodeSetParams_fn; + t_hipGraphExecMemcpyNodeSetParams1D hipGraphExecMemcpyNodeSetParams1D_fn; + t_hipGraphExecMemcpyNodeSetParamsFromSymbol hipGraphExecMemcpyNodeSetParamsFromSymbol_fn; + t_hipGraphExecMemcpyNodeSetParamsToSymbol hipGraphExecMemcpyNodeSetParamsToSymbol_fn; + t_hipGraphExecMemsetNodeSetParams hipGraphExecMemsetNodeSetParams_fn; + t_hipGraphExecUpdate hipGraphExecUpdate_fn; + t_hipGraphGetEdges hipGraphGetEdges_fn; + t_hipGraphGetNodes hipGraphGetNodes_fn; + t_hipGraphGetRootNodes hipGraphGetRootNodes_fn; + t_hipGraphHostNodeGetParams hipGraphHostNodeGetParams_fn; + t_hipGraphHostNodeSetParams hipGraphHostNodeSetParams_fn; + t_hipGraphInstantiate hipGraphInstantiate_fn; + t_hipGraphInstantiateWithFlags hipGraphInstantiateWithFlags_fn; + t_hipGraphKernelNodeCopyAttributes hipGraphKernelNodeCopyAttributes_fn; + t_hipGraphKernelNodeGetAttribute hipGraphKernelNodeGetAttribute_fn; + t_hipGraphKernelNodeGetParams hipGraphKernelNodeGetParams_fn; + t_hipGraphKernelNodeSetAttribute hipGraphKernelNodeSetAttribute_fn; + t_hipGraphKernelNodeSetParams hipGraphKernelNodeSetParams_fn; + t_hipGraphLaunch hipGraphLaunch_fn; + t_hipGraphMemAllocNodeGetParams hipGraphMemAllocNodeGetParams_fn; + t_hipGraphMemFreeNodeGetParams hipGraphMemFreeNodeGetParams_fn; + t_hipGraphMemcpyNodeGetParams hipGraphMemcpyNodeGetParams_fn; + t_hipGraphMemcpyNodeSetParams hipGraphMemcpyNodeSetParams_fn; + t_hipGraphMemcpyNodeSetParams1D hipGraphMemcpyNodeSetParams1D_fn; + t_hipGraphMemcpyNodeSetParamsFromSymbol hipGraphMemcpyNodeSetParamsFromSymbol_fn; + t_hipGraphMemcpyNodeSetParamsToSymbol hipGraphMemcpyNodeSetParamsToSymbol_fn; + t_hipGraphMemsetNodeGetParams hipGraphMemsetNodeGetParams_fn; + t_hipGraphMemsetNodeSetParams hipGraphMemsetNodeSetParams_fn; + t_hipGraphNodeFindInClone hipGraphNodeFindInClone_fn; + t_hipGraphNodeGetDependencies hipGraphNodeGetDependencies_fn; + t_hipGraphNodeGetDependentNodes hipGraphNodeGetDependentNodes_fn; + t_hipGraphNodeGetEnabled hipGraphNodeGetEnabled_fn; + t_hipGraphNodeGetType hipGraphNodeGetType_fn; + t_hipGraphNodeSetEnabled hipGraphNodeSetEnabled_fn; + t_hipGraphReleaseUserObject hipGraphReleaseUserObject_fn; + t_hipGraphRemoveDependencies hipGraphRemoveDependencies_fn; + t_hipGraphRetainUserObject hipGraphRetainUserObject_fn; + t_hipGraphUpload hipGraphUpload_fn; + t_hipGraphicsGLRegisterBuffer hipGraphicsGLRegisterBuffer_fn; + t_hipGraphicsGLRegisterImage hipGraphicsGLRegisterImage_fn; + t_hipGraphicsMapResources hipGraphicsMapResources_fn; + t_hipGraphicsResourceGetMappedPointer hipGraphicsResourceGetMappedPointer_fn; + t_hipGraphicsSubResourceGetMappedArray hipGraphicsSubResourceGetMappedArray_fn; + t_hipGraphicsUnmapResources hipGraphicsUnmapResources_fn; + t_hipGraphicsUnregisterResource hipGraphicsUnregisterResource_fn; + t_hipHostAlloc hipHostAlloc_fn; + t_hipHostFree hipHostFree_fn; + t_hipHostGetDevicePointer hipHostGetDevicePointer_fn; + t_hipHostGetFlags hipHostGetFlags_fn; + t_hipHostMalloc hipHostMalloc_fn; + t_hipHostRegister hipHostRegister_fn; + t_hipHostUnregister hipHostUnregister_fn; + t_hipImportExternalMemory hipImportExternalMemory_fn; + t_hipImportExternalSemaphore hipImportExternalSemaphore_fn; + t_hipInit hipInit_fn; + t_hipIpcCloseMemHandle hipIpcCloseMemHandle_fn; + t_hipIpcGetEventHandle hipIpcGetEventHandle_fn; + t_hipIpcGetMemHandle hipIpcGetMemHandle_fn; + t_hipIpcOpenEventHandle hipIpcOpenEventHandle_fn; + t_hipIpcOpenMemHandle hipIpcOpenMemHandle_fn; + t_hipKernelNameRef hipKernelNameRef_fn; + t_hipKernelNameRefByPtr hipKernelNameRefByPtr_fn; + t_hipLaunchByPtr hipLaunchByPtr_fn; + t_hipLaunchCooperativeKernel hipLaunchCooperativeKernel_fn; + t_hipLaunchCooperativeKernelMultiDevice hipLaunchCooperativeKernelMultiDevice_fn; + t_hipLaunchHostFunc hipLaunchHostFunc_fn; + t_hipLaunchKernel hipLaunchKernel_fn; + t_hipMalloc hipMalloc_fn; + t_hipMalloc3D hipMalloc3D_fn; + t_hipMalloc3DArray hipMalloc3DArray_fn; + t_hipMallocArray hipMallocArray_fn; + t_hipMallocAsync hipMallocAsync_fn; + t_hipMallocFromPoolAsync hipMallocFromPoolAsync_fn; + t_hipMallocHost hipMallocHost_fn; + t_hipMallocManaged hipMallocManaged_fn; + t_hipMallocMipmappedArray hipMallocMipmappedArray_fn; + t_hipMallocPitch hipMallocPitch_fn; + t_hipMemAddressFree hipMemAddressFree_fn; + t_hipMemAddressReserve hipMemAddressReserve_fn; + t_hipMemAdvise hipMemAdvise_fn; + t_hipMemAllocHost hipMemAllocHost_fn; + t_hipMemAllocPitch hipMemAllocPitch_fn; + t_hipMemCreate hipMemCreate_fn; + t_hipMemExportToShareableHandle hipMemExportToShareableHandle_fn; + t_hipMemGetAccess hipMemGetAccess_fn; + t_hipMemGetAddressRange hipMemGetAddressRange_fn; + t_hipMemGetAllocationGranularity hipMemGetAllocationGranularity_fn; + t_hipMemGetAllocationPropertiesFromHandle hipMemGetAllocationPropertiesFromHandle_fn; + t_hipMemGetInfo hipMemGetInfo_fn; + t_hipMemImportFromShareableHandle hipMemImportFromShareableHandle_fn; + t_hipMemMap hipMemMap_fn; + t_hipMemMapArrayAsync hipMemMapArrayAsync_fn; + t_hipMemPoolCreate hipMemPoolCreate_fn; + t_hipMemPoolDestroy hipMemPoolDestroy_fn; + t_hipMemPoolExportPointer hipMemPoolExportPointer_fn; + t_hipMemPoolExportToShareableHandle hipMemPoolExportToShareableHandle_fn; + t_hipMemPoolGetAccess hipMemPoolGetAccess_fn; + t_hipMemPoolGetAttribute hipMemPoolGetAttribute_fn; + t_hipMemPoolImportFromShareableHandle hipMemPoolImportFromShareableHandle_fn; + t_hipMemPoolImportPointer hipMemPoolImportPointer_fn; + t_hipMemPoolSetAccess hipMemPoolSetAccess_fn; + t_hipMemPoolSetAttribute hipMemPoolSetAttribute_fn; + t_hipMemPoolTrimTo hipMemPoolTrimTo_fn; + t_hipMemPrefetchAsync hipMemPrefetchAsync_fn; + t_hipMemPtrGetInfo hipMemPtrGetInfo_fn; + t_hipMemRangeGetAttribute hipMemRangeGetAttribute_fn; + t_hipMemRangeGetAttributes hipMemRangeGetAttributes_fn; + t_hipMemRelease hipMemRelease_fn; + t_hipMemRetainAllocationHandle hipMemRetainAllocationHandle_fn; + t_hipMemSetAccess hipMemSetAccess_fn; + t_hipMemUnmap hipMemUnmap_fn; + t_hipMemcpy hipMemcpy_fn; + t_hipMemcpy2D hipMemcpy2D_fn; + t_hipMemcpy2DAsync hipMemcpy2DAsync_fn; + t_hipMemcpy2DFromArray hipMemcpy2DFromArray_fn; + t_hipMemcpy2DFromArrayAsync hipMemcpy2DFromArrayAsync_fn; + t_hipMemcpy2DToArray hipMemcpy2DToArray_fn; + t_hipMemcpy2DToArrayAsync hipMemcpy2DToArrayAsync_fn; + t_hipMemcpy3D hipMemcpy3D_fn; + t_hipMemcpy3DAsync hipMemcpy3DAsync_fn; + t_hipMemcpyAsync hipMemcpyAsync_fn; + t_hipMemcpyAtoH hipMemcpyAtoH_fn; + t_hipMemcpyDtoD hipMemcpyDtoD_fn; + t_hipMemcpyDtoDAsync hipMemcpyDtoDAsync_fn; + t_hipMemcpyDtoH hipMemcpyDtoH_fn; + t_hipMemcpyDtoHAsync hipMemcpyDtoHAsync_fn; + t_hipMemcpyFromArray hipMemcpyFromArray_fn; + t_hipMemcpyFromSymbol hipMemcpyFromSymbol_fn; + t_hipMemcpyFromSymbolAsync hipMemcpyFromSymbolAsync_fn; + t_hipMemcpyHtoA hipMemcpyHtoA_fn; + t_hipMemcpyHtoD hipMemcpyHtoD_fn; + t_hipMemcpyHtoDAsync hipMemcpyHtoDAsync_fn; + t_hipMemcpyParam2D hipMemcpyParam2D_fn; + t_hipMemcpyParam2DAsync hipMemcpyParam2DAsync_fn; + t_hipMemcpyPeer hipMemcpyPeer_fn; + t_hipMemcpyPeerAsync hipMemcpyPeerAsync_fn; + t_hipMemcpyToArray hipMemcpyToArray_fn; + t_hipMemcpyToSymbol hipMemcpyToSymbol_fn; + t_hipMemcpyToSymbolAsync hipMemcpyToSymbolAsync_fn; + t_hipMemcpyWithStream hipMemcpyWithStream_fn; + t_hipMemset hipMemset_fn; + t_hipMemset2D hipMemset2D_fn; + t_hipMemset2DAsync hipMemset2DAsync_fn; + t_hipMemset3D hipMemset3D_fn; + t_hipMemset3DAsync hipMemset3DAsync_fn; + t_hipMemsetAsync hipMemsetAsync_fn; + t_hipMemsetD16 hipMemsetD16_fn; + t_hipMemsetD16Async hipMemsetD16Async_fn; + t_hipMemsetD32 hipMemsetD32_fn; + t_hipMemsetD32Async hipMemsetD32Async_fn; + t_hipMemsetD8 hipMemsetD8_fn; + t_hipMemsetD8Async hipMemsetD8Async_fn; + t_hipMipmappedArrayCreate hipMipmappedArrayCreate_fn; + t_hipMipmappedArrayDestroy hipMipmappedArrayDestroy_fn; + t_hipMipmappedArrayGetLevel hipMipmappedArrayGetLevel_fn; + t_hipModuleGetFunction hipModuleGetFunction_fn; + t_hipModuleGetGlobal hipModuleGetGlobal_fn; + t_hipModuleGetTexRef hipModuleGetTexRef_fn; + t_hipModuleLaunchCooperativeKernel hipModuleLaunchCooperativeKernel_fn; + t_hipModuleLaunchCooperativeKernelMultiDevice hipModuleLaunchCooperativeKernelMultiDevice_fn; + t_hipModuleLaunchKernel hipModuleLaunchKernel_fn; + t_hipModuleLoad hipModuleLoad_fn; + t_hipModuleLoadData hipModuleLoadData_fn; + t_hipModuleLoadDataEx hipModuleLoadDataEx_fn; + t_hipModuleOccupancyMaxActiveBlocksPerMultiprocessor + hipModuleOccupancyMaxActiveBlocksPerMultiprocessor_fn; + t_hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags + hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags_fn; + t_hipModuleOccupancyMaxPotentialBlockSize hipModuleOccupancyMaxPotentialBlockSize_fn; + t_hipModuleOccupancyMaxPotentialBlockSizeWithFlags + hipModuleOccupancyMaxPotentialBlockSizeWithFlags_fn; + t_hipModuleUnload hipModuleUnload_fn; + t_hipOccupancyMaxActiveBlocksPerMultiprocessor hipOccupancyMaxActiveBlocksPerMultiprocessor_fn; + t_hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags + hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags_fn; + t_hipOccupancyMaxPotentialBlockSize hipOccupancyMaxPotentialBlockSize_fn; + t_hipPeekAtLastError hipPeekAtLastError_fn; + t_hipPointerGetAttribute hipPointerGetAttribute_fn; + t_hipPointerGetAttributes hipPointerGetAttributes_fn; + t_hipPointerSetAttribute hipPointerSetAttribute_fn; + t_hipProfilerStart hipProfilerStart_fn; + t_hipProfilerStop hipProfilerStop_fn; + t_hipRuntimeGetVersion hipRuntimeGetVersion_fn; + t_hipSetDevice hipSetDevice_fn; + t_hipSetDeviceFlags hipSetDeviceFlags_fn; + t_hipSetupArgument hipSetupArgument_fn; + t_hipSignalExternalSemaphoresAsync hipSignalExternalSemaphoresAsync_fn; + t_hipStreamAddCallback hipStreamAddCallback_fn; + t_hipStreamAttachMemAsync hipStreamAttachMemAsync_fn; + t_hipStreamBeginCapture hipStreamBeginCapture_fn; + t_hipStreamCreate hipStreamCreate_fn; + t_hipStreamCreateWithFlags hipStreamCreateWithFlags_fn; + t_hipStreamCreateWithPriority hipStreamCreateWithPriority_fn; + t_hipStreamDestroy hipStreamDestroy_fn; + t_hipStreamEndCapture hipStreamEndCapture_fn; + t_hipStreamGetCaptureInfo hipStreamGetCaptureInfo_fn; + t_hipStreamGetCaptureInfo_v2 hipStreamGetCaptureInfo_v2_fn; + t_hipStreamGetDevice hipStreamGetDevice_fn; + t_hipStreamGetFlags hipStreamGetFlags_fn; + t_hipStreamGetPriority hipStreamGetPriority_fn; + t_hipStreamIsCapturing hipStreamIsCapturing_fn; + t_hipStreamQuery hipStreamQuery_fn; + t_hipStreamSynchronize hipStreamSynchronize_fn; + t_hipStreamUpdateCaptureDependencies hipStreamUpdateCaptureDependencies_fn; + t_hipStreamWaitEvent hipStreamWaitEvent_fn; + t_hipStreamWaitValue32 hipStreamWaitValue32_fn; + t_hipStreamWaitValue64 hipStreamWaitValue64_fn; + t_hipStreamWriteValue32 hipStreamWriteValue32_fn; + t_hipStreamWriteValue64 hipStreamWriteValue64_fn; + t_hipTexObjectCreate hipTexObjectCreate_fn; + t_hipTexObjectDestroy hipTexObjectDestroy_fn; + t_hipTexObjectGetResourceDesc hipTexObjectGetResourceDesc_fn; + t_hipTexObjectGetResourceViewDesc hipTexObjectGetResourceViewDesc_fn; + t_hipTexObjectGetTextureDesc hipTexObjectGetTextureDesc_fn; + t_hipTexRefGetAddress hipTexRefGetAddress_fn; + t_hipTexRefGetAddressMode hipTexRefGetAddressMode_fn; + t_hipTexRefGetFilterMode hipTexRefGetFilterMode_fn; + t_hipTexRefGetFlags hipTexRefGetFlags_fn; + t_hipTexRefGetFormat hipTexRefGetFormat_fn; + t_hipTexRefGetMaxAnisotropy hipTexRefGetMaxAnisotropy_fn; + t_hipTexRefGetMipMappedArray hipTexRefGetMipMappedArray_fn; + t_hipTexRefGetMipmapFilterMode hipTexRefGetMipmapFilterMode_fn; + t_hipTexRefGetMipmapLevelBias hipTexRefGetMipmapLevelBias_fn; + t_hipTexRefGetMipmapLevelClamp hipTexRefGetMipmapLevelClamp_fn; + t_hipTexRefSetAddress hipTexRefSetAddress_fn; + t_hipTexRefSetAddress2D hipTexRefSetAddress2D_fn; + t_hipTexRefSetAddressMode hipTexRefSetAddressMode_fn; + t_hipTexRefSetArray hipTexRefSetArray_fn; + t_hipTexRefSetBorderColor hipTexRefSetBorderColor_fn; + t_hipTexRefSetFilterMode hipTexRefSetFilterMode_fn; + t_hipTexRefSetFlags hipTexRefSetFlags_fn; + t_hipTexRefSetFormat hipTexRefSetFormat_fn; + t_hipTexRefSetMaxAnisotropy hipTexRefSetMaxAnisotropy_fn; + t_hipTexRefSetMipmapFilterMode hipTexRefSetMipmapFilterMode_fn; + t_hipTexRefSetMipmapLevelBias hipTexRefSetMipmapLevelBias_fn; + t_hipTexRefSetMipmapLevelClamp hipTexRefSetMipmapLevelClamp_fn; + t_hipTexRefSetMipmappedArray hipTexRefSetMipmappedArray_fn; + t_hipThreadExchangeStreamCaptureMode hipThreadExchangeStreamCaptureMode_fn; + t_hipUnbindTexture hipUnbindTexture_fn; + t_hipUserObjectCreate hipUserObjectCreate_fn; + t_hipUserObjectRelease hipUserObjectRelease_fn; + t_hipUserObjectRetain hipUserObjectRetain_fn; + t_hipWaitExternalSemaphoresAsync hipWaitExternalSemaphoresAsync_fn; + t_hipCreateChannelDesc hipCreateChannelDesc_fn; + t_hipExtModuleLaunchKernel hipExtModuleLaunchKernel_fn; + t_hipHccModuleLaunchKernel hipHccModuleLaunchKernel_fn; + t_hipMemcpy_spt hipMemcpy_spt_fn; + t_hipMemcpyToSymbol_spt hipMemcpyToSymbol_spt_fn; + t_hipMemcpyFromSymbol_spt hipMemcpyFromSymbol_spt_fn; + t_hipMemcpy2D_spt hipMemcpy2D_spt_fn; + t_hipMemcpy2DFromArray_spt hipMemcpy2DFromArray_spt_fn; + t_hipMemcpy3D_spt hipMemcpy3D_spt_fn; + t_hipMemset_spt hipMemset_spt_fn; + t_hipMemsetAsync_spt hipMemsetAsync_spt_fn; + t_hipMemset2D_spt hipMemset2D_spt_fn; + t_hipMemset2DAsync_spt hipMemset2DAsync_spt_fn; + t_hipMemset3DAsync_spt hipMemset3DAsync_spt_fn; + t_hipMemset3D_spt hipMemset3D_spt_fn; + t_hipMemcpyAsync_spt hipMemcpyAsync_spt_fn; + t_hipMemcpy3DAsync_spt hipMemcpy3DAsync_spt_fn; + t_hipMemcpy2DAsync_spt hipMemcpy2DAsync_spt_fn; + t_hipMemcpyFromSymbolAsync_spt hipMemcpyFromSymbolAsync_spt_fn; + t_hipMemcpyToSymbolAsync_spt hipMemcpyToSymbolAsync_spt_fn; + t_hipMemcpyFromArray_spt hipMemcpyFromArray_spt_fn; + t_hipMemcpy2DToArray_spt hipMemcpy2DToArray_spt_fn; + t_hipMemcpy2DFromArrayAsync_spt hipMemcpy2DFromArrayAsync_spt_fn; + t_hipMemcpy2DToArrayAsync_spt hipMemcpy2DToArrayAsync_spt_fn; + t_hipStreamQuery_spt hipStreamQuery_spt_fn; + t_hipStreamSynchronize_spt hipStreamSynchronize_spt_fn; + t_hipStreamGetPriority_spt hipStreamGetPriority_spt_fn; + t_hipStreamWaitEvent_spt hipStreamWaitEvent_spt_fn; + t_hipStreamGetFlags_spt hipStreamGetFlags_spt_fn; + t_hipStreamAddCallback_spt hipStreamAddCallback_spt_fn; + t_hipEventRecord_spt hipEventRecord_spt_fn; + t_hipLaunchCooperativeKernel_spt hipLaunchCooperativeKernel_spt_fn; + t_hipLaunchKernel_spt hipLaunchKernel_spt_fn; + t_hipGraphLaunch_spt hipGraphLaunch_spt_fn; + t_hipStreamBeginCapture_spt hipStreamBeginCapture_spt_fn; + t_hipStreamEndCapture_spt hipStreamEndCapture_spt_fn; + t_hipStreamIsCapturing_spt hipStreamIsCapturing_spt_fn; + t_hipStreamGetCaptureInfo_spt hipStreamGetCaptureInfo_spt_fn; + t_hipStreamGetCaptureInfo_v2_spt hipStreamGetCaptureInfo_v2_spt_fn; + t_hipLaunchHostFunc_spt hipLaunchHostFunc_spt_fn; + t_hipGetStreamDeviceId hipGetStreamDeviceId_fn; + t_hipDrvGraphAddMemsetNode hipDrvGraphAddMemsetNode_fn; + t_hipGraphAddExternalSemaphoresWaitNode hipGraphAddExternalSemaphoresWaitNode_fn; + t_hipGraphAddExternalSemaphoresSignalNode hipGraphAddExternalSemaphoresSignalNode_fn; + t_hipGraphExternalSemaphoresSignalNodeSetParams hipGraphExternalSemaphoresSignalNodeSetParams_fn; + t_hipGraphExternalSemaphoresWaitNodeSetParams hipGraphExternalSemaphoresWaitNodeSetParams_fn; + t_hipGraphExternalSemaphoresSignalNodeGetParams hipGraphExternalSemaphoresSignalNodeGetParams_fn; + t_hipGraphExternalSemaphoresWaitNodeGetParams hipGraphExternalSemaphoresWaitNodeGetParams_fn; + t_hipGraphExecExternalSemaphoresSignalNodeSetParams hipGraphExecExternalSemaphoresSignalNodeSetParams_fn; + t_hipGraphExecExternalSemaphoresWaitNodeSetParams hipGraphExecExternalSemaphoresWaitNodeSetParams_fn; + t_hipGraphAddNode hipGraphAddNode_fn; + t_hipGraphInstantiateWithParams hipGraphInstantiateWithParams_fn; + t_hipExtGetLastError hipExtGetLastError_fn; + t_hipTexRefGetBorderColor hipTexRefGetBorderColor_fn; + t_hipTexRefGetArray hipTexRefGetArray_fn; + t_hipGetProcAddress hipGetProcAddress_fn; + t_hipStreamBeginCaptureToGraph hipStreamBeginCaptureToGraph_fn; + t_hipGetFuncBySymbol hipGetFuncBySymbol_fn; + t_hipSetValidDevices hipSetValidDevices_fn; + t_hipMemcpyAtoD hipMemcpyAtoD_fn; + t_hipMemcpyDtoA hipMemcpyDtoA_fn; + t_hipMemcpyAtoA hipMemcpyAtoA_fn; + t_hipMemcpyAtoHAsync hipMemcpyAtoHAsync_fn; + t_hipMemcpyHtoAAsync hipMemcpyHtoAAsync_fn; + t_hipMemcpy2DArrayToArray hipMemcpy2DArrayToArray_fn; +}; diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_assert.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_assert.h new file mode 100644 index 0000000000000000000000000000000000000000..7d634eae0df3a94002d697d641f367ebb5226a2a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_assert.h @@ -0,0 +1,101 @@ +/* +Copyright (c) 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. +*/ + +#pragma once + +// abort +extern "C" __device__ inline __attribute__((weak)) +void abort() { + __builtin_trap(); +} + +// The noinline attribute helps encapsulate the printf expansion, +// which otherwise has a performance impact just by increasing the +// size of the calling function. Additionally, the weak attribute +// allows the function to exist as a global although its definition is +// included in every compilation unit. +#if defined(_WIN32) || defined(_WIN64) +extern "C" __device__ __attribute__((noinline)) __attribute__((weak)) +void _wassert(const wchar_t *_msg, const wchar_t *_file, unsigned _line) { + // FIXME: Need `wchar_t` support to generate assertion message. + __builtin_trap(); +} +#else /* defined(_WIN32) || defined(_WIN64) */ +extern "C" __device__ __attribute__((noinline)) __attribute__((weak)) +void __assert_fail(const char *assertion, + const char *file, + unsigned int line, + const char *function) +{ + const char fmt[] = "%s:%u: %s: Device-side assertion `%s' failed.\n"; + + // strlen is not available as a built-in yet, so we create our own + // loop in a macro. With a string literal argument, the compiler + // usually manages to replace the loop with a constant. + // + // The macro does not check for null pointer, since all the string + // arguments are defined to be constant literals when called from + // the assert() macro. + // + // NOTE: The loop below includes the null terminator in the length + // as required by append_string_n(). +#define __hip_get_string_length(LEN, STR) \ + do { \ + const char *tmp = STR; \ + while (*tmp++); \ + LEN = tmp - STR; \ + } while (0) + + auto msg = __ockl_fprintf_stderr_begin(); + int len = 0; + __hip_get_string_length(len, fmt); + msg = __ockl_fprintf_append_string_n(msg, fmt, len, 0); + __hip_get_string_length(len, file); + msg = __ockl_fprintf_append_string_n(msg, file, len, 0); + msg = __ockl_fprintf_append_args(msg, 1, line, 0, 0, 0, 0, 0, 0, 0); + __hip_get_string_length(len, function); + msg = __ockl_fprintf_append_string_n(msg, function, len, 0); + __hip_get_string_length(len, assertion); + __ockl_fprintf_append_string_n(msg, assertion, len, /* is_last = */ 1); + +#undef __hip_get_string_length + + __builtin_trap(); +} + +extern "C" __device__ __attribute__((noinline)) __attribute__((weak)) +void __assertfail() +{ + // ignore all the args for now. + __builtin_trap(); +} +#endif /* defined(_WIN32) || defined(_WIN64) */ + +#if defined(NDEBUG) +#define __hip_assert(COND) +#else +#define __hip_assert(COND) \ + do { \ + if (!(COND)) \ + __builtin_trap(); \ + } while (0) +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_cooperative_groups_helper.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_cooperative_groups_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..f62246a031a5b17ce4c3cf1596e44c97127fe2d3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_cooperative_groups_helper.h @@ -0,0 +1,242 @@ +/* +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_helper.h + * + * @brief Device side implementation of cooperative group feature. + * + * Defines helper constructs and APIs which aid the types and device API + * wrappers defined within `amd_detail/hip_cooperative_groups.h`. + */ +#ifndef HIP_INCLUDE_HIP_AMD_DETAIL_HIP_COOPERATIVE_GROUPS_HELPER_H +#define HIP_INCLUDE_HIP_AMD_DETAIL_HIP_COOPERATIVE_GROUPS_HELPER_H + +#if __cplusplus +#if !defined(__HIPCC_RTC__) +#include // threadId, blockId +#include +#endif +#if !defined(__align__) +#define __align__(x) __attribute__((aligned(x))) +#endif + +#if !defined(__CG_QUALIFIER__) +#define __CG_QUALIFIER__ __device__ __forceinline__ +#endif + +#if !defined(__CG_STATIC_QUALIFIER__) +#define __CG_STATIC_QUALIFIER__ __device__ static __forceinline__ +#endif + +#if !defined(_CG_STATIC_CONST_DECL_) +#define _CG_STATIC_CONST_DECL_ static constexpr +#endif + +#if __AMDGCN_WAVEFRONT_SIZE == 32 +using lane_mask = unsigned int; +#else +using lane_mask = unsigned long long int; +#endif + +namespace cooperative_groups { + +/* Global scope */ +template +using is_power_of_2 = std::integral_constant; + +template +using is_valid_wavefront = std::integral_constant; + +template +using is_valid_tile_size = + std::integral_constant::value && is_valid_wavefront::value>; + +template +using is_valid_type = + std::integral_constant::value || std::is_floating_point::value>; + +namespace internal { + +/** +* @brief Enums representing different cooperative group types +* @note This enum is only applicable on Linux. +* + */ +typedef enum { + cg_invalid, + cg_multi_grid, + cg_grid, + cg_workgroup, + cg_tiled_group, + cg_coalesced_group +} group_type; +/** + * @ingroup CooperativeG + * @{ + * This section describes the cooperative groups functions of HIP runtime API. + * + * The cooperative groups provides flexible thread parallel programming algorithms, threads + * cooperate and share data to perform collective computations. + * + * @note Cooperative groups feature is implemented on Linux, under developement + * on Windows. + * + */ +/** + * + * @brief Functionalities related to multi-grid cooperative group type + * @note The following cooperative groups functions are only applicable on Linux. + * + */ +namespace multi_grid { + +__CG_STATIC_QUALIFIER__ uint32_t num_grids() { + return static_cast(__ockl_multi_grid_num_grids()); } + +__CG_STATIC_QUALIFIER__ uint32_t grid_rank() { + return static_cast(__ockl_multi_grid_grid_rank()); } + +__CG_STATIC_QUALIFIER__ uint32_t size() { return static_cast(__ockl_multi_grid_size()); } + +__CG_STATIC_QUALIFIER__ uint32_t thread_rank() { + return static_cast(__ockl_multi_grid_thread_rank()); } + +__CG_STATIC_QUALIFIER__ bool is_valid() { return static_cast(__ockl_multi_grid_is_valid()); } + +__CG_STATIC_QUALIFIER__ void sync() { __ockl_multi_grid_sync(); } + +} // namespace multi_grid + +/** + * @brief Functionalities related to grid cooperative group type + * @note The following cooperative groups functions are only applicable on Linux. + */ +namespace grid { + +__CG_STATIC_QUALIFIER__ uint32_t size() { + return static_cast((blockDim.z * gridDim.z) * (blockDim.y * gridDim.y) * + (blockDim.x * gridDim.x)); +} + +__CG_STATIC_QUALIFIER__ uint32_t thread_rank() { + // Compute global id of the workgroup to which the current thread belongs to + uint32_t blkIdx = static_cast((blockIdx.z * gridDim.y * gridDim.x) + + (blockIdx.y * gridDim.x) + (blockIdx.x)); + + // Compute total number of threads being passed to reach current workgroup + // within grid + uint32_t num_threads_till_current_workgroup = + static_cast(blkIdx * (blockDim.x * blockDim.y * blockDim.z)); + + // Compute thread local rank within current workgroup + uint32_t local_thread_rank = static_cast((threadIdx.z * blockDim.y * blockDim.x) + + (threadIdx.y * blockDim.x) + (threadIdx.x)); + + return (num_threads_till_current_workgroup + local_thread_rank); +} + +__CG_STATIC_QUALIFIER__ bool is_valid() { return static_cast(__ockl_grid_is_valid()); } + +__CG_STATIC_QUALIFIER__ void sync() { __ockl_grid_sync(); } + +} // namespace grid + +/** + * @brief Functionalities related to `workgroup` (thread_block in CUDA terminology) + * cooperative group type + * @note The following cooperative groups functions are only applicable on Linux. + */ +namespace workgroup { + +__CG_STATIC_QUALIFIER__ dim3 group_index() { + return (dim3(static_cast(blockIdx.x), static_cast(blockIdx.y), + static_cast(blockIdx.z))); +} + +__CG_STATIC_QUALIFIER__ dim3 thread_index() { + return (dim3(static_cast(threadIdx.x), static_cast(threadIdx.y), + static_cast(threadIdx.z))); +} + +__CG_STATIC_QUALIFIER__ uint32_t size() { + return (static_cast(blockDim.x * blockDim.y * blockDim.z)); +} + +__CG_STATIC_QUALIFIER__ uint32_t thread_rank() { + return (static_cast((threadIdx.z * blockDim.y * blockDim.x) + + (threadIdx.y * blockDim.x) + (threadIdx.x))); +} + +__CG_STATIC_QUALIFIER__ bool is_valid() { + return true; +} + +__CG_STATIC_QUALIFIER__ void sync() { __syncthreads(); } + +__CG_STATIC_QUALIFIER__ dim3 block_dim() { + return (dim3(static_cast(blockDim.x), static_cast(blockDim.y), + static_cast(blockDim.z))); +} + +} // namespace workgroup + +namespace tiled_group { + +// enforce ordering for memory intructions +__CG_STATIC_QUALIFIER__ void sync() { __builtin_amdgcn_fence(__ATOMIC_ACQ_REL, "agent"); } + +} // namespace tiled_group + +namespace coalesced_group { + +// enforce ordering for memory intructions +__CG_STATIC_QUALIFIER__ void sync() { __builtin_amdgcn_fence(__ATOMIC_ACQ_REL, "agent"); } + +// Masked bit count +// +// For each thread, this function returns the number of active threads which +// have i-th bit of x set and come before the current thread. +__CG_STATIC_QUALIFIER__ unsigned int masked_bit_count(lane_mask x, unsigned int add = 0) { + unsigned int counter=0; + #if __AMDGCN_WAVEFRONT_SIZE == 32 + counter = __builtin_amdgcn_mbcnt_lo(x, add); + #else + counter = __builtin_amdgcn_mbcnt_lo(static_cast(x), add); + counter = __builtin_amdgcn_mbcnt_hi(static_cast(x >> 32), counter); + #endif + + return counter; +} + +} // namespace coalesced_group + + +} // namespace internal + +} // namespace cooperative_groups +/** +* @} +*/ + +#endif // __cplusplus +#endif // HIP_INCLUDE_HIP_AMD_DETAIL_HIP_COOPERATIVE_GROUPS_HELPER_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_fp16_gcc.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_fp16_gcc.h new file mode 100644 index 0000000000000000000000000000000000000000..e76a7fff3a7bdc0061cc81b3aa77f6f9fa1fec88 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_fp16_gcc.h @@ -0,0 +1,254 @@ +#pragma once + +#if defined(__cplusplus) + #include +#endif + +struct __half_raw { + unsigned short x; +}; + +struct __half2_raw { + unsigned short x; + unsigned short y; +}; + +#if defined(__cplusplus) + struct __half; + + __half __float2half(float); + float __half2float(__half); + + // BEGIN STRUCT __HALF + struct __half { + protected: + unsigned short __x; + public: + // CREATORS + __half() = default; + __half(const __half_raw& x) : __x{x.x} {} + #if !defined(__HIP_NO_HALF_CONVERSIONS__) + __half(float x) : __x{__float2half(x).__x} {} + __half(double x) : __x{__float2half(x).__x} {} + #endif + __half(const __half&) = default; + __half(__half&&) = default; + ~__half() = default; + + // MANIPULATORS + __half& operator=(const __half&) = default; + __half& operator=(__half&&) = default; + __half& operator=(const __half_raw& x) { __x = x.x; return *this; } + #if !defined(__HIP_NO_HALF_CONVERSIONS__) + __half& operator=(float x) + { + __x = __float2half(x).__x; + return *this; + } + __half& operator=(double x) + { + return *this = static_cast(x); + } + #endif + + // ACCESSORS + operator float() const { return __half2float(*this); } + operator __half_raw() const { return __half_raw{__x}; } + }; + // END STRUCT __HALF + + // BEGIN STRUCT __HALF2 + struct __half2 { + public: + __half x; + __half y; + + // CREATORS + __half2() = default; + __half2(const __half2_raw& ix) + : + x{reinterpret_cast(ix.x)}, + y{reinterpret_cast(ix.y)} + {} + __half2(const __half& ix, const __half& iy) : x{ix}, y{iy} {} + __half2(const __half2&) = default; + __half2(__half2&&) = default; + ~__half2() = default; + + // MANIPULATORS + __half2& operator=(const __half2&) = default; + __half2& operator=(__half2&&) = default; + __half2& operator=(const __half2_raw& ix) + { + x = reinterpret_cast(ix.x); + y = reinterpret_cast(ix.y); + return *this; + } + + // ACCESSORS + operator __half2_raw() const + { + return __half2_raw{ + reinterpret_cast(x), + reinterpret_cast(y)}; + } + }; + // END STRUCT __HALF2 + + inline + unsigned short __internal_float2half( + float flt, unsigned int& sgn, unsigned int& rem) + { + unsigned int x{}; + std::memcpy(&x, &flt, sizeof(flt)); + + unsigned int u = (x & 0x7fffffffU); + sgn = ((x >> 16) & 0x8000U); + + // NaN/+Inf/-Inf + if (u >= 0x7f800000U) { + rem = 0; + return static_cast( + (u == 0x7f800000U) ? (sgn | 0x7c00U) : 0x7fffU); + } + // Overflows + if (u > 0x477fefffU) { + rem = 0x80000000U; + return static_cast(sgn | 0x7bffU); + } + // Normal numbers + if (u >= 0x38800000U) { + rem = u << 19; + u -= 0x38000000U; + return static_cast(sgn | (u >> 13)); + } + // +0/-0 + if (u < 0x33000001U) { + rem = u; + return static_cast(sgn); + } + // Denormal numbers + unsigned int exponent = u >> 23; + unsigned int mantissa = (u & 0x7fffffU); + unsigned int shift = 0x7eU - exponent; + mantissa |= 0x800000U; + rem = mantissa << (32 - shift); + return static_cast(sgn | (mantissa >> shift)); + } + + inline + __half __float2half(float x) + { + __half_raw r; + unsigned int sgn{}; + unsigned int rem{}; + r.x = __internal_float2half(x, sgn, rem); + if (rem > 0x80000000U || (rem == 0x80000000U && (r.x & 0x1))) ++r.x; + + return r; + } + + inline + __half __float2half_rn(float x) { return __float2half(x); } + + inline + __half __float2half_rz(float x) + { + __half_raw r; + unsigned int sgn{}; + unsigned int rem{}; + r.x = __internal_float2half(x, sgn, rem); + + return r; + } + + inline + __half __float2half_rd(float x) + { + __half_raw r; + unsigned int sgn{}; + unsigned int rem{}; + r.x = __internal_float2half(x, sgn, rem); + if (rem && sgn) ++r.x; + + return r; + } + + inline + __half __float2half_ru(float x) + { + __half_raw r; + unsigned int sgn{}; + unsigned int rem{}; + r.x = __internal_float2half(x, sgn, rem); + if (rem && !sgn) ++r.x; + + return r; + } + + inline + __half2 __float2half2_rn(float x) + { + return __half2{__float2half_rn(x), __float2half_rn(x)}; + } + + inline + __half2 __floats2half2_rn(float x, float y) + { + return __half2{__float2half_rn(x), __float2half_rn(y)}; + } + + inline + float __internal_half2float(unsigned short x) + { + unsigned int sign = ((x >> 15) & 1); + unsigned int exponent = ((x >> 10) & 0x1f); + unsigned int mantissa = ((x & 0x3ff) << 13); + + if (exponent == 0x1fU) { /* NaN or Inf */ + mantissa = (mantissa ? (sign = 0, 0x7fffffU) : 0); + exponent = 0xffU; + } else if (!exponent) { /* Denorm or Zero */ + if (mantissa) { + unsigned int msb; + exponent = 0x71U; + do { + msb = (mantissa & 0x400000U); + mantissa <<= 1; /* normalize */ + --exponent; + } while (!msb); + mantissa &= 0x7fffffU; /* 1.mantissa is implicit */ + } + } else { + exponent += 0x70U; + } + unsigned int u = ((sign << 31) | (exponent << 23) | mantissa); + float f; + memcpy(&f, &u, sizeof(u)); + + return f; + } + + inline + float __half2float(__half x) + { + return __internal_half2float(static_cast<__half_raw>(x).x); + } + + inline + float __low2float(__half2 x) + { + return __internal_half2float(static_cast<__half2_raw>(x).x); + } + + inline + float __high2float(__half2 x) + { + return __internal_half2float(static_cast<__half2_raw>(x).y); + } + + #if !defined(HIP_NO_HALF) + using half = __half; + using half2 = __half2; + #endif +#endif // defined(__cplusplus) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_fp16_math_fwd.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_fp16_math_fwd.h new file mode 100644 index 0000000000000000000000000000000000000000..9b2efefe6bd000c46ce6e24b85b9033cc6329826 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_fp16_math_fwd.h @@ -0,0 +1,96 @@ +/* +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. +*/ + +#pragma once + +// /* +// Half Math Functions +// */ +#if !defined(__HIPCC_RTC__) +#include "host_defines.h" +#endif +#ifndef __CLANG_HIP_RUNTIME_WRAPPER_INCLUDED__ +extern "C" +{ + __device__ __attribute__((const)) _Float16 __ocml_ceil_f16(_Float16); + __device__ _Float16 __ocml_cos_f16(_Float16); + __device__ __attribute__((pure)) _Float16 __ocml_exp_f16(_Float16); + __device__ __attribute__((pure)) _Float16 __ocml_exp10_f16(_Float16); + __device__ __attribute__((pure)) _Float16 __ocml_exp2_f16(_Float16); + __device__ __attribute__((const)) _Float16 __ocml_floor_f16(_Float16); + __device__ __attribute__((const)) + _Float16 __ocml_fma_f16(_Float16, _Float16, _Float16); + __device__ __attribute__((const)) _Float16 __ocml_fabs_f16(_Float16); + __device__ __attribute__((const)) int __ocml_isinf_f16(_Float16); + __device__ __attribute__((const)) int __ocml_isnan_f16(_Float16); + __device__ __attribute__((pure)) _Float16 __ocml_log_f16(_Float16); + __device__ __attribute__((pure)) _Float16 __ocml_log10_f16(_Float16); + __device__ __attribute__((pure)) _Float16 __ocml_log2_f16(_Float16); + __device__ __attribute__((pure)) _Float16 __ocml_pown_f16(_Float16, int); + __device__ __attribute__((const)) _Float16 __ocml_rint_f16(_Float16); + __device__ __attribute__((const)) _Float16 __ocml_rsqrt_f16(_Float16); + __device__ _Float16 __ocml_sin_f16(_Float16); + __device__ __attribute__((const)) _Float16 __ocml_sqrt_f16(_Float16); + __device__ __attribute__((const)) _Float16 __ocml_trunc_f16(_Float16); + __device__ __attribute__((const)) _Float16 __ocml_fmax_f16(_Float16, _Float16); + __device__ __attribute__((const)) _Float16 __ocml_fmin_f16(_Float16, _Float16); + + typedef _Float16 __2f16 __attribute__((ext_vector_type(2))); + typedef short __2i16 __attribute__((ext_vector_type(2))); + + #if defined(__clang__) && defined(__HIP__) + __device__ __attribute__((const)) float __ockl_fdot2(__2f16 a, __2f16 b, float c, bool s); + #endif + + __device__ __attribute__((const)) __2f16 __ocml_ceil_2f16(__2f16); + __device__ __attribute__((const)) __2f16 __ocml_fabs_2f16(__2f16); + __device__ __2f16 __ocml_cos_2f16(__2f16); + __device__ __attribute__((pure)) __2f16 __ocml_exp_2f16(__2f16); + __device__ __attribute__((pure)) __2f16 __ocml_exp10_2f16(__2f16); + __device__ __attribute__((pure)) __2f16 __ocml_exp2_2f16(__2f16); + __device__ __attribute__((const)) __2f16 __ocml_floor_2f16(__2f16); + __device__ __attribute__((const)) __2f16 __ocml_fma_2f16(__2f16, __2f16, __2f16); + __device__ __attribute__((const)) __2i16 __ocml_isinf_2f16(__2f16); + __device__ __attribute__((const)) __2i16 __ocml_isnan_2f16(__2f16); + __device__ __attribute__((pure)) __2f16 __ocml_log_2f16(__2f16); + __device__ __attribute__((pure)) __2f16 __ocml_log10_2f16(__2f16); + __device__ __attribute__((pure)) __2f16 __ocml_log2_2f16(__2f16); + __device__ __attribute__((const)) __2f16 __ocml_rint_2f16(__2f16); + __device__ __attribute__((const)) __2f16 __ocml_rsqrt_2f16(__2f16); + __device__ __2f16 __ocml_sin_2f16(__2f16); + __device__ __attribute__((const)) __2f16 __ocml_sqrt_2f16(__2f16); + __device__ __attribute__((const)) __2f16 __ocml_trunc_2f16(__2f16); + + __device__ __attribute__((const)) _Float16 __ocml_cvtrtn_f16_f32(float); + __device__ __attribute__((const)) _Float16 __ocml_cvtrtp_f16_f32(float); + __device__ __attribute__((const)) _Float16 __ocml_cvtrtz_f16_f32(float); + +} +#endif // !__CLANG_HIP_RUNTIME_WRAPPER_INCLUDED__ +//TODO: remove these after they get into clang header __clang_hip_libdevice_declares.h' +extern "C" { + __device__ __attribute__((const)) _Float16 __ocml_fmax_f16(_Float16, _Float16); + __device__ __attribute__((const)) _Float16 __ocml_fmin_f16(_Float16, _Float16); + __device__ __attribute__((const)) _Float16 __ocml_cvtrtn_f16_f32(float); + __device__ __attribute__((const)) _Float16 __ocml_cvtrtp_f16_f32(float); + __device__ __attribute__((const)) _Float16 __ocml_cvtrtz_f16_f32(float); +} diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_ldg.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_ldg.h new file mode 100644 index 0000000000000000000000000000000000000000..ce1fb51f464c4d8c9be1baa52512e356ba01a216 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_ldg.h @@ -0,0 +1,100 @@ +/* +Copyright (c) 2015 - 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_LDG_H +#define HIP_INCLUDE_HIP_AMD_DETAIL_HIP_LDG_H + +#if __HIP_CLANG_ONLY__ +#include "amd_hip_vector_types.h" +#include "host_defines.h" + +__device__ inline static char __ldg(const char* ptr) { return *ptr; } + +__device__ inline static char2 __ldg(const char2* ptr) { return *ptr; } + +__device__ inline static char4 __ldg(const char4* ptr) { return *ptr; } + +__device__ inline static signed char __ldg(const signed char* ptr) { return ptr[0]; } + +__device__ inline static unsigned char __ldg(const unsigned char* ptr) { return ptr[0]; } + + +__device__ inline static short __ldg(const short* ptr) { return ptr[0]; } + +__device__ inline static short2 __ldg(const short2* ptr) { return ptr[0]; } + +__device__ inline static short4 __ldg(const short4* ptr) { return ptr[0]; } + +__device__ inline static unsigned short __ldg(const unsigned short* ptr) { return ptr[0]; } + + +__device__ inline static int __ldg(const int* ptr) { return ptr[0]; } + +__device__ inline static int2 __ldg(const int2* ptr) { return ptr[0]; } + +__device__ inline static int4 __ldg(const int4* ptr) { return ptr[0]; } + +__device__ inline static unsigned int __ldg(const unsigned int* ptr) { return ptr[0]; } + + +__device__ inline static long __ldg(const long* ptr) { return ptr[0]; } + +__device__ inline static unsigned long __ldg(const unsigned long* ptr) { return ptr[0]; } + + +__device__ inline static long long __ldg(const long long* ptr) { return ptr[0]; } + +__device__ inline static longlong2 __ldg(const longlong2* ptr) { return ptr[0]; } + +__device__ inline static unsigned long long __ldg(const unsigned long long* ptr) { return ptr[0]; } + + +__device__ inline static uchar2 __ldg(const uchar2* ptr) { return ptr[0]; } + +__device__ inline static uchar4 __ldg(const uchar4* ptr) { return ptr[0]; } + + +__device__ inline static ushort2 __ldg(const ushort2* ptr) { return ptr[0]; } + + +__device__ inline static uint2 __ldg(const uint2* ptr) { return ptr[0]; } + +__device__ inline static uint4 __ldg(const uint4* ptr) { return ptr[0]; } + + +__device__ inline static ulonglong2 __ldg(const ulonglong2* ptr) { return ptr[0]; } + + +__device__ inline static float __ldg(const float* ptr) { return ptr[0]; } + +__device__ inline static float2 __ldg(const float2* ptr) { return ptr[0]; } + +__device__ inline static float4 __ldg(const float4* ptr) { return ptr[0]; } + + +__device__ inline static double __ldg(const double* ptr) { return ptr[0]; } + +__device__ inline static double2 __ldg(const double2* ptr) { return ptr[0]; } + +#endif // __HIP_CLANG_ONLY__ + +#endif // HIP_LDG_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_prof_str.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_prof_str.h new file mode 100644 index 0000000000000000000000000000000000000000..992c198d0894550ce6a38e66332f9d013423e9fd --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_prof_str.h @@ -0,0 +1,10570 @@ +// Generated file. DO NOT EDIT. +// +// This file is automatically generated by the hip_prof_gen.py script. +// If changes are required, run the script and commit the updated file. + +#ifndef _HIP_PROF_STR_H +#define _HIP_PROF_STR_H +#define HIP_PROF_VER 1 + +#include +#include +#include "amd_hip_gl_interop.h" + +#define HIP_API_ID_CONCAT_HELPER(a,b) a##b +#define HIP_API_ID_CONCAT(a,b) HIP_API_ID_CONCAT_HELPER(a,b) + +// HIP API callbacks ID enumeration +enum hip_api_id_t { + HIP_API_ID_NONE = 0, + HIP_API_ID_FIRST = 1, + HIP_API_ID___hipPopCallConfiguration = 1, + HIP_API_ID___hipPushCallConfiguration = 2, + HIP_API_ID_hipArray3DCreate = 3, + HIP_API_ID_hipArrayCreate = 4, + HIP_API_ID_hipArrayDestroy = 5, + HIP_API_ID_hipChooseDeviceR0000 = 6, + HIP_API_ID_hipConfigureCall = 7, + HIP_API_ID_hipCtxCreate = 8, + HIP_API_ID_hipCtxDestroy = 9, + HIP_API_ID_hipCtxDisablePeerAccess = 10, + HIP_API_ID_hipCtxEnablePeerAccess = 11, + HIP_API_ID_hipCtxGetApiVersion = 12, + HIP_API_ID_hipCtxGetCacheConfig = 13, + HIP_API_ID_hipCtxGetCurrent = 14, + HIP_API_ID_hipCtxGetDevice = 15, + HIP_API_ID_hipCtxGetFlags = 16, + HIP_API_ID_hipCtxGetSharedMemConfig = 17, + HIP_API_ID_hipCtxPopCurrent = 18, + HIP_API_ID_hipCtxPushCurrent = 19, + HIP_API_ID_hipCtxSetCacheConfig = 20, + HIP_API_ID_hipCtxSetCurrent = 21, + HIP_API_ID_hipCtxSetSharedMemConfig = 22, + HIP_API_ID_hipCtxSynchronize = 23, + HIP_API_ID_hipDestroyExternalMemory = 24, + HIP_API_ID_hipDestroyExternalSemaphore = 25, + HIP_API_ID_hipDeviceCanAccessPeer = 26, + HIP_API_ID_hipDeviceComputeCapability = 27, + HIP_API_ID_hipDeviceDisablePeerAccess = 28, + HIP_API_ID_hipDeviceEnablePeerAccess = 29, + HIP_API_ID_hipDeviceGet = 30, + HIP_API_ID_hipDeviceGetAttribute = 31, + HIP_API_ID_hipDeviceGetByPCIBusId = 32, + HIP_API_ID_hipDeviceGetCacheConfig = 33, + HIP_API_ID_hipDeviceGetLimit = 34, + HIP_API_ID_hipDeviceGetName = 35, + HIP_API_ID_hipDeviceGetP2PAttribute = 36, + HIP_API_ID_hipDeviceGetPCIBusId = 37, + HIP_API_ID_hipDeviceGetSharedMemConfig = 38, + HIP_API_ID_hipDeviceGetStreamPriorityRange = 39, + HIP_API_ID_hipDevicePrimaryCtxGetState = 40, + HIP_API_ID_hipDevicePrimaryCtxRelease = 41, + HIP_API_ID_hipDevicePrimaryCtxReset = 42, + HIP_API_ID_hipDevicePrimaryCtxRetain = 43, + HIP_API_ID_hipDevicePrimaryCtxSetFlags = 44, + HIP_API_ID_hipDeviceReset = 45, + HIP_API_ID_hipDeviceSetCacheConfig = 46, + HIP_API_ID_hipDeviceSetSharedMemConfig = 47, + HIP_API_ID_hipDeviceSynchronize = 48, + HIP_API_ID_hipDeviceTotalMem = 49, + HIP_API_ID_RESERVED_50 = 50, + HIP_API_ID_hipDrvMemcpy2DUnaligned = 51, + HIP_API_ID_hipDrvMemcpy3D = 52, + HIP_API_ID_hipDrvMemcpy3DAsync = 53, + HIP_API_ID_hipEventCreate = 54, + HIP_API_ID_hipEventCreateWithFlags = 55, + HIP_API_ID_hipEventDestroy = 56, + HIP_API_ID_hipEventElapsedTime = 57, + HIP_API_ID_hipEventQuery = 58, + HIP_API_ID_hipEventRecord = 59, + HIP_API_ID_hipEventSynchronize = 60, + HIP_API_ID_hipExtGetLinkTypeAndHopCount = 61, + HIP_API_ID_hipExtLaunchKernel = 62, + HIP_API_ID_hipExtLaunchMultiKernelMultiDevice = 63, + HIP_API_ID_hipExtMallocWithFlags = 64, + HIP_API_ID_hipExtModuleLaunchKernel = 65, + HIP_API_ID_hipExtStreamCreateWithCUMask = 66, + HIP_API_ID_hipExtStreamGetCUMask = 67, + HIP_API_ID_hipExternalMemoryGetMappedBuffer = 68, + HIP_API_ID_hipFree = 69, + HIP_API_ID_hipFreeArray = 70, + HIP_API_ID_hipFreeHost = 71, + HIP_API_ID_hipFreeMipmappedArray = 72, + HIP_API_ID_hipFuncGetAttribute = 73, + HIP_API_ID_hipFuncGetAttributes = 74, + HIP_API_ID_hipFuncSetAttribute = 75, + HIP_API_ID_hipFuncSetCacheConfig = 76, + HIP_API_ID_hipFuncSetSharedMemConfig = 77, + HIP_API_ID_hipGetDevice = 78, + HIP_API_ID_hipGetDeviceCount = 79, + HIP_API_ID_hipGetDeviceFlags = 80, + HIP_API_ID_hipGetDevicePropertiesR0000 = 81, + HIP_API_ID_RESERVED_82 = 82, + HIP_API_ID_hipGetErrorString = 83, + HIP_API_ID_hipGetLastError = 84, + HIP_API_ID_hipGetMipmappedArrayLevel = 85, + HIP_API_ID_hipGetSymbolAddress = 86, + HIP_API_ID_hipGetSymbolSize = 87, + HIP_API_ID_hipHccModuleLaunchKernel = 88, + HIP_API_ID_hipHostAlloc = 89, + HIP_API_ID_hipHostFree = 90, + HIP_API_ID_hipHostGetDevicePointer = 91, + HIP_API_ID_hipHostGetFlags = 92, + HIP_API_ID_hipHostMalloc = 93, + HIP_API_ID_hipHostRegister = 94, + HIP_API_ID_hipHostUnregister = 95, + HIP_API_ID_hipImportExternalMemory = 96, + HIP_API_ID_hipImportExternalSemaphore = 97, + HIP_API_ID_hipInit = 98, + HIP_API_ID_hipIpcCloseMemHandle = 99, + HIP_API_ID_hipIpcGetEventHandle = 100, + HIP_API_ID_hipIpcGetMemHandle = 101, + HIP_API_ID_hipIpcOpenEventHandle = 102, + HIP_API_ID_hipIpcOpenMemHandle = 103, + HIP_API_ID_hipLaunchByPtr = 104, + HIP_API_ID_hipLaunchCooperativeKernel = 105, + HIP_API_ID_hipLaunchCooperativeKernelMultiDevice = 106, + HIP_API_ID_hipLaunchKernel = 107, + HIP_API_ID_hipMalloc = 108, + HIP_API_ID_hipMalloc3D = 109, + HIP_API_ID_hipMalloc3DArray = 110, + HIP_API_ID_hipMallocArray = 111, + HIP_API_ID_hipMallocHost = 112, + HIP_API_ID_hipMallocManaged = 113, + HIP_API_ID_hipMallocMipmappedArray = 114, + HIP_API_ID_hipMallocPitch = 115, + HIP_API_ID_hipMemAdvise = 116, + HIP_API_ID_hipMemAllocHost = 117, + HIP_API_ID_hipMemAllocPitch = 118, + HIP_API_ID_hipMemGetAddressRange = 119, + HIP_API_ID_hipMemGetInfo = 120, + HIP_API_ID_hipMemPrefetchAsync = 121, + HIP_API_ID_hipMemPtrGetInfo = 122, + HIP_API_ID_hipMemRangeGetAttribute = 123, + HIP_API_ID_hipMemRangeGetAttributes = 124, + HIP_API_ID_hipMemcpy = 125, + HIP_API_ID_hipMemcpy2D = 126, + HIP_API_ID_hipMemcpy2DAsync = 127, + HIP_API_ID_hipMemcpy2DFromArray = 128, + HIP_API_ID_hipMemcpy2DFromArrayAsync = 129, + HIP_API_ID_hipMemcpy2DToArray = 130, + HIP_API_ID_hipMemcpy2DToArrayAsync = 131, + HIP_API_ID_hipMemcpy3D = 132, + HIP_API_ID_hipMemcpy3DAsync = 133, + HIP_API_ID_hipMemcpyAsync = 134, + HIP_API_ID_hipMemcpyAtoH = 135, + HIP_API_ID_hipMemcpyDtoD = 136, + HIP_API_ID_hipMemcpyDtoDAsync = 137, + HIP_API_ID_hipMemcpyDtoH = 138, + HIP_API_ID_hipMemcpyDtoHAsync = 139, + HIP_API_ID_hipMemcpyFromArray = 140, + HIP_API_ID_hipMemcpyFromSymbol = 141, + HIP_API_ID_hipMemcpyFromSymbolAsync = 142, + HIP_API_ID_hipMemcpyHtoA = 143, + HIP_API_ID_hipMemcpyHtoD = 144, + HIP_API_ID_hipMemcpyHtoDAsync = 145, + HIP_API_ID_hipMemcpyParam2D = 146, + HIP_API_ID_hipMemcpyParam2DAsync = 147, + HIP_API_ID_hipMemcpyPeer = 148, + HIP_API_ID_hipMemcpyPeerAsync = 149, + HIP_API_ID_hipMemcpyToArray = 150, + HIP_API_ID_hipMemcpyToSymbol = 151, + HIP_API_ID_hipMemcpyToSymbolAsync = 152, + HIP_API_ID_hipMemcpyWithStream = 153, + HIP_API_ID_hipMemset = 154, + HIP_API_ID_hipMemset2D = 155, + HIP_API_ID_hipMemset2DAsync = 156, + HIP_API_ID_hipMemset3D = 157, + HIP_API_ID_hipMemset3DAsync = 158, + HIP_API_ID_hipMemsetAsync = 159, + HIP_API_ID_hipMemsetD16 = 160, + HIP_API_ID_hipMemsetD16Async = 161, + HIP_API_ID_hipMemsetD32 = 162, + HIP_API_ID_hipMemsetD32Async = 163, + HIP_API_ID_hipMemsetD8 = 164, + HIP_API_ID_hipMemsetD8Async = 165, + HIP_API_ID_hipModuleGetFunction = 166, + HIP_API_ID_hipModuleGetGlobal = 167, + HIP_API_ID_hipModuleGetTexRef = 168, + HIP_API_ID_hipModuleLaunchKernel = 169, + HIP_API_ID_hipModuleLoad = 170, + HIP_API_ID_hipModuleLoadData = 171, + HIP_API_ID_hipModuleLoadDataEx = 172, + HIP_API_ID_hipModuleOccupancyMaxActiveBlocksPerMultiprocessor = 173, + HIP_API_ID_hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags = 174, + HIP_API_ID_hipModuleOccupancyMaxPotentialBlockSize = 175, + HIP_API_ID_hipModuleOccupancyMaxPotentialBlockSizeWithFlags = 176, + HIP_API_ID_hipModuleUnload = 177, + HIP_API_ID_hipOccupancyMaxActiveBlocksPerMultiprocessor = 178, + HIP_API_ID_hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags = 179, + HIP_API_ID_hipOccupancyMaxPotentialBlockSize = 180, + HIP_API_ID_hipPeekAtLastError = 181, + HIP_API_ID_hipPointerGetAttributes = 182, + HIP_API_ID_hipProfilerStart = 183, + HIP_API_ID_hipProfilerStop = 184, + HIP_API_ID_RESERVED_185 = 185, + HIP_API_ID_hipSetDevice = 186, + HIP_API_ID_hipSetDeviceFlags = 187, + HIP_API_ID_hipSetupArgument = 188, + HIP_API_ID_hipSignalExternalSemaphoresAsync = 189, + HIP_API_ID_hipStreamAddCallback = 190, + HIP_API_ID_hipStreamAttachMemAsync = 191, + HIP_API_ID_hipStreamCreate = 192, + HIP_API_ID_hipStreamCreateWithFlags = 193, + HIP_API_ID_hipStreamCreateWithPriority = 194, + HIP_API_ID_hipStreamDestroy = 195, + HIP_API_ID_hipStreamGetFlags = 196, + HIP_API_ID_hipStreamGetPriority = 197, + HIP_API_ID_hipStreamQuery = 198, + HIP_API_ID_hipStreamSynchronize = 199, + HIP_API_ID_hipStreamWaitEvent = 200, + HIP_API_ID_hipStreamWaitValue32 = 201, + HIP_API_ID_hipStreamWaitValue64 = 202, + HIP_API_ID_hipStreamWriteValue32 = 203, + HIP_API_ID_hipStreamWriteValue64 = 204, + HIP_API_ID_hipWaitExternalSemaphoresAsync = 205, + HIP_API_ID_hipCreateSurfaceObject = 206, + HIP_API_ID_hipDestroySurfaceObject = 207, + HIP_API_ID_hipGraphAddKernelNode = 208, + HIP_API_ID_hipGraphAddMemcpyNode = 209, + HIP_API_ID_hipGraphAddMemsetNode = 210, + HIP_API_ID_hipGraphCreate = 211, + HIP_API_ID_hipGraphDestroy = 212, + HIP_API_ID_hipGraphExecDestroy = 213, + HIP_API_ID_hipGraphInstantiate = 214, + HIP_API_ID_hipGraphLaunch = 215, + HIP_API_ID_hipMipmappedArrayCreate = 216, + HIP_API_ID_hipMipmappedArrayDestroy = 217, + HIP_API_ID_hipMipmappedArrayGetLevel = 218, + HIP_API_ID_hipStreamBeginCapture = 219, + HIP_API_ID_hipStreamEndCapture = 220, + HIP_API_ID_hipTexRefGetAddress = 221, + HIP_API_ID_hipTexRefGetFlags = 222, + HIP_API_ID_hipTexRefGetFormat = 223, + HIP_API_ID_hipTexRefGetMaxAnisotropy = 224, + HIP_API_ID_hipTexRefGetMipMappedArray = 225, + HIP_API_ID_hipTexRefGetMipmapLevelBias = 226, + HIP_API_ID_hipTexRefGetMipmapLevelClamp = 227, + HIP_API_ID_hipTexRefSetAddress = 228, + HIP_API_ID_hipTexRefSetAddress2D = 229, + HIP_API_ID_hipTexRefSetBorderColor = 230, + HIP_API_ID_hipTexRefSetFormat = 231, + HIP_API_ID_hipTexRefSetMaxAnisotropy = 232, + HIP_API_ID_hipTexRefSetMipmapLevelClamp = 233, + HIP_API_ID_hipTexRefSetMipmappedArray = 234, + HIP_API_ID_hipGLGetDevices = 235, + HIP_API_ID_hipGraphAddDependencies = 236, + HIP_API_ID_hipGraphAddEmptyNode = 237, + HIP_API_ID_hipGraphExecKernelNodeSetParams = 238, + HIP_API_ID_hipGraphGetNodes = 239, + HIP_API_ID_hipGraphGetRootNodes = 240, + HIP_API_ID_hipGraphKernelNodeGetParams = 241, + HIP_API_ID_hipGraphKernelNodeSetParams = 242, + HIP_API_ID_hipGraphMemcpyNodeGetParams = 243, + HIP_API_ID_hipGraphMemcpyNodeSetParams = 244, + HIP_API_ID_hipGraphMemsetNodeGetParams = 245, + HIP_API_ID_hipGraphMemsetNodeSetParams = 246, + HIP_API_ID_hipGraphicsGLRegisterBuffer = 247, + HIP_API_ID_hipGraphicsMapResources = 248, + HIP_API_ID_hipGraphicsResourceGetMappedPointer = 249, + HIP_API_ID_hipGraphicsUnmapResources = 250, + HIP_API_ID_hipGraphicsUnregisterResource = 251, + HIP_API_ID_hipGraphAddChildGraphNode = 252, + HIP_API_ID_hipGraphAddEventRecordNode = 253, + HIP_API_ID_hipGraphAddEventWaitNode = 254, + HIP_API_ID_hipGraphAddHostNode = 255, + HIP_API_ID_hipGraphAddMemcpyNode1D = 256, + HIP_API_ID_hipGraphAddMemcpyNodeFromSymbol = 257, + HIP_API_ID_hipGraphAddMemcpyNodeToSymbol = 258, + HIP_API_ID_hipGraphChildGraphNodeGetGraph = 259, + HIP_API_ID_hipGraphClone = 260, + HIP_API_ID_hipGraphDestroyNode = 261, + HIP_API_ID_hipGraphEventRecordNodeGetEvent = 262, + HIP_API_ID_hipGraphEventRecordNodeSetEvent = 263, + HIP_API_ID_hipGraphEventWaitNodeGetEvent = 264, + HIP_API_ID_hipGraphEventWaitNodeSetEvent = 265, + HIP_API_ID_hipGraphExecChildGraphNodeSetParams = 266, + HIP_API_ID_hipGraphExecEventRecordNodeSetEvent = 267, + HIP_API_ID_hipGraphExecEventWaitNodeSetEvent = 268, + HIP_API_ID_hipGraphExecHostNodeSetParams = 269, + HIP_API_ID_hipGraphExecMemcpyNodeSetParams = 270, + HIP_API_ID_hipGraphExecMemcpyNodeSetParams1D = 271, + HIP_API_ID_hipGraphExecMemcpyNodeSetParamsFromSymbol = 272, + HIP_API_ID_hipGraphExecMemcpyNodeSetParamsToSymbol = 273, + HIP_API_ID_hipGraphExecMemsetNodeSetParams = 274, + HIP_API_ID_hipGraphExecUpdate = 275, + HIP_API_ID_hipGraphGetEdges = 276, + HIP_API_ID_hipGraphHostNodeGetParams = 277, + HIP_API_ID_hipGraphHostNodeSetParams = 278, + HIP_API_ID_hipGraphInstantiateWithFlags = 279, + HIP_API_ID_hipGraphMemcpyNodeSetParams1D = 280, + HIP_API_ID_hipGraphMemcpyNodeSetParamsFromSymbol = 281, + HIP_API_ID_hipGraphMemcpyNodeSetParamsToSymbol = 282, + HIP_API_ID_hipGraphNodeFindInClone = 283, + HIP_API_ID_hipGraphNodeGetDependencies = 284, + HIP_API_ID_hipGraphNodeGetDependentNodes = 285, + HIP_API_ID_hipGraphNodeGetType = 286, + HIP_API_ID_hipGraphRemoveDependencies = 287, + HIP_API_ID_hipStreamGetCaptureInfo = 288, + HIP_API_ID_hipStreamGetCaptureInfo_v2 = 289, + HIP_API_ID_hipStreamIsCapturing = 290, + HIP_API_ID_hipStreamUpdateCaptureDependencies = 291, + HIP_API_ID_hipDrvPointerGetAttributes = 292, + HIP_API_ID_hipGraphicsGLRegisterImage = 293, + HIP_API_ID_hipGraphicsSubResourceGetMappedArray = 294, + HIP_API_ID_hipPointerGetAttribute = 295, + HIP_API_ID_RESERVED_296 = 296, + HIP_API_ID_hipThreadExchangeStreamCaptureMode = 297, + HIP_API_ID_hipDeviceGetUuid = 298, + HIP_API_ID_hipGetChannelDesc = 299, + HIP_API_ID_hipGraphKernelNodeGetAttribute = 300, + HIP_API_ID_hipGraphKernelNodeSetAttribute = 301, + HIP_API_ID_hipLaunchHostFunc = 302, + HIP_API_ID_hipDeviceGetDefaultMemPool = 303, + HIP_API_ID_hipDeviceGetMemPool = 304, + HIP_API_ID_hipDeviceSetMemPool = 305, + HIP_API_ID_hipFreeAsync = 306, + HIP_API_ID_hipMallocAsync = 307, + HIP_API_ID_hipMallocFromPoolAsync = 308, + HIP_API_ID_hipMemPoolCreate = 309, + HIP_API_ID_hipMemPoolDestroy = 310, + HIP_API_ID_hipMemPoolExportPointer = 311, + HIP_API_ID_hipMemPoolExportToShareableHandle = 312, + HIP_API_ID_hipMemPoolGetAccess = 313, + HIP_API_ID_hipMemPoolGetAttribute = 314, + HIP_API_ID_hipMemPoolImportFromShareableHandle = 315, + HIP_API_ID_hipMemPoolImportPointer = 316, + HIP_API_ID_hipMemPoolSetAccess = 317, + HIP_API_ID_hipMemPoolSetAttribute = 318, + HIP_API_ID_hipMemPoolTrimTo = 319, + HIP_API_ID_hipMemAddressFree = 320, + HIP_API_ID_hipMemAddressReserve = 321, + HIP_API_ID_hipMemCreate = 322, + HIP_API_ID_hipMemExportToShareableHandle = 323, + HIP_API_ID_hipMemGetAccess = 324, + HIP_API_ID_hipMemGetAllocationGranularity = 325, + HIP_API_ID_hipMemGetAllocationPropertiesFromHandle = 326, + HIP_API_ID_hipMemImportFromShareableHandle = 327, + HIP_API_ID_hipMemMap = 328, + HIP_API_ID_hipMemMapArrayAsync = 329, + HIP_API_ID_hipMemRelease = 330, + HIP_API_ID_hipMemRetainAllocationHandle = 331, + HIP_API_ID_hipMemSetAccess = 332, + HIP_API_ID_hipMemUnmap = 333, + HIP_API_ID_hipDeviceSetGraphMemAttribute = 334, + HIP_API_ID_hipDeviceGetGraphMemAttribute = 335, + HIP_API_ID_hipDeviceGraphMemTrim = 336, + HIP_API_ID_hipDeviceSetLimit = 337, + HIP_API_ID_hipTexRefSetArray = 338, + HIP_API_ID_hipTexRefSetFlags = 339, + HIP_API_ID_hipTexRefSetMipmapLevelBias = 340, + HIP_API_ID_hipDriverGetVersion = 341, + HIP_API_ID_hipGraphUpload = 342, + HIP_API_ID_hipRuntimeGetVersion = 343, + HIP_API_ID_hipUserObjectCreate = 344, + HIP_API_ID_hipUserObjectRelease = 345, + HIP_API_ID_hipUserObjectRetain = 346, + HIP_API_ID_hipGraphRetainUserObject = 347, + HIP_API_ID_hipGraphReleaseUserObject = 348, + HIP_API_ID_hipGraphDebugDotPrint = 349, + HIP_API_ID_hipGraphKernelNodeCopyAttributes = 350, + HIP_API_ID_hipGraphNodeGetEnabled = 351, + HIP_API_ID_hipGraphNodeSetEnabled = 352, + HIP_API_ID_hipPointerSetAttribute = 353, + HIP_API_ID_hipGraphAddMemAllocNode = 354, + HIP_API_ID_hipGraphAddMemFreeNode = 355, + HIP_API_ID_hipGraphMemAllocNodeGetParams = 356, + HIP_API_ID_hipGraphMemFreeNodeGetParams = 357, + HIP_API_ID_hipModuleLaunchCooperativeKernel = 358, + HIP_API_ID_hipModuleLaunchCooperativeKernelMultiDevice = 359, + HIP_API_ID_hipArray3DGetDescriptor = 360, + HIP_API_ID_hipArrayGetDescriptor = 361, + HIP_API_ID_hipArrayGetInfo = 362, + HIP_API_ID_hipStreamGetDevice = 363, + HIP_API_ID_hipExternalMemoryGetMappedMipmappedArray = 364, + HIP_API_ID_hipChooseDeviceR0600 = 365, + HIP_API_ID_hipDrvGraphAddMemcpyNode = 366, + HIP_API_ID_hipDrvGraphAddMemsetNode = 367, + HIP_API_ID_RESERVED_368 = 368, + HIP_API_ID_RESERVED_369 = 369, + HIP_API_ID_hipGetDevicePropertiesR0600 = 370, + HIP_API_ID_hipGraphAddExternalSemaphoresSignalNode = 371, + HIP_API_ID_hipGraphAddExternalSemaphoresWaitNode = 372, + HIP_API_ID_hipGraphExecExternalSemaphoresSignalNodeSetParams = 373, + HIP_API_ID_hipGraphExecExternalSemaphoresWaitNodeSetParams = 374, + HIP_API_ID_hipGraphExternalSemaphoresSignalNodeGetParams = 375, + HIP_API_ID_hipGraphExternalSemaphoresSignalNodeSetParams = 376, + HIP_API_ID_hipGraphExternalSemaphoresWaitNodeGetParams = 377, + HIP_API_ID_hipGraphExternalSemaphoresWaitNodeSetParams = 378, + HIP_API_ID_hipExtGetLastError = 379, + HIP_API_ID_hipGraphAddNode = 380, + HIP_API_ID_hipGetProcAddress = 381, + HIP_API_ID_RESERVED_382 = 382, + HIP_API_ID_RESERVED_383 = 383, + HIP_API_ID_hipGraphInstantiateWithParams = 384, + HIP_API_ID_RESERVED_385 = 385, + HIP_API_ID_RESERVED_386 = 386, + HIP_API_ID_RESERVED_387 = 387, + HIP_API_ID_RESERVED_388 = 388, + HIP_API_ID_hipTexRefGetArray = 389, + HIP_API_ID_hipTexRefGetBorderColor = 390, + HIP_API_ID_hipStreamBeginCaptureToGraph = 391, + HIP_API_ID_hipGetFuncBySymbol = 392, + HIP_API_ID_hipMemcpy2DArrayToArray = 393, + HIP_API_ID_hipMemcpyAtoA = 394, + HIP_API_ID_hipMemcpyAtoD = 395, + HIP_API_ID_hipMemcpyAtoHAsync = 396, + HIP_API_ID_hipMemcpyDtoA = 397, + HIP_API_ID_hipMemcpyHtoAAsync = 398, + HIP_API_ID_hipSetValidDevices = 399, + HIP_API_ID_LAST = 399, + + HIP_API_ID_hipChooseDevice = HIP_API_ID_CONCAT(HIP_API_ID_,hipChooseDevice), + HIP_API_ID_hipGetDeviceProperties = HIP_API_ID_CONCAT(HIP_API_ID_,hipGetDeviceProperties), + + HIP_API_ID_hipBindTexture = HIP_API_ID_NONE, + HIP_API_ID_hipBindTexture2D = HIP_API_ID_NONE, + HIP_API_ID_hipBindTextureToArray = HIP_API_ID_NONE, + HIP_API_ID_hipBindTextureToMipmappedArray = HIP_API_ID_NONE, + HIP_API_ID_hipCreateTextureObject = HIP_API_ID_NONE, + HIP_API_ID_hipDestroyTextureObject = HIP_API_ID_NONE, + HIP_API_ID_hipDeviceGetCount = HIP_API_ID_NONE, + HIP_API_ID_hipGetTextureAlignmentOffset = HIP_API_ID_NONE, + HIP_API_ID_hipGetTextureObjectResourceDesc = HIP_API_ID_NONE, + HIP_API_ID_hipGetTextureObjectResourceViewDesc = HIP_API_ID_NONE, + HIP_API_ID_hipGetTextureObjectTextureDesc = HIP_API_ID_NONE, + HIP_API_ID_hipGetTextureReference = HIP_API_ID_NONE, + HIP_API_ID_hipTexObjectCreate = HIP_API_ID_NONE, + HIP_API_ID_hipTexObjectDestroy = HIP_API_ID_NONE, + HIP_API_ID_hipTexObjectGetResourceDesc = HIP_API_ID_NONE, + HIP_API_ID_hipTexObjectGetResourceViewDesc = HIP_API_ID_NONE, + HIP_API_ID_hipTexObjectGetTextureDesc = HIP_API_ID_NONE, + HIP_API_ID_hipTexRefGetAddressMode = HIP_API_ID_NONE, + HIP_API_ID_hipTexRefGetFilterMode = HIP_API_ID_NONE, + HIP_API_ID_hipTexRefGetMipmapFilterMode = HIP_API_ID_NONE, + HIP_API_ID_hipTexRefSetAddressMode = HIP_API_ID_NONE, + HIP_API_ID_hipTexRefSetFilterMode = HIP_API_ID_NONE, + HIP_API_ID_hipTexRefSetMipmapFilterMode = HIP_API_ID_NONE, + HIP_API_ID_hipUnbindTexture = HIP_API_ID_NONE, +}; + +#undef HIP_API_ID_CONCAT_HELPER +#undef HIP_API_ID_CONCAT + +// Return the HIP API string for a given callback ID +static inline const char* hip_api_name(const uint32_t id) { + switch(id) { + case HIP_API_ID___hipPopCallConfiguration: return "__hipPopCallConfiguration"; + case HIP_API_ID___hipPushCallConfiguration: return "__hipPushCallConfiguration"; + case HIP_API_ID_hipArray3DCreate: return "hipArray3DCreate"; + case HIP_API_ID_hipArray3DGetDescriptor: return "hipArray3DGetDescriptor"; + case HIP_API_ID_hipArrayCreate: return "hipArrayCreate"; + case HIP_API_ID_hipArrayDestroy: return "hipArrayDestroy"; + case HIP_API_ID_hipArrayGetDescriptor: return "hipArrayGetDescriptor"; + case HIP_API_ID_hipArrayGetInfo: return "hipArrayGetInfo"; + case HIP_API_ID_hipChooseDeviceR0000: return "hipChooseDeviceR0000"; + case HIP_API_ID_hipChooseDeviceR0600: return "hipChooseDeviceR0600"; + case HIP_API_ID_hipConfigureCall: return "hipConfigureCall"; + case HIP_API_ID_hipCreateSurfaceObject: return "hipCreateSurfaceObject"; + case HIP_API_ID_hipCtxCreate: return "hipCtxCreate"; + case HIP_API_ID_hipCtxDestroy: return "hipCtxDestroy"; + case HIP_API_ID_hipCtxDisablePeerAccess: return "hipCtxDisablePeerAccess"; + case HIP_API_ID_hipCtxEnablePeerAccess: return "hipCtxEnablePeerAccess"; + case HIP_API_ID_hipCtxGetApiVersion: return "hipCtxGetApiVersion"; + case HIP_API_ID_hipCtxGetCacheConfig: return "hipCtxGetCacheConfig"; + case HIP_API_ID_hipCtxGetCurrent: return "hipCtxGetCurrent"; + case HIP_API_ID_hipCtxGetDevice: return "hipCtxGetDevice"; + case HIP_API_ID_hipCtxGetFlags: return "hipCtxGetFlags"; + case HIP_API_ID_hipCtxGetSharedMemConfig: return "hipCtxGetSharedMemConfig"; + case HIP_API_ID_hipCtxPopCurrent: return "hipCtxPopCurrent"; + case HIP_API_ID_hipCtxPushCurrent: return "hipCtxPushCurrent"; + case HIP_API_ID_hipCtxSetCacheConfig: return "hipCtxSetCacheConfig"; + case HIP_API_ID_hipCtxSetCurrent: return "hipCtxSetCurrent"; + case HIP_API_ID_hipCtxSetSharedMemConfig: return "hipCtxSetSharedMemConfig"; + case HIP_API_ID_hipCtxSynchronize: return "hipCtxSynchronize"; + case HIP_API_ID_hipDestroyExternalMemory: return "hipDestroyExternalMemory"; + case HIP_API_ID_hipDestroyExternalSemaphore: return "hipDestroyExternalSemaphore"; + case HIP_API_ID_hipDestroySurfaceObject: return "hipDestroySurfaceObject"; + case HIP_API_ID_hipDeviceCanAccessPeer: return "hipDeviceCanAccessPeer"; + case HIP_API_ID_hipDeviceComputeCapability: return "hipDeviceComputeCapability"; + case HIP_API_ID_hipDeviceDisablePeerAccess: return "hipDeviceDisablePeerAccess"; + case HIP_API_ID_hipDeviceEnablePeerAccess: return "hipDeviceEnablePeerAccess"; + case HIP_API_ID_hipDeviceGet: return "hipDeviceGet"; + case HIP_API_ID_hipDeviceGetAttribute: return "hipDeviceGetAttribute"; + case HIP_API_ID_hipDeviceGetByPCIBusId: return "hipDeviceGetByPCIBusId"; + case HIP_API_ID_hipDeviceGetCacheConfig: return "hipDeviceGetCacheConfig"; + case HIP_API_ID_hipDeviceGetDefaultMemPool: return "hipDeviceGetDefaultMemPool"; + case HIP_API_ID_hipDeviceGetGraphMemAttribute: return "hipDeviceGetGraphMemAttribute"; + case HIP_API_ID_hipDeviceGetLimit: return "hipDeviceGetLimit"; + case HIP_API_ID_hipDeviceGetMemPool: return "hipDeviceGetMemPool"; + case HIP_API_ID_hipDeviceGetName: return "hipDeviceGetName"; + case HIP_API_ID_hipDeviceGetP2PAttribute: return "hipDeviceGetP2PAttribute"; + case HIP_API_ID_hipDeviceGetPCIBusId: return "hipDeviceGetPCIBusId"; + case HIP_API_ID_hipDeviceGetSharedMemConfig: return "hipDeviceGetSharedMemConfig"; + case HIP_API_ID_hipDeviceGetStreamPriorityRange: return "hipDeviceGetStreamPriorityRange"; + case HIP_API_ID_hipDeviceGetUuid: return "hipDeviceGetUuid"; + case HIP_API_ID_hipDeviceGraphMemTrim: return "hipDeviceGraphMemTrim"; + case HIP_API_ID_hipDevicePrimaryCtxGetState: return "hipDevicePrimaryCtxGetState"; + case HIP_API_ID_hipDevicePrimaryCtxRelease: return "hipDevicePrimaryCtxRelease"; + case HIP_API_ID_hipDevicePrimaryCtxReset: return "hipDevicePrimaryCtxReset"; + case HIP_API_ID_hipDevicePrimaryCtxRetain: return "hipDevicePrimaryCtxRetain"; + case HIP_API_ID_hipDevicePrimaryCtxSetFlags: return "hipDevicePrimaryCtxSetFlags"; + case HIP_API_ID_hipDeviceReset: return "hipDeviceReset"; + case HIP_API_ID_hipDeviceSetCacheConfig: return "hipDeviceSetCacheConfig"; + case HIP_API_ID_hipDeviceSetGraphMemAttribute: return "hipDeviceSetGraphMemAttribute"; + case HIP_API_ID_hipDeviceSetLimit: return "hipDeviceSetLimit"; + case HIP_API_ID_hipDeviceSetMemPool: return "hipDeviceSetMemPool"; + case HIP_API_ID_hipDeviceSetSharedMemConfig: return "hipDeviceSetSharedMemConfig"; + case HIP_API_ID_hipDeviceSynchronize: return "hipDeviceSynchronize"; + case HIP_API_ID_hipDeviceTotalMem: return "hipDeviceTotalMem"; + case HIP_API_ID_hipDriverGetVersion: return "hipDriverGetVersion"; + case HIP_API_ID_hipDrvGraphAddMemcpyNode: return "hipDrvGraphAddMemcpyNode"; + case HIP_API_ID_hipDrvGraphAddMemsetNode: return "hipDrvGraphAddMemsetNode"; + case HIP_API_ID_hipDrvMemcpy2DUnaligned: return "hipDrvMemcpy2DUnaligned"; + case HIP_API_ID_hipDrvMemcpy3D: return "hipDrvMemcpy3D"; + case HIP_API_ID_hipDrvMemcpy3DAsync: return "hipDrvMemcpy3DAsync"; + case HIP_API_ID_hipDrvPointerGetAttributes: return "hipDrvPointerGetAttributes"; + case HIP_API_ID_hipEventCreate: return "hipEventCreate"; + case HIP_API_ID_hipEventCreateWithFlags: return "hipEventCreateWithFlags"; + case HIP_API_ID_hipEventDestroy: return "hipEventDestroy"; + case HIP_API_ID_hipEventElapsedTime: return "hipEventElapsedTime"; + case HIP_API_ID_hipEventQuery: return "hipEventQuery"; + case HIP_API_ID_hipEventRecord: return "hipEventRecord"; + case HIP_API_ID_hipEventSynchronize: return "hipEventSynchronize"; + case HIP_API_ID_hipExtGetLastError: return "hipExtGetLastError"; + case HIP_API_ID_hipExtGetLinkTypeAndHopCount: return "hipExtGetLinkTypeAndHopCount"; + case HIP_API_ID_hipExtLaunchKernel: return "hipExtLaunchKernel"; + case HIP_API_ID_hipExtLaunchMultiKernelMultiDevice: return "hipExtLaunchMultiKernelMultiDevice"; + case HIP_API_ID_hipExtMallocWithFlags: return "hipExtMallocWithFlags"; + case HIP_API_ID_hipExtModuleLaunchKernel: return "hipExtModuleLaunchKernel"; + case HIP_API_ID_hipExtStreamCreateWithCUMask: return "hipExtStreamCreateWithCUMask"; + case HIP_API_ID_hipExtStreamGetCUMask: return "hipExtStreamGetCUMask"; + case HIP_API_ID_hipExternalMemoryGetMappedBuffer: return "hipExternalMemoryGetMappedBuffer"; + case HIP_API_ID_hipExternalMemoryGetMappedMipmappedArray: return "hipExternalMemoryGetMappedMipmappedArray"; + case HIP_API_ID_hipFree: return "hipFree"; + case HIP_API_ID_hipFreeArray: return "hipFreeArray"; + case HIP_API_ID_hipFreeAsync: return "hipFreeAsync"; + case HIP_API_ID_hipFreeHost: return "hipFreeHost"; + case HIP_API_ID_hipFreeMipmappedArray: return "hipFreeMipmappedArray"; + case HIP_API_ID_hipFuncGetAttribute: return "hipFuncGetAttribute"; + case HIP_API_ID_hipFuncGetAttributes: return "hipFuncGetAttributes"; + case HIP_API_ID_hipFuncSetAttribute: return "hipFuncSetAttribute"; + case HIP_API_ID_hipFuncSetCacheConfig: return "hipFuncSetCacheConfig"; + case HIP_API_ID_hipFuncSetSharedMemConfig: return "hipFuncSetSharedMemConfig"; + case HIP_API_ID_hipGLGetDevices: return "hipGLGetDevices"; + case HIP_API_ID_hipGetChannelDesc: return "hipGetChannelDesc"; + case HIP_API_ID_hipGetDevice: return "hipGetDevice"; + case HIP_API_ID_hipGetDeviceCount: return "hipGetDeviceCount"; + case HIP_API_ID_hipGetDeviceFlags: return "hipGetDeviceFlags"; + case HIP_API_ID_hipGetDevicePropertiesR0000: return "hipGetDevicePropertiesR0000"; + case HIP_API_ID_hipGetDevicePropertiesR0600: return "hipGetDevicePropertiesR0600"; + case HIP_API_ID_hipGetErrorString: return "hipGetErrorString"; + case HIP_API_ID_hipGetFuncBySymbol: return "hipGetFuncBySymbol"; + case HIP_API_ID_hipGetLastError: return "hipGetLastError"; + case HIP_API_ID_hipGetMipmappedArrayLevel: return "hipGetMipmappedArrayLevel"; + case HIP_API_ID_hipGetProcAddress: return "hipGetProcAddress"; + case HIP_API_ID_hipGetSymbolAddress: return "hipGetSymbolAddress"; + case HIP_API_ID_hipGetSymbolSize: return "hipGetSymbolSize"; + case HIP_API_ID_hipGraphAddChildGraphNode: return "hipGraphAddChildGraphNode"; + case HIP_API_ID_hipGraphAddDependencies: return "hipGraphAddDependencies"; + case HIP_API_ID_hipGraphAddEmptyNode: return "hipGraphAddEmptyNode"; + case HIP_API_ID_hipGraphAddEventRecordNode: return "hipGraphAddEventRecordNode"; + case HIP_API_ID_hipGraphAddEventWaitNode: return "hipGraphAddEventWaitNode"; + case HIP_API_ID_hipGraphAddExternalSemaphoresSignalNode: return "hipGraphAddExternalSemaphoresSignalNode"; + case HIP_API_ID_hipGraphAddExternalSemaphoresWaitNode: return "hipGraphAddExternalSemaphoresWaitNode"; + case HIP_API_ID_hipGraphAddHostNode: return "hipGraphAddHostNode"; + case HIP_API_ID_hipGraphAddKernelNode: return "hipGraphAddKernelNode"; + case HIP_API_ID_hipGraphAddMemAllocNode: return "hipGraphAddMemAllocNode"; + case HIP_API_ID_hipGraphAddMemFreeNode: return "hipGraphAddMemFreeNode"; + case HIP_API_ID_hipGraphAddMemcpyNode: return "hipGraphAddMemcpyNode"; + case HIP_API_ID_hipGraphAddMemcpyNode1D: return "hipGraphAddMemcpyNode1D"; + case HIP_API_ID_hipGraphAddMemcpyNodeFromSymbol: return "hipGraphAddMemcpyNodeFromSymbol"; + case HIP_API_ID_hipGraphAddMemcpyNodeToSymbol: return "hipGraphAddMemcpyNodeToSymbol"; + case HIP_API_ID_hipGraphAddMemsetNode: return "hipGraphAddMemsetNode"; + case HIP_API_ID_hipGraphAddNode: return "hipGraphAddNode"; + case HIP_API_ID_hipGraphChildGraphNodeGetGraph: return "hipGraphChildGraphNodeGetGraph"; + case HIP_API_ID_hipGraphClone: return "hipGraphClone"; + case HIP_API_ID_hipGraphCreate: return "hipGraphCreate"; + case HIP_API_ID_hipGraphDebugDotPrint: return "hipGraphDebugDotPrint"; + case HIP_API_ID_hipGraphDestroy: return "hipGraphDestroy"; + case HIP_API_ID_hipGraphDestroyNode: return "hipGraphDestroyNode"; + case HIP_API_ID_hipGraphEventRecordNodeGetEvent: return "hipGraphEventRecordNodeGetEvent"; + case HIP_API_ID_hipGraphEventRecordNodeSetEvent: return "hipGraphEventRecordNodeSetEvent"; + case HIP_API_ID_hipGraphEventWaitNodeGetEvent: return "hipGraphEventWaitNodeGetEvent"; + case HIP_API_ID_hipGraphEventWaitNodeSetEvent: return "hipGraphEventWaitNodeSetEvent"; + case HIP_API_ID_hipGraphExecChildGraphNodeSetParams: return "hipGraphExecChildGraphNodeSetParams"; + case HIP_API_ID_hipGraphExecDestroy: return "hipGraphExecDestroy"; + case HIP_API_ID_hipGraphExecEventRecordNodeSetEvent: return "hipGraphExecEventRecordNodeSetEvent"; + case HIP_API_ID_hipGraphExecEventWaitNodeSetEvent: return "hipGraphExecEventWaitNodeSetEvent"; + case HIP_API_ID_hipGraphExecExternalSemaphoresSignalNodeSetParams: return "hipGraphExecExternalSemaphoresSignalNodeSetParams"; + case HIP_API_ID_hipGraphExecExternalSemaphoresWaitNodeSetParams: return "hipGraphExecExternalSemaphoresWaitNodeSetParams"; + case HIP_API_ID_hipGraphExecHostNodeSetParams: return "hipGraphExecHostNodeSetParams"; + case HIP_API_ID_hipGraphExecKernelNodeSetParams: return "hipGraphExecKernelNodeSetParams"; + case HIP_API_ID_hipGraphExecMemcpyNodeSetParams: return "hipGraphExecMemcpyNodeSetParams"; + case HIP_API_ID_hipGraphExecMemcpyNodeSetParams1D: return "hipGraphExecMemcpyNodeSetParams1D"; + case HIP_API_ID_hipGraphExecMemcpyNodeSetParamsFromSymbol: return "hipGraphExecMemcpyNodeSetParamsFromSymbol"; + case HIP_API_ID_hipGraphExecMemcpyNodeSetParamsToSymbol: return "hipGraphExecMemcpyNodeSetParamsToSymbol"; + case HIP_API_ID_hipGraphExecMemsetNodeSetParams: return "hipGraphExecMemsetNodeSetParams"; + case HIP_API_ID_hipGraphExecUpdate: return "hipGraphExecUpdate"; + case HIP_API_ID_hipGraphExternalSemaphoresSignalNodeGetParams: return "hipGraphExternalSemaphoresSignalNodeGetParams"; + case HIP_API_ID_hipGraphExternalSemaphoresSignalNodeSetParams: return "hipGraphExternalSemaphoresSignalNodeSetParams"; + case HIP_API_ID_hipGraphExternalSemaphoresWaitNodeGetParams: return "hipGraphExternalSemaphoresWaitNodeGetParams"; + case HIP_API_ID_hipGraphExternalSemaphoresWaitNodeSetParams: return "hipGraphExternalSemaphoresWaitNodeSetParams"; + case HIP_API_ID_hipGraphGetEdges: return "hipGraphGetEdges"; + case HIP_API_ID_hipGraphGetNodes: return "hipGraphGetNodes"; + case HIP_API_ID_hipGraphGetRootNodes: return "hipGraphGetRootNodes"; + case HIP_API_ID_hipGraphHostNodeGetParams: return "hipGraphHostNodeGetParams"; + case HIP_API_ID_hipGraphHostNodeSetParams: return "hipGraphHostNodeSetParams"; + case HIP_API_ID_hipGraphInstantiate: return "hipGraphInstantiate"; + case HIP_API_ID_hipGraphInstantiateWithFlags: return "hipGraphInstantiateWithFlags"; + case HIP_API_ID_hipGraphInstantiateWithParams: return "hipGraphInstantiateWithParams"; + case HIP_API_ID_hipGraphKernelNodeCopyAttributes: return "hipGraphKernelNodeCopyAttributes"; + case HIP_API_ID_hipGraphKernelNodeGetAttribute: return "hipGraphKernelNodeGetAttribute"; + case HIP_API_ID_hipGraphKernelNodeGetParams: return "hipGraphKernelNodeGetParams"; + case HIP_API_ID_hipGraphKernelNodeSetAttribute: return "hipGraphKernelNodeSetAttribute"; + case HIP_API_ID_hipGraphKernelNodeSetParams: return "hipGraphKernelNodeSetParams"; + case HIP_API_ID_hipGraphLaunch: return "hipGraphLaunch"; + case HIP_API_ID_hipGraphMemAllocNodeGetParams: return "hipGraphMemAllocNodeGetParams"; + case HIP_API_ID_hipGraphMemFreeNodeGetParams: return "hipGraphMemFreeNodeGetParams"; + case HIP_API_ID_hipGraphMemcpyNodeGetParams: return "hipGraphMemcpyNodeGetParams"; + case HIP_API_ID_hipGraphMemcpyNodeSetParams: return "hipGraphMemcpyNodeSetParams"; + case HIP_API_ID_hipGraphMemcpyNodeSetParams1D: return "hipGraphMemcpyNodeSetParams1D"; + case HIP_API_ID_hipGraphMemcpyNodeSetParamsFromSymbol: return "hipGraphMemcpyNodeSetParamsFromSymbol"; + case HIP_API_ID_hipGraphMemcpyNodeSetParamsToSymbol: return "hipGraphMemcpyNodeSetParamsToSymbol"; + case HIP_API_ID_hipGraphMemsetNodeGetParams: return "hipGraphMemsetNodeGetParams"; + case HIP_API_ID_hipGraphMemsetNodeSetParams: return "hipGraphMemsetNodeSetParams"; + case HIP_API_ID_hipGraphNodeFindInClone: return "hipGraphNodeFindInClone"; + case HIP_API_ID_hipGraphNodeGetDependencies: return "hipGraphNodeGetDependencies"; + case HIP_API_ID_hipGraphNodeGetDependentNodes: return "hipGraphNodeGetDependentNodes"; + case HIP_API_ID_hipGraphNodeGetEnabled: return "hipGraphNodeGetEnabled"; + case HIP_API_ID_hipGraphNodeGetType: return "hipGraphNodeGetType"; + case HIP_API_ID_hipGraphNodeSetEnabled: return "hipGraphNodeSetEnabled"; + case HIP_API_ID_hipGraphReleaseUserObject: return "hipGraphReleaseUserObject"; + case HIP_API_ID_hipGraphRemoveDependencies: return "hipGraphRemoveDependencies"; + case HIP_API_ID_hipGraphRetainUserObject: return "hipGraphRetainUserObject"; + case HIP_API_ID_hipGraphUpload: return "hipGraphUpload"; + case HIP_API_ID_hipGraphicsGLRegisterBuffer: return "hipGraphicsGLRegisterBuffer"; + case HIP_API_ID_hipGraphicsGLRegisterImage: return "hipGraphicsGLRegisterImage"; + case HIP_API_ID_hipGraphicsMapResources: return "hipGraphicsMapResources"; + case HIP_API_ID_hipGraphicsResourceGetMappedPointer: return "hipGraphicsResourceGetMappedPointer"; + case HIP_API_ID_hipGraphicsSubResourceGetMappedArray: return "hipGraphicsSubResourceGetMappedArray"; + case HIP_API_ID_hipGraphicsUnmapResources: return "hipGraphicsUnmapResources"; + case HIP_API_ID_hipGraphicsUnregisterResource: return "hipGraphicsUnregisterResource"; + case HIP_API_ID_hipHccModuleLaunchKernel: return "hipHccModuleLaunchKernel"; + case HIP_API_ID_hipHostAlloc: return "hipHostAlloc"; + case HIP_API_ID_hipHostFree: return "hipHostFree"; + case HIP_API_ID_hipHostGetDevicePointer: return "hipHostGetDevicePointer"; + case HIP_API_ID_hipHostGetFlags: return "hipHostGetFlags"; + case HIP_API_ID_hipHostMalloc: return "hipHostMalloc"; + case HIP_API_ID_hipHostRegister: return "hipHostRegister"; + case HIP_API_ID_hipHostUnregister: return "hipHostUnregister"; + case HIP_API_ID_hipImportExternalMemory: return "hipImportExternalMemory"; + case HIP_API_ID_hipImportExternalSemaphore: return "hipImportExternalSemaphore"; + case HIP_API_ID_hipInit: return "hipInit"; + case HIP_API_ID_hipIpcCloseMemHandle: return "hipIpcCloseMemHandle"; + case HIP_API_ID_hipIpcGetEventHandle: return "hipIpcGetEventHandle"; + case HIP_API_ID_hipIpcGetMemHandle: return "hipIpcGetMemHandle"; + case HIP_API_ID_hipIpcOpenEventHandle: return "hipIpcOpenEventHandle"; + case HIP_API_ID_hipIpcOpenMemHandle: return "hipIpcOpenMemHandle"; + case HIP_API_ID_hipLaunchByPtr: return "hipLaunchByPtr"; + case HIP_API_ID_hipLaunchCooperativeKernel: return "hipLaunchCooperativeKernel"; + case HIP_API_ID_hipLaunchCooperativeKernelMultiDevice: return "hipLaunchCooperativeKernelMultiDevice"; + case HIP_API_ID_hipLaunchHostFunc: return "hipLaunchHostFunc"; + case HIP_API_ID_hipLaunchKernel: return "hipLaunchKernel"; + case HIP_API_ID_hipMalloc: return "hipMalloc"; + case HIP_API_ID_hipMalloc3D: return "hipMalloc3D"; + case HIP_API_ID_hipMalloc3DArray: return "hipMalloc3DArray"; + case HIP_API_ID_hipMallocArray: return "hipMallocArray"; + case HIP_API_ID_hipMallocAsync: return "hipMallocAsync"; + case HIP_API_ID_hipMallocFromPoolAsync: return "hipMallocFromPoolAsync"; + case HIP_API_ID_hipMallocHost: return "hipMallocHost"; + case HIP_API_ID_hipMallocManaged: return "hipMallocManaged"; + case HIP_API_ID_hipMallocMipmappedArray: return "hipMallocMipmappedArray"; + case HIP_API_ID_hipMallocPitch: return "hipMallocPitch"; + case HIP_API_ID_hipMemAddressFree: return "hipMemAddressFree"; + case HIP_API_ID_hipMemAddressReserve: return "hipMemAddressReserve"; + case HIP_API_ID_hipMemAdvise: return "hipMemAdvise"; + case HIP_API_ID_hipMemAllocHost: return "hipMemAllocHost"; + case HIP_API_ID_hipMemAllocPitch: return "hipMemAllocPitch"; + case HIP_API_ID_hipMemCreate: return "hipMemCreate"; + case HIP_API_ID_hipMemExportToShareableHandle: return "hipMemExportToShareableHandle"; + case HIP_API_ID_hipMemGetAccess: return "hipMemGetAccess"; + case HIP_API_ID_hipMemGetAddressRange: return "hipMemGetAddressRange"; + case HIP_API_ID_hipMemGetAllocationGranularity: return "hipMemGetAllocationGranularity"; + case HIP_API_ID_hipMemGetAllocationPropertiesFromHandle: return "hipMemGetAllocationPropertiesFromHandle"; + case HIP_API_ID_hipMemGetInfo: return "hipMemGetInfo"; + case HIP_API_ID_hipMemImportFromShareableHandle: return "hipMemImportFromShareableHandle"; + case HIP_API_ID_hipMemMap: return "hipMemMap"; + case HIP_API_ID_hipMemMapArrayAsync: return "hipMemMapArrayAsync"; + case HIP_API_ID_hipMemPoolCreate: return "hipMemPoolCreate"; + case HIP_API_ID_hipMemPoolDestroy: return "hipMemPoolDestroy"; + case HIP_API_ID_hipMemPoolExportPointer: return "hipMemPoolExportPointer"; + case HIP_API_ID_hipMemPoolExportToShareableHandle: return "hipMemPoolExportToShareableHandle"; + case HIP_API_ID_hipMemPoolGetAccess: return "hipMemPoolGetAccess"; + case HIP_API_ID_hipMemPoolGetAttribute: return "hipMemPoolGetAttribute"; + case HIP_API_ID_hipMemPoolImportFromShareableHandle: return "hipMemPoolImportFromShareableHandle"; + case HIP_API_ID_hipMemPoolImportPointer: return "hipMemPoolImportPointer"; + case HIP_API_ID_hipMemPoolSetAccess: return "hipMemPoolSetAccess"; + case HIP_API_ID_hipMemPoolSetAttribute: return "hipMemPoolSetAttribute"; + case HIP_API_ID_hipMemPoolTrimTo: return "hipMemPoolTrimTo"; + case HIP_API_ID_hipMemPrefetchAsync: return "hipMemPrefetchAsync"; + case HIP_API_ID_hipMemPtrGetInfo: return "hipMemPtrGetInfo"; + case HIP_API_ID_hipMemRangeGetAttribute: return "hipMemRangeGetAttribute"; + case HIP_API_ID_hipMemRangeGetAttributes: return "hipMemRangeGetAttributes"; + case HIP_API_ID_hipMemRelease: return "hipMemRelease"; + case HIP_API_ID_hipMemRetainAllocationHandle: return "hipMemRetainAllocationHandle"; + case HIP_API_ID_hipMemSetAccess: return "hipMemSetAccess"; + case HIP_API_ID_hipMemUnmap: return "hipMemUnmap"; + case HIP_API_ID_hipMemcpy: return "hipMemcpy"; + case HIP_API_ID_hipMemcpy2D: return "hipMemcpy2D"; + case HIP_API_ID_hipMemcpy2DArrayToArray: return "hipMemcpy2DArrayToArray"; + case HIP_API_ID_hipMemcpy2DAsync: return "hipMemcpy2DAsync"; + case HIP_API_ID_hipMemcpy2DFromArray: return "hipMemcpy2DFromArray"; + case HIP_API_ID_hipMemcpy2DFromArrayAsync: return "hipMemcpy2DFromArrayAsync"; + case HIP_API_ID_hipMemcpy2DToArray: return "hipMemcpy2DToArray"; + case HIP_API_ID_hipMemcpy2DToArrayAsync: return "hipMemcpy2DToArrayAsync"; + case HIP_API_ID_hipMemcpy3D: return "hipMemcpy3D"; + case HIP_API_ID_hipMemcpy3DAsync: return "hipMemcpy3DAsync"; + case HIP_API_ID_hipMemcpyAsync: return "hipMemcpyAsync"; + case HIP_API_ID_hipMemcpyAtoA: return "hipMemcpyAtoA"; + case HIP_API_ID_hipMemcpyAtoD: return "hipMemcpyAtoD"; + case HIP_API_ID_hipMemcpyAtoH: return "hipMemcpyAtoH"; + case HIP_API_ID_hipMemcpyAtoHAsync: return "hipMemcpyAtoHAsync"; + case HIP_API_ID_hipMemcpyDtoA: return "hipMemcpyDtoA"; + case HIP_API_ID_hipMemcpyDtoD: return "hipMemcpyDtoD"; + case HIP_API_ID_hipMemcpyDtoDAsync: return "hipMemcpyDtoDAsync"; + case HIP_API_ID_hipMemcpyDtoH: return "hipMemcpyDtoH"; + case HIP_API_ID_hipMemcpyDtoHAsync: return "hipMemcpyDtoHAsync"; + case HIP_API_ID_hipMemcpyFromArray: return "hipMemcpyFromArray"; + case HIP_API_ID_hipMemcpyFromSymbol: return "hipMemcpyFromSymbol"; + case HIP_API_ID_hipMemcpyFromSymbolAsync: return "hipMemcpyFromSymbolAsync"; + case HIP_API_ID_hipMemcpyHtoA: return "hipMemcpyHtoA"; + case HIP_API_ID_hipMemcpyHtoAAsync: return "hipMemcpyHtoAAsync"; + case HIP_API_ID_hipMemcpyHtoD: return "hipMemcpyHtoD"; + case HIP_API_ID_hipMemcpyHtoDAsync: return "hipMemcpyHtoDAsync"; + case HIP_API_ID_hipMemcpyParam2D: return "hipMemcpyParam2D"; + case HIP_API_ID_hipMemcpyParam2DAsync: return "hipMemcpyParam2DAsync"; + case HIP_API_ID_hipMemcpyPeer: return "hipMemcpyPeer"; + case HIP_API_ID_hipMemcpyPeerAsync: return "hipMemcpyPeerAsync"; + case HIP_API_ID_hipMemcpyToArray: return "hipMemcpyToArray"; + case HIP_API_ID_hipMemcpyToSymbol: return "hipMemcpyToSymbol"; + case HIP_API_ID_hipMemcpyToSymbolAsync: return "hipMemcpyToSymbolAsync"; + case HIP_API_ID_hipMemcpyWithStream: return "hipMemcpyWithStream"; + case HIP_API_ID_hipMemset: return "hipMemset"; + case HIP_API_ID_hipMemset2D: return "hipMemset2D"; + case HIP_API_ID_hipMemset2DAsync: return "hipMemset2DAsync"; + case HIP_API_ID_hipMemset3D: return "hipMemset3D"; + case HIP_API_ID_hipMemset3DAsync: return "hipMemset3DAsync"; + case HIP_API_ID_hipMemsetAsync: return "hipMemsetAsync"; + case HIP_API_ID_hipMemsetD16: return "hipMemsetD16"; + case HIP_API_ID_hipMemsetD16Async: return "hipMemsetD16Async"; + case HIP_API_ID_hipMemsetD32: return "hipMemsetD32"; + case HIP_API_ID_hipMemsetD32Async: return "hipMemsetD32Async"; + case HIP_API_ID_hipMemsetD8: return "hipMemsetD8"; + case HIP_API_ID_hipMemsetD8Async: return "hipMemsetD8Async"; + case HIP_API_ID_hipMipmappedArrayCreate: return "hipMipmappedArrayCreate"; + case HIP_API_ID_hipMipmappedArrayDestroy: return "hipMipmappedArrayDestroy"; + case HIP_API_ID_hipMipmappedArrayGetLevel: return "hipMipmappedArrayGetLevel"; + case HIP_API_ID_hipModuleGetFunction: return "hipModuleGetFunction"; + case HIP_API_ID_hipModuleGetGlobal: return "hipModuleGetGlobal"; + case HIP_API_ID_hipModuleGetTexRef: return "hipModuleGetTexRef"; + case HIP_API_ID_hipModuleLaunchCooperativeKernel: return "hipModuleLaunchCooperativeKernel"; + case HIP_API_ID_hipModuleLaunchCooperativeKernelMultiDevice: return "hipModuleLaunchCooperativeKernelMultiDevice"; + case HIP_API_ID_hipModuleLaunchKernel: return "hipModuleLaunchKernel"; + case HIP_API_ID_hipModuleLoad: return "hipModuleLoad"; + case HIP_API_ID_hipModuleLoadData: return "hipModuleLoadData"; + case HIP_API_ID_hipModuleLoadDataEx: return "hipModuleLoadDataEx"; + case HIP_API_ID_hipModuleOccupancyMaxActiveBlocksPerMultiprocessor: return "hipModuleOccupancyMaxActiveBlocksPerMultiprocessor"; + case HIP_API_ID_hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags: return "hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags"; + case HIP_API_ID_hipModuleOccupancyMaxPotentialBlockSize: return "hipModuleOccupancyMaxPotentialBlockSize"; + case HIP_API_ID_hipModuleOccupancyMaxPotentialBlockSizeWithFlags: return "hipModuleOccupancyMaxPotentialBlockSizeWithFlags"; + case HIP_API_ID_hipModuleUnload: return "hipModuleUnload"; + case HIP_API_ID_hipOccupancyMaxActiveBlocksPerMultiprocessor: return "hipOccupancyMaxActiveBlocksPerMultiprocessor"; + case HIP_API_ID_hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags: return "hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags"; + case HIP_API_ID_hipOccupancyMaxPotentialBlockSize: return "hipOccupancyMaxPotentialBlockSize"; + case HIP_API_ID_hipPeekAtLastError: return "hipPeekAtLastError"; + case HIP_API_ID_hipPointerGetAttribute: return "hipPointerGetAttribute"; + case HIP_API_ID_hipPointerGetAttributes: return "hipPointerGetAttributes"; + case HIP_API_ID_hipPointerSetAttribute: return "hipPointerSetAttribute"; + case HIP_API_ID_hipProfilerStart: return "hipProfilerStart"; + case HIP_API_ID_hipProfilerStop: return "hipProfilerStop"; + case HIP_API_ID_hipRuntimeGetVersion: return "hipRuntimeGetVersion"; + case HIP_API_ID_hipSetDevice: return "hipSetDevice"; + case HIP_API_ID_hipSetDeviceFlags: return "hipSetDeviceFlags"; + case HIP_API_ID_hipSetValidDevices: return "hipSetValidDevices"; + case HIP_API_ID_hipSetupArgument: return "hipSetupArgument"; + case HIP_API_ID_hipSignalExternalSemaphoresAsync: return "hipSignalExternalSemaphoresAsync"; + case HIP_API_ID_hipStreamAddCallback: return "hipStreamAddCallback"; + case HIP_API_ID_hipStreamAttachMemAsync: return "hipStreamAttachMemAsync"; + case HIP_API_ID_hipStreamBeginCapture: return "hipStreamBeginCapture"; + case HIP_API_ID_hipStreamBeginCaptureToGraph: return "hipStreamBeginCaptureToGraph"; + case HIP_API_ID_hipStreamCreate: return "hipStreamCreate"; + case HIP_API_ID_hipStreamCreateWithFlags: return "hipStreamCreateWithFlags"; + case HIP_API_ID_hipStreamCreateWithPriority: return "hipStreamCreateWithPriority"; + case HIP_API_ID_hipStreamDestroy: return "hipStreamDestroy"; + case HIP_API_ID_hipStreamEndCapture: return "hipStreamEndCapture"; + case HIP_API_ID_hipStreamGetCaptureInfo: return "hipStreamGetCaptureInfo"; + case HIP_API_ID_hipStreamGetCaptureInfo_v2: return "hipStreamGetCaptureInfo_v2"; + case HIP_API_ID_hipStreamGetDevice: return "hipStreamGetDevice"; + case HIP_API_ID_hipStreamGetFlags: return "hipStreamGetFlags"; + case HIP_API_ID_hipStreamGetPriority: return "hipStreamGetPriority"; + case HIP_API_ID_hipStreamIsCapturing: return "hipStreamIsCapturing"; + case HIP_API_ID_hipStreamQuery: return "hipStreamQuery"; + case HIP_API_ID_hipStreamSynchronize: return "hipStreamSynchronize"; + case HIP_API_ID_hipStreamUpdateCaptureDependencies: return "hipStreamUpdateCaptureDependencies"; + case HIP_API_ID_hipStreamWaitEvent: return "hipStreamWaitEvent"; + case HIP_API_ID_hipStreamWaitValue32: return "hipStreamWaitValue32"; + case HIP_API_ID_hipStreamWaitValue64: return "hipStreamWaitValue64"; + case HIP_API_ID_hipStreamWriteValue32: return "hipStreamWriteValue32"; + case HIP_API_ID_hipStreamWriteValue64: return "hipStreamWriteValue64"; + case HIP_API_ID_hipTexRefGetAddress: return "hipTexRefGetAddress"; + case HIP_API_ID_hipTexRefGetArray: return "hipTexRefGetArray"; + case HIP_API_ID_hipTexRefGetBorderColor: return "hipTexRefGetBorderColor"; + case HIP_API_ID_hipTexRefGetFlags: return "hipTexRefGetFlags"; + case HIP_API_ID_hipTexRefGetFormat: return "hipTexRefGetFormat"; + case HIP_API_ID_hipTexRefGetMaxAnisotropy: return "hipTexRefGetMaxAnisotropy"; + case HIP_API_ID_hipTexRefGetMipMappedArray: return "hipTexRefGetMipMappedArray"; + case HIP_API_ID_hipTexRefGetMipmapLevelBias: return "hipTexRefGetMipmapLevelBias"; + case HIP_API_ID_hipTexRefGetMipmapLevelClamp: return "hipTexRefGetMipmapLevelClamp"; + case HIP_API_ID_hipTexRefSetAddress: return "hipTexRefSetAddress"; + case HIP_API_ID_hipTexRefSetAddress2D: return "hipTexRefSetAddress2D"; + case HIP_API_ID_hipTexRefSetArray: return "hipTexRefSetArray"; + case HIP_API_ID_hipTexRefSetBorderColor: return "hipTexRefSetBorderColor"; + case HIP_API_ID_hipTexRefSetFlags: return "hipTexRefSetFlags"; + case HIP_API_ID_hipTexRefSetFormat: return "hipTexRefSetFormat"; + case HIP_API_ID_hipTexRefSetMaxAnisotropy: return "hipTexRefSetMaxAnisotropy"; + case HIP_API_ID_hipTexRefSetMipmapLevelBias: return "hipTexRefSetMipmapLevelBias"; + case HIP_API_ID_hipTexRefSetMipmapLevelClamp: return "hipTexRefSetMipmapLevelClamp"; + case HIP_API_ID_hipTexRefSetMipmappedArray: return "hipTexRefSetMipmappedArray"; + case HIP_API_ID_hipThreadExchangeStreamCaptureMode: return "hipThreadExchangeStreamCaptureMode"; + case HIP_API_ID_hipUserObjectCreate: return "hipUserObjectCreate"; + case HIP_API_ID_hipUserObjectRelease: return "hipUserObjectRelease"; + case HIP_API_ID_hipUserObjectRetain: return "hipUserObjectRetain"; + case HIP_API_ID_hipWaitExternalSemaphoresAsync: return "hipWaitExternalSemaphoresAsync"; + }; + return "unknown"; +}; + +#include +// Return the HIP API callback ID for a given name +static inline uint32_t hipApiIdByName(const char* name) { + if (strcmp("__hipPopCallConfiguration", name) == 0) return HIP_API_ID___hipPopCallConfiguration; + if (strcmp("__hipPushCallConfiguration", name) == 0) return HIP_API_ID___hipPushCallConfiguration; + if (strcmp("hipArray3DCreate", name) == 0) return HIP_API_ID_hipArray3DCreate; + if (strcmp("hipArray3DGetDescriptor", name) == 0) return HIP_API_ID_hipArray3DGetDescriptor; + if (strcmp("hipArrayCreate", name) == 0) return HIP_API_ID_hipArrayCreate; + if (strcmp("hipArrayDestroy", name) == 0) return HIP_API_ID_hipArrayDestroy; + if (strcmp("hipArrayGetDescriptor", name) == 0) return HIP_API_ID_hipArrayGetDescriptor; + if (strcmp("hipArrayGetInfo", name) == 0) return HIP_API_ID_hipArrayGetInfo; + if (strcmp("hipChooseDeviceR0000", name) == 0) return HIP_API_ID_hipChooseDeviceR0000; + if (strcmp("hipChooseDeviceR0600", name) == 0) return HIP_API_ID_hipChooseDeviceR0600; + if (strcmp("hipConfigureCall", name) == 0) return HIP_API_ID_hipConfigureCall; + if (strcmp("hipCreateSurfaceObject", name) == 0) return HIP_API_ID_hipCreateSurfaceObject; + if (strcmp("hipCtxCreate", name) == 0) return HIP_API_ID_hipCtxCreate; + if (strcmp("hipCtxDestroy", name) == 0) return HIP_API_ID_hipCtxDestroy; + if (strcmp("hipCtxDisablePeerAccess", name) == 0) return HIP_API_ID_hipCtxDisablePeerAccess; + if (strcmp("hipCtxEnablePeerAccess", name) == 0) return HIP_API_ID_hipCtxEnablePeerAccess; + if (strcmp("hipCtxGetApiVersion", name) == 0) return HIP_API_ID_hipCtxGetApiVersion; + if (strcmp("hipCtxGetCacheConfig", name) == 0) return HIP_API_ID_hipCtxGetCacheConfig; + if (strcmp("hipCtxGetCurrent", name) == 0) return HIP_API_ID_hipCtxGetCurrent; + if (strcmp("hipCtxGetDevice", name) == 0) return HIP_API_ID_hipCtxGetDevice; + if (strcmp("hipCtxGetFlags", name) == 0) return HIP_API_ID_hipCtxGetFlags; + if (strcmp("hipCtxGetSharedMemConfig", name) == 0) return HIP_API_ID_hipCtxGetSharedMemConfig; + if (strcmp("hipCtxPopCurrent", name) == 0) return HIP_API_ID_hipCtxPopCurrent; + if (strcmp("hipCtxPushCurrent", name) == 0) return HIP_API_ID_hipCtxPushCurrent; + if (strcmp("hipCtxSetCacheConfig", name) == 0) return HIP_API_ID_hipCtxSetCacheConfig; + if (strcmp("hipCtxSetCurrent", name) == 0) return HIP_API_ID_hipCtxSetCurrent; + if (strcmp("hipCtxSetSharedMemConfig", name) == 0) return HIP_API_ID_hipCtxSetSharedMemConfig; + if (strcmp("hipCtxSynchronize", name) == 0) return HIP_API_ID_hipCtxSynchronize; + if (strcmp("hipDestroyExternalMemory", name) == 0) return HIP_API_ID_hipDestroyExternalMemory; + if (strcmp("hipDestroyExternalSemaphore", name) == 0) return HIP_API_ID_hipDestroyExternalSemaphore; + if (strcmp("hipDestroySurfaceObject", name) == 0) return HIP_API_ID_hipDestroySurfaceObject; + if (strcmp("hipDeviceCanAccessPeer", name) == 0) return HIP_API_ID_hipDeviceCanAccessPeer; + if (strcmp("hipDeviceComputeCapability", name) == 0) return HIP_API_ID_hipDeviceComputeCapability; + if (strcmp("hipDeviceDisablePeerAccess", name) == 0) return HIP_API_ID_hipDeviceDisablePeerAccess; + if (strcmp("hipDeviceEnablePeerAccess", name) == 0) return HIP_API_ID_hipDeviceEnablePeerAccess; + if (strcmp("hipDeviceGet", name) == 0) return HIP_API_ID_hipDeviceGet; + if (strcmp("hipDeviceGetAttribute", name) == 0) return HIP_API_ID_hipDeviceGetAttribute; + if (strcmp("hipDeviceGetByPCIBusId", name) == 0) return HIP_API_ID_hipDeviceGetByPCIBusId; + if (strcmp("hipDeviceGetCacheConfig", name) == 0) return HIP_API_ID_hipDeviceGetCacheConfig; + if (strcmp("hipDeviceGetDefaultMemPool", name) == 0) return HIP_API_ID_hipDeviceGetDefaultMemPool; + if (strcmp("hipDeviceGetGraphMemAttribute", name) == 0) return HIP_API_ID_hipDeviceGetGraphMemAttribute; + if (strcmp("hipDeviceGetLimit", name) == 0) return HIP_API_ID_hipDeviceGetLimit; + if (strcmp("hipDeviceGetMemPool", name) == 0) return HIP_API_ID_hipDeviceGetMemPool; + if (strcmp("hipDeviceGetName", name) == 0) return HIP_API_ID_hipDeviceGetName; + if (strcmp("hipDeviceGetP2PAttribute", name) == 0) return HIP_API_ID_hipDeviceGetP2PAttribute; + if (strcmp("hipDeviceGetPCIBusId", name) == 0) return HIP_API_ID_hipDeviceGetPCIBusId; + if (strcmp("hipDeviceGetSharedMemConfig", name) == 0) return HIP_API_ID_hipDeviceGetSharedMemConfig; + if (strcmp("hipDeviceGetStreamPriorityRange", name) == 0) return HIP_API_ID_hipDeviceGetStreamPriorityRange; + if (strcmp("hipDeviceGetUuid", name) == 0) return HIP_API_ID_hipDeviceGetUuid; + if (strcmp("hipDeviceGraphMemTrim", name) == 0) return HIP_API_ID_hipDeviceGraphMemTrim; + if (strcmp("hipDevicePrimaryCtxGetState", name) == 0) return HIP_API_ID_hipDevicePrimaryCtxGetState; + if (strcmp("hipDevicePrimaryCtxRelease", name) == 0) return HIP_API_ID_hipDevicePrimaryCtxRelease; + if (strcmp("hipDevicePrimaryCtxReset", name) == 0) return HIP_API_ID_hipDevicePrimaryCtxReset; + if (strcmp("hipDevicePrimaryCtxRetain", name) == 0) return HIP_API_ID_hipDevicePrimaryCtxRetain; + if (strcmp("hipDevicePrimaryCtxSetFlags", name) == 0) return HIP_API_ID_hipDevicePrimaryCtxSetFlags; + if (strcmp("hipDeviceReset", name) == 0) return HIP_API_ID_hipDeviceReset; + if (strcmp("hipDeviceSetCacheConfig", name) == 0) return HIP_API_ID_hipDeviceSetCacheConfig; + if (strcmp("hipDeviceSetGraphMemAttribute", name) == 0) return HIP_API_ID_hipDeviceSetGraphMemAttribute; + if (strcmp("hipDeviceSetLimit", name) == 0) return HIP_API_ID_hipDeviceSetLimit; + if (strcmp("hipDeviceSetMemPool", name) == 0) return HIP_API_ID_hipDeviceSetMemPool; + if (strcmp("hipDeviceSetSharedMemConfig", name) == 0) return HIP_API_ID_hipDeviceSetSharedMemConfig; + if (strcmp("hipDeviceSynchronize", name) == 0) return HIP_API_ID_hipDeviceSynchronize; + if (strcmp("hipDeviceTotalMem", name) == 0) return HIP_API_ID_hipDeviceTotalMem; + if (strcmp("hipDriverGetVersion", name) == 0) return HIP_API_ID_hipDriverGetVersion; + if (strcmp("hipDrvGraphAddMemcpyNode", name) == 0) return HIP_API_ID_hipDrvGraphAddMemcpyNode; + if (strcmp("hipDrvGraphAddMemsetNode", name) == 0) return HIP_API_ID_hipDrvGraphAddMemsetNode; + if (strcmp("hipDrvMemcpy2DUnaligned", name) == 0) return HIP_API_ID_hipDrvMemcpy2DUnaligned; + if (strcmp("hipDrvMemcpy3D", name) == 0) return HIP_API_ID_hipDrvMemcpy3D; + if (strcmp("hipDrvMemcpy3DAsync", name) == 0) return HIP_API_ID_hipDrvMemcpy3DAsync; + if (strcmp("hipDrvPointerGetAttributes", name) == 0) return HIP_API_ID_hipDrvPointerGetAttributes; + if (strcmp("hipEventCreate", name) == 0) return HIP_API_ID_hipEventCreate; + if (strcmp("hipEventCreateWithFlags", name) == 0) return HIP_API_ID_hipEventCreateWithFlags; + if (strcmp("hipEventDestroy", name) == 0) return HIP_API_ID_hipEventDestroy; + if (strcmp("hipEventElapsedTime", name) == 0) return HIP_API_ID_hipEventElapsedTime; + if (strcmp("hipEventQuery", name) == 0) return HIP_API_ID_hipEventQuery; + if (strcmp("hipEventRecord", name) == 0) return HIP_API_ID_hipEventRecord; + if (strcmp("hipEventSynchronize", name) == 0) return HIP_API_ID_hipEventSynchronize; + if (strcmp("hipExtGetLastError", name) == 0) return HIP_API_ID_hipExtGetLastError; + if (strcmp("hipExtGetLinkTypeAndHopCount", name) == 0) return HIP_API_ID_hipExtGetLinkTypeAndHopCount; + if (strcmp("hipExtLaunchKernel", name) == 0) return HIP_API_ID_hipExtLaunchKernel; + if (strcmp("hipExtLaunchMultiKernelMultiDevice", name) == 0) return HIP_API_ID_hipExtLaunchMultiKernelMultiDevice; + if (strcmp("hipExtMallocWithFlags", name) == 0) return HIP_API_ID_hipExtMallocWithFlags; + if (strcmp("hipExtModuleLaunchKernel", name) == 0) return HIP_API_ID_hipExtModuleLaunchKernel; + if (strcmp("hipExtStreamCreateWithCUMask", name) == 0) return HIP_API_ID_hipExtStreamCreateWithCUMask; + if (strcmp("hipExtStreamGetCUMask", name) == 0) return HIP_API_ID_hipExtStreamGetCUMask; + if (strcmp("hipExternalMemoryGetMappedBuffer", name) == 0) return HIP_API_ID_hipExternalMemoryGetMappedBuffer; + if (strcmp("hipExternalMemoryGetMappedMipmappedArray", name) == 0) return HIP_API_ID_hipExternalMemoryGetMappedMipmappedArray; + if (strcmp("hipFree", name) == 0) return HIP_API_ID_hipFree; + if (strcmp("hipFreeArray", name) == 0) return HIP_API_ID_hipFreeArray; + if (strcmp("hipFreeAsync", name) == 0) return HIP_API_ID_hipFreeAsync; + if (strcmp("hipFreeHost", name) == 0) return HIP_API_ID_hipFreeHost; + if (strcmp("hipFreeMipmappedArray", name) == 0) return HIP_API_ID_hipFreeMipmappedArray; + if (strcmp("hipFuncGetAttribute", name) == 0) return HIP_API_ID_hipFuncGetAttribute; + if (strcmp("hipFuncGetAttributes", name) == 0) return HIP_API_ID_hipFuncGetAttributes; + if (strcmp("hipFuncSetAttribute", name) == 0) return HIP_API_ID_hipFuncSetAttribute; + if (strcmp("hipFuncSetCacheConfig", name) == 0) return HIP_API_ID_hipFuncSetCacheConfig; + if (strcmp("hipFuncSetSharedMemConfig", name) == 0) return HIP_API_ID_hipFuncSetSharedMemConfig; + if (strcmp("hipGLGetDevices", name) == 0) return HIP_API_ID_hipGLGetDevices; + if (strcmp("hipGetChannelDesc", name) == 0) return HIP_API_ID_hipGetChannelDesc; + if (strcmp("hipGetDevice", name) == 0) return HIP_API_ID_hipGetDevice; + if (strcmp("hipGetDeviceCount", name) == 0) return HIP_API_ID_hipGetDeviceCount; + if (strcmp("hipGetDeviceFlags", name) == 0) return HIP_API_ID_hipGetDeviceFlags; + if (strcmp("hipGetDevicePropertiesR0000", name) == 0) return HIP_API_ID_hipGetDevicePropertiesR0000; + if (strcmp("hipGetDevicePropertiesR0600", name) == 0) return HIP_API_ID_hipGetDevicePropertiesR0600; + if (strcmp("hipGetErrorString", name) == 0) return HIP_API_ID_hipGetErrorString; + if (strcmp("hipGetFuncBySymbol", name) == 0) return HIP_API_ID_hipGetFuncBySymbol; + if (strcmp("hipGetLastError", name) == 0) return HIP_API_ID_hipGetLastError; + if (strcmp("hipGetMipmappedArrayLevel", name) == 0) return HIP_API_ID_hipGetMipmappedArrayLevel; + if (strcmp("hipGetProcAddress", name) == 0) return HIP_API_ID_hipGetProcAddress; + if (strcmp("hipGetSymbolAddress", name) == 0) return HIP_API_ID_hipGetSymbolAddress; + if (strcmp("hipGetSymbolSize", name) == 0) return HIP_API_ID_hipGetSymbolSize; + if (strcmp("hipGraphAddChildGraphNode", name) == 0) return HIP_API_ID_hipGraphAddChildGraphNode; + if (strcmp("hipGraphAddDependencies", name) == 0) return HIP_API_ID_hipGraphAddDependencies; + if (strcmp("hipGraphAddEmptyNode", name) == 0) return HIP_API_ID_hipGraphAddEmptyNode; + if (strcmp("hipGraphAddEventRecordNode", name) == 0) return HIP_API_ID_hipGraphAddEventRecordNode; + if (strcmp("hipGraphAddEventWaitNode", name) == 0) return HIP_API_ID_hipGraphAddEventWaitNode; + if (strcmp("hipGraphAddExternalSemaphoresSignalNode", name) == 0) return HIP_API_ID_hipGraphAddExternalSemaphoresSignalNode; + if (strcmp("hipGraphAddExternalSemaphoresWaitNode", name) == 0) return HIP_API_ID_hipGraphAddExternalSemaphoresWaitNode; + if (strcmp("hipGraphAddHostNode", name) == 0) return HIP_API_ID_hipGraphAddHostNode; + if (strcmp("hipGraphAddKernelNode", name) == 0) return HIP_API_ID_hipGraphAddKernelNode; + if (strcmp("hipGraphAddMemAllocNode", name) == 0) return HIP_API_ID_hipGraphAddMemAllocNode; + if (strcmp("hipGraphAddMemFreeNode", name) == 0) return HIP_API_ID_hipGraphAddMemFreeNode; + if (strcmp("hipGraphAddMemcpyNode", name) == 0) return HIP_API_ID_hipGraphAddMemcpyNode; + if (strcmp("hipGraphAddMemcpyNode1D", name) == 0) return HIP_API_ID_hipGraphAddMemcpyNode1D; + if (strcmp("hipGraphAddMemcpyNodeFromSymbol", name) == 0) return HIP_API_ID_hipGraphAddMemcpyNodeFromSymbol; + if (strcmp("hipGraphAddMemcpyNodeToSymbol", name) == 0) return HIP_API_ID_hipGraphAddMemcpyNodeToSymbol; + if (strcmp("hipGraphAddMemsetNode", name) == 0) return HIP_API_ID_hipGraphAddMemsetNode; + if (strcmp("hipGraphAddNode", name) == 0) return HIP_API_ID_hipGraphAddNode; + if (strcmp("hipGraphChildGraphNodeGetGraph", name) == 0) return HIP_API_ID_hipGraphChildGraphNodeGetGraph; + if (strcmp("hipGraphClone", name) == 0) return HIP_API_ID_hipGraphClone; + if (strcmp("hipGraphCreate", name) == 0) return HIP_API_ID_hipGraphCreate; + if (strcmp("hipGraphDebugDotPrint", name) == 0) return HIP_API_ID_hipGraphDebugDotPrint; + if (strcmp("hipGraphDestroy", name) == 0) return HIP_API_ID_hipGraphDestroy; + if (strcmp("hipGraphDestroyNode", name) == 0) return HIP_API_ID_hipGraphDestroyNode; + if (strcmp("hipGraphEventRecordNodeGetEvent", name) == 0) return HIP_API_ID_hipGraphEventRecordNodeGetEvent; + if (strcmp("hipGraphEventRecordNodeSetEvent", name) == 0) return HIP_API_ID_hipGraphEventRecordNodeSetEvent; + if (strcmp("hipGraphEventWaitNodeGetEvent", name) == 0) return HIP_API_ID_hipGraphEventWaitNodeGetEvent; + if (strcmp("hipGraphEventWaitNodeSetEvent", name) == 0) return HIP_API_ID_hipGraphEventWaitNodeSetEvent; + if (strcmp("hipGraphExecChildGraphNodeSetParams", name) == 0) return HIP_API_ID_hipGraphExecChildGraphNodeSetParams; + if (strcmp("hipGraphExecDestroy", name) == 0) return HIP_API_ID_hipGraphExecDestroy; + if (strcmp("hipGraphExecEventRecordNodeSetEvent", name) == 0) return HIP_API_ID_hipGraphExecEventRecordNodeSetEvent; + if (strcmp("hipGraphExecEventWaitNodeSetEvent", name) == 0) return HIP_API_ID_hipGraphExecEventWaitNodeSetEvent; + if (strcmp("hipGraphExecExternalSemaphoresSignalNodeSetParams", name) == 0) return HIP_API_ID_hipGraphExecExternalSemaphoresSignalNodeSetParams; + if (strcmp("hipGraphExecExternalSemaphoresWaitNodeSetParams", name) == 0) return HIP_API_ID_hipGraphExecExternalSemaphoresWaitNodeSetParams; + if (strcmp("hipGraphExecHostNodeSetParams", name) == 0) return HIP_API_ID_hipGraphExecHostNodeSetParams; + if (strcmp("hipGraphExecKernelNodeSetParams", name) == 0) return HIP_API_ID_hipGraphExecKernelNodeSetParams; + if (strcmp("hipGraphExecMemcpyNodeSetParams", name) == 0) return HIP_API_ID_hipGraphExecMemcpyNodeSetParams; + if (strcmp("hipGraphExecMemcpyNodeSetParams1D", name) == 0) return HIP_API_ID_hipGraphExecMemcpyNodeSetParams1D; + if (strcmp("hipGraphExecMemcpyNodeSetParamsFromSymbol", name) == 0) return HIP_API_ID_hipGraphExecMemcpyNodeSetParamsFromSymbol; + if (strcmp("hipGraphExecMemcpyNodeSetParamsToSymbol", name) == 0) return HIP_API_ID_hipGraphExecMemcpyNodeSetParamsToSymbol; + if (strcmp("hipGraphExecMemsetNodeSetParams", name) == 0) return HIP_API_ID_hipGraphExecMemsetNodeSetParams; + if (strcmp("hipGraphExecUpdate", name) == 0) return HIP_API_ID_hipGraphExecUpdate; + if (strcmp("hipGraphExternalSemaphoresSignalNodeGetParams", name) == 0) return HIP_API_ID_hipGraphExternalSemaphoresSignalNodeGetParams; + if (strcmp("hipGraphExternalSemaphoresSignalNodeSetParams", name) == 0) return HIP_API_ID_hipGraphExternalSemaphoresSignalNodeSetParams; + if (strcmp("hipGraphExternalSemaphoresWaitNodeGetParams", name) == 0) return HIP_API_ID_hipGraphExternalSemaphoresWaitNodeGetParams; + if (strcmp("hipGraphExternalSemaphoresWaitNodeSetParams", name) == 0) return HIP_API_ID_hipGraphExternalSemaphoresWaitNodeSetParams; + if (strcmp("hipGraphGetEdges", name) == 0) return HIP_API_ID_hipGraphGetEdges; + if (strcmp("hipGraphGetNodes", name) == 0) return HIP_API_ID_hipGraphGetNodes; + if (strcmp("hipGraphGetRootNodes", name) == 0) return HIP_API_ID_hipGraphGetRootNodes; + if (strcmp("hipGraphHostNodeGetParams", name) == 0) return HIP_API_ID_hipGraphHostNodeGetParams; + if (strcmp("hipGraphHostNodeSetParams", name) == 0) return HIP_API_ID_hipGraphHostNodeSetParams; + if (strcmp("hipGraphInstantiate", name) == 0) return HIP_API_ID_hipGraphInstantiate; + if (strcmp("hipGraphInstantiateWithFlags", name) == 0) return HIP_API_ID_hipGraphInstantiateWithFlags; + if (strcmp("hipGraphInstantiateWithParams", name) == 0) return HIP_API_ID_hipGraphInstantiateWithParams; + if (strcmp("hipGraphKernelNodeCopyAttributes", name) == 0) return HIP_API_ID_hipGraphKernelNodeCopyAttributes; + if (strcmp("hipGraphKernelNodeGetAttribute", name) == 0) return HIP_API_ID_hipGraphKernelNodeGetAttribute; + if (strcmp("hipGraphKernelNodeGetParams", name) == 0) return HIP_API_ID_hipGraphKernelNodeGetParams; + if (strcmp("hipGraphKernelNodeSetAttribute", name) == 0) return HIP_API_ID_hipGraphKernelNodeSetAttribute; + if (strcmp("hipGraphKernelNodeSetParams", name) == 0) return HIP_API_ID_hipGraphKernelNodeSetParams; + if (strcmp("hipGraphLaunch", name) == 0) return HIP_API_ID_hipGraphLaunch; + if (strcmp("hipGraphMemAllocNodeGetParams", name) == 0) return HIP_API_ID_hipGraphMemAllocNodeGetParams; + if (strcmp("hipGraphMemFreeNodeGetParams", name) == 0) return HIP_API_ID_hipGraphMemFreeNodeGetParams; + if (strcmp("hipGraphMemcpyNodeGetParams", name) == 0) return HIP_API_ID_hipGraphMemcpyNodeGetParams; + if (strcmp("hipGraphMemcpyNodeSetParams", name) == 0) return HIP_API_ID_hipGraphMemcpyNodeSetParams; + if (strcmp("hipGraphMemcpyNodeSetParams1D", name) == 0) return HIP_API_ID_hipGraphMemcpyNodeSetParams1D; + if (strcmp("hipGraphMemcpyNodeSetParamsFromSymbol", name) == 0) return HIP_API_ID_hipGraphMemcpyNodeSetParamsFromSymbol; + if (strcmp("hipGraphMemcpyNodeSetParamsToSymbol", name) == 0) return HIP_API_ID_hipGraphMemcpyNodeSetParamsToSymbol; + if (strcmp("hipGraphMemsetNodeGetParams", name) == 0) return HIP_API_ID_hipGraphMemsetNodeGetParams; + if (strcmp("hipGraphMemsetNodeSetParams", name) == 0) return HIP_API_ID_hipGraphMemsetNodeSetParams; + if (strcmp("hipGraphNodeFindInClone", name) == 0) return HIP_API_ID_hipGraphNodeFindInClone; + if (strcmp("hipGraphNodeGetDependencies", name) == 0) return HIP_API_ID_hipGraphNodeGetDependencies; + if (strcmp("hipGraphNodeGetDependentNodes", name) == 0) return HIP_API_ID_hipGraphNodeGetDependentNodes; + if (strcmp("hipGraphNodeGetEnabled", name) == 0) return HIP_API_ID_hipGraphNodeGetEnabled; + if (strcmp("hipGraphNodeGetType", name) == 0) return HIP_API_ID_hipGraphNodeGetType; + if (strcmp("hipGraphNodeSetEnabled", name) == 0) return HIP_API_ID_hipGraphNodeSetEnabled; + if (strcmp("hipGraphReleaseUserObject", name) == 0) return HIP_API_ID_hipGraphReleaseUserObject; + if (strcmp("hipGraphRemoveDependencies", name) == 0) return HIP_API_ID_hipGraphRemoveDependencies; + if (strcmp("hipGraphRetainUserObject", name) == 0) return HIP_API_ID_hipGraphRetainUserObject; + if (strcmp("hipGraphUpload", name) == 0) return HIP_API_ID_hipGraphUpload; + if (strcmp("hipGraphicsGLRegisterBuffer", name) == 0) return HIP_API_ID_hipGraphicsGLRegisterBuffer; + if (strcmp("hipGraphicsGLRegisterImage", name) == 0) return HIP_API_ID_hipGraphicsGLRegisterImage; + if (strcmp("hipGraphicsMapResources", name) == 0) return HIP_API_ID_hipGraphicsMapResources; + if (strcmp("hipGraphicsResourceGetMappedPointer", name) == 0) return HIP_API_ID_hipGraphicsResourceGetMappedPointer; + if (strcmp("hipGraphicsSubResourceGetMappedArray", name) == 0) return HIP_API_ID_hipGraphicsSubResourceGetMappedArray; + if (strcmp("hipGraphicsUnmapResources", name) == 0) return HIP_API_ID_hipGraphicsUnmapResources; + if (strcmp("hipGraphicsUnregisterResource", name) == 0) return HIP_API_ID_hipGraphicsUnregisterResource; + if (strcmp("hipHccModuleLaunchKernel", name) == 0) return HIP_API_ID_hipHccModuleLaunchKernel; + if (strcmp("hipHostAlloc", name) == 0) return HIP_API_ID_hipHostAlloc; + if (strcmp("hipHostFree", name) == 0) return HIP_API_ID_hipHostFree; + if (strcmp("hipHostGetDevicePointer", name) == 0) return HIP_API_ID_hipHostGetDevicePointer; + if (strcmp("hipHostGetFlags", name) == 0) return HIP_API_ID_hipHostGetFlags; + if (strcmp("hipHostMalloc", name) == 0) return HIP_API_ID_hipHostMalloc; + if (strcmp("hipHostRegister", name) == 0) return HIP_API_ID_hipHostRegister; + if (strcmp("hipHostUnregister", name) == 0) return HIP_API_ID_hipHostUnregister; + if (strcmp("hipImportExternalMemory", name) == 0) return HIP_API_ID_hipImportExternalMemory; + if (strcmp("hipImportExternalSemaphore", name) == 0) return HIP_API_ID_hipImportExternalSemaphore; + if (strcmp("hipInit", name) == 0) return HIP_API_ID_hipInit; + if (strcmp("hipIpcCloseMemHandle", name) == 0) return HIP_API_ID_hipIpcCloseMemHandle; + if (strcmp("hipIpcGetEventHandle", name) == 0) return HIP_API_ID_hipIpcGetEventHandle; + if (strcmp("hipIpcGetMemHandle", name) == 0) return HIP_API_ID_hipIpcGetMemHandle; + if (strcmp("hipIpcOpenEventHandle", name) == 0) return HIP_API_ID_hipIpcOpenEventHandle; + if (strcmp("hipIpcOpenMemHandle", name) == 0) return HIP_API_ID_hipIpcOpenMemHandle; + if (strcmp("hipLaunchByPtr", name) == 0) return HIP_API_ID_hipLaunchByPtr; + if (strcmp("hipLaunchCooperativeKernel", name) == 0) return HIP_API_ID_hipLaunchCooperativeKernel; + if (strcmp("hipLaunchCooperativeKernelMultiDevice", name) == 0) return HIP_API_ID_hipLaunchCooperativeKernelMultiDevice; + if (strcmp("hipLaunchHostFunc", name) == 0) return HIP_API_ID_hipLaunchHostFunc; + if (strcmp("hipLaunchKernel", name) == 0) return HIP_API_ID_hipLaunchKernel; + if (strcmp("hipMalloc", name) == 0) return HIP_API_ID_hipMalloc; + if (strcmp("hipMalloc3D", name) == 0) return HIP_API_ID_hipMalloc3D; + if (strcmp("hipMalloc3DArray", name) == 0) return HIP_API_ID_hipMalloc3DArray; + if (strcmp("hipMallocArray", name) == 0) return HIP_API_ID_hipMallocArray; + if (strcmp("hipMallocAsync", name) == 0) return HIP_API_ID_hipMallocAsync; + if (strcmp("hipMallocFromPoolAsync", name) == 0) return HIP_API_ID_hipMallocFromPoolAsync; + if (strcmp("hipMallocHost", name) == 0) return HIP_API_ID_hipMallocHost; + if (strcmp("hipMallocManaged", name) == 0) return HIP_API_ID_hipMallocManaged; + if (strcmp("hipMallocMipmappedArray", name) == 0) return HIP_API_ID_hipMallocMipmappedArray; + if (strcmp("hipMallocPitch", name) == 0) return HIP_API_ID_hipMallocPitch; + if (strcmp("hipMemAddressFree", name) == 0) return HIP_API_ID_hipMemAddressFree; + if (strcmp("hipMemAddressReserve", name) == 0) return HIP_API_ID_hipMemAddressReserve; + if (strcmp("hipMemAdvise", name) == 0) return HIP_API_ID_hipMemAdvise; + if (strcmp("hipMemAllocHost", name) == 0) return HIP_API_ID_hipMemAllocHost; + if (strcmp("hipMemAllocPitch", name) == 0) return HIP_API_ID_hipMemAllocPitch; + if (strcmp("hipMemCreate", name) == 0) return HIP_API_ID_hipMemCreate; + if (strcmp("hipMemExportToShareableHandle", name) == 0) return HIP_API_ID_hipMemExportToShareableHandle; + if (strcmp("hipMemGetAccess", name) == 0) return HIP_API_ID_hipMemGetAccess; + if (strcmp("hipMemGetAddressRange", name) == 0) return HIP_API_ID_hipMemGetAddressRange; + if (strcmp("hipMemGetAllocationGranularity", name) == 0) return HIP_API_ID_hipMemGetAllocationGranularity; + if (strcmp("hipMemGetAllocationPropertiesFromHandle", name) == 0) return HIP_API_ID_hipMemGetAllocationPropertiesFromHandle; + if (strcmp("hipMemGetInfo", name) == 0) return HIP_API_ID_hipMemGetInfo; + if (strcmp("hipMemImportFromShareableHandle", name) == 0) return HIP_API_ID_hipMemImportFromShareableHandle; + if (strcmp("hipMemMap", name) == 0) return HIP_API_ID_hipMemMap; + if (strcmp("hipMemMapArrayAsync", name) == 0) return HIP_API_ID_hipMemMapArrayAsync; + if (strcmp("hipMemPoolCreate", name) == 0) return HIP_API_ID_hipMemPoolCreate; + if (strcmp("hipMemPoolDestroy", name) == 0) return HIP_API_ID_hipMemPoolDestroy; + if (strcmp("hipMemPoolExportPointer", name) == 0) return HIP_API_ID_hipMemPoolExportPointer; + if (strcmp("hipMemPoolExportToShareableHandle", name) == 0) return HIP_API_ID_hipMemPoolExportToShareableHandle; + if (strcmp("hipMemPoolGetAccess", name) == 0) return HIP_API_ID_hipMemPoolGetAccess; + if (strcmp("hipMemPoolGetAttribute", name) == 0) return HIP_API_ID_hipMemPoolGetAttribute; + if (strcmp("hipMemPoolImportFromShareableHandle", name) == 0) return HIP_API_ID_hipMemPoolImportFromShareableHandle; + if (strcmp("hipMemPoolImportPointer", name) == 0) return HIP_API_ID_hipMemPoolImportPointer; + if (strcmp("hipMemPoolSetAccess", name) == 0) return HIP_API_ID_hipMemPoolSetAccess; + if (strcmp("hipMemPoolSetAttribute", name) == 0) return HIP_API_ID_hipMemPoolSetAttribute; + if (strcmp("hipMemPoolTrimTo", name) == 0) return HIP_API_ID_hipMemPoolTrimTo; + if (strcmp("hipMemPrefetchAsync", name) == 0) return HIP_API_ID_hipMemPrefetchAsync; + if (strcmp("hipMemPtrGetInfo", name) == 0) return HIP_API_ID_hipMemPtrGetInfo; + if (strcmp("hipMemRangeGetAttribute", name) == 0) return HIP_API_ID_hipMemRangeGetAttribute; + if (strcmp("hipMemRangeGetAttributes", name) == 0) return HIP_API_ID_hipMemRangeGetAttributes; + if (strcmp("hipMemRelease", name) == 0) return HIP_API_ID_hipMemRelease; + if (strcmp("hipMemRetainAllocationHandle", name) == 0) return HIP_API_ID_hipMemRetainAllocationHandle; + if (strcmp("hipMemSetAccess", name) == 0) return HIP_API_ID_hipMemSetAccess; + if (strcmp("hipMemUnmap", name) == 0) return HIP_API_ID_hipMemUnmap; + if (strcmp("hipMemcpy", name) == 0) return HIP_API_ID_hipMemcpy; + if (strcmp("hipMemcpy2D", name) == 0) return HIP_API_ID_hipMemcpy2D; + if (strcmp("hipMemcpy2DArrayToArray", name) == 0) return HIP_API_ID_hipMemcpy2DArrayToArray; + if (strcmp("hipMemcpy2DAsync", name) == 0) return HIP_API_ID_hipMemcpy2DAsync; + if (strcmp("hipMemcpy2DFromArray", name) == 0) return HIP_API_ID_hipMemcpy2DFromArray; + if (strcmp("hipMemcpy2DFromArrayAsync", name) == 0) return HIP_API_ID_hipMemcpy2DFromArrayAsync; + if (strcmp("hipMemcpy2DToArray", name) == 0) return HIP_API_ID_hipMemcpy2DToArray; + if (strcmp("hipMemcpy2DToArrayAsync", name) == 0) return HIP_API_ID_hipMemcpy2DToArrayAsync; + if (strcmp("hipMemcpy3D", name) == 0) return HIP_API_ID_hipMemcpy3D; + if (strcmp("hipMemcpy3DAsync", name) == 0) return HIP_API_ID_hipMemcpy3DAsync; + if (strcmp("hipMemcpyAsync", name) == 0) return HIP_API_ID_hipMemcpyAsync; + if (strcmp("hipMemcpyAtoA", name) == 0) return HIP_API_ID_hipMemcpyAtoA; + if (strcmp("hipMemcpyAtoD", name) == 0) return HIP_API_ID_hipMemcpyAtoD; + if (strcmp("hipMemcpyAtoH", name) == 0) return HIP_API_ID_hipMemcpyAtoH; + if (strcmp("hipMemcpyAtoHAsync", name) == 0) return HIP_API_ID_hipMemcpyAtoHAsync; + if (strcmp("hipMemcpyDtoA", name) == 0) return HIP_API_ID_hipMemcpyDtoA; + if (strcmp("hipMemcpyDtoD", name) == 0) return HIP_API_ID_hipMemcpyDtoD; + if (strcmp("hipMemcpyDtoDAsync", name) == 0) return HIP_API_ID_hipMemcpyDtoDAsync; + if (strcmp("hipMemcpyDtoH", name) == 0) return HIP_API_ID_hipMemcpyDtoH; + if (strcmp("hipMemcpyDtoHAsync", name) == 0) return HIP_API_ID_hipMemcpyDtoHAsync; + if (strcmp("hipMemcpyFromArray", name) == 0) return HIP_API_ID_hipMemcpyFromArray; + if (strcmp("hipMemcpyFromSymbol", name) == 0) return HIP_API_ID_hipMemcpyFromSymbol; + if (strcmp("hipMemcpyFromSymbolAsync", name) == 0) return HIP_API_ID_hipMemcpyFromSymbolAsync; + if (strcmp("hipMemcpyHtoA", name) == 0) return HIP_API_ID_hipMemcpyHtoA; + if (strcmp("hipMemcpyHtoAAsync", name) == 0) return HIP_API_ID_hipMemcpyHtoAAsync; + if (strcmp("hipMemcpyHtoD", name) == 0) return HIP_API_ID_hipMemcpyHtoD; + if (strcmp("hipMemcpyHtoDAsync", name) == 0) return HIP_API_ID_hipMemcpyHtoDAsync; + if (strcmp("hipMemcpyParam2D", name) == 0) return HIP_API_ID_hipMemcpyParam2D; + if (strcmp("hipMemcpyParam2DAsync", name) == 0) return HIP_API_ID_hipMemcpyParam2DAsync; + if (strcmp("hipMemcpyPeer", name) == 0) return HIP_API_ID_hipMemcpyPeer; + if (strcmp("hipMemcpyPeerAsync", name) == 0) return HIP_API_ID_hipMemcpyPeerAsync; + if (strcmp("hipMemcpyToArray", name) == 0) return HIP_API_ID_hipMemcpyToArray; + if (strcmp("hipMemcpyToSymbol", name) == 0) return HIP_API_ID_hipMemcpyToSymbol; + if (strcmp("hipMemcpyToSymbolAsync", name) == 0) return HIP_API_ID_hipMemcpyToSymbolAsync; + if (strcmp("hipMemcpyWithStream", name) == 0) return HIP_API_ID_hipMemcpyWithStream; + if (strcmp("hipMemset", name) == 0) return HIP_API_ID_hipMemset; + if (strcmp("hipMemset2D", name) == 0) return HIP_API_ID_hipMemset2D; + if (strcmp("hipMemset2DAsync", name) == 0) return HIP_API_ID_hipMemset2DAsync; + if (strcmp("hipMemset3D", name) == 0) return HIP_API_ID_hipMemset3D; + if (strcmp("hipMemset3DAsync", name) == 0) return HIP_API_ID_hipMemset3DAsync; + if (strcmp("hipMemsetAsync", name) == 0) return HIP_API_ID_hipMemsetAsync; + if (strcmp("hipMemsetD16", name) == 0) return HIP_API_ID_hipMemsetD16; + if (strcmp("hipMemsetD16Async", name) == 0) return HIP_API_ID_hipMemsetD16Async; + if (strcmp("hipMemsetD32", name) == 0) return HIP_API_ID_hipMemsetD32; + if (strcmp("hipMemsetD32Async", name) == 0) return HIP_API_ID_hipMemsetD32Async; + if (strcmp("hipMemsetD8", name) == 0) return HIP_API_ID_hipMemsetD8; + if (strcmp("hipMemsetD8Async", name) == 0) return HIP_API_ID_hipMemsetD8Async; + if (strcmp("hipMipmappedArrayCreate", name) == 0) return HIP_API_ID_hipMipmappedArrayCreate; + if (strcmp("hipMipmappedArrayDestroy", name) == 0) return HIP_API_ID_hipMipmappedArrayDestroy; + if (strcmp("hipMipmappedArrayGetLevel", name) == 0) return HIP_API_ID_hipMipmappedArrayGetLevel; + if (strcmp("hipModuleGetFunction", name) == 0) return HIP_API_ID_hipModuleGetFunction; + if (strcmp("hipModuleGetGlobal", name) == 0) return HIP_API_ID_hipModuleGetGlobal; + if (strcmp("hipModuleGetTexRef", name) == 0) return HIP_API_ID_hipModuleGetTexRef; + if (strcmp("hipModuleLaunchCooperativeKernel", name) == 0) return HIP_API_ID_hipModuleLaunchCooperativeKernel; + if (strcmp("hipModuleLaunchCooperativeKernelMultiDevice", name) == 0) return HIP_API_ID_hipModuleLaunchCooperativeKernelMultiDevice; + if (strcmp("hipModuleLaunchKernel", name) == 0) return HIP_API_ID_hipModuleLaunchKernel; + if (strcmp("hipModuleLoad", name) == 0) return HIP_API_ID_hipModuleLoad; + if (strcmp("hipModuleLoadData", name) == 0) return HIP_API_ID_hipModuleLoadData; + if (strcmp("hipModuleLoadDataEx", name) == 0) return HIP_API_ID_hipModuleLoadDataEx; + if (strcmp("hipModuleOccupancyMaxActiveBlocksPerMultiprocessor", name) == 0) return HIP_API_ID_hipModuleOccupancyMaxActiveBlocksPerMultiprocessor; + if (strcmp("hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags", name) == 0) return HIP_API_ID_hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags; + if (strcmp("hipModuleOccupancyMaxPotentialBlockSize", name) == 0) return HIP_API_ID_hipModuleOccupancyMaxPotentialBlockSize; + if (strcmp("hipModuleOccupancyMaxPotentialBlockSizeWithFlags", name) == 0) return HIP_API_ID_hipModuleOccupancyMaxPotentialBlockSizeWithFlags; + if (strcmp("hipModuleUnload", name) == 0) return HIP_API_ID_hipModuleUnload; + if (strcmp("hipOccupancyMaxActiveBlocksPerMultiprocessor", name) == 0) return HIP_API_ID_hipOccupancyMaxActiveBlocksPerMultiprocessor; + if (strcmp("hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags", name) == 0) return HIP_API_ID_hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags; + if (strcmp("hipOccupancyMaxPotentialBlockSize", name) == 0) return HIP_API_ID_hipOccupancyMaxPotentialBlockSize; + if (strcmp("hipPeekAtLastError", name) == 0) return HIP_API_ID_hipPeekAtLastError; + if (strcmp("hipPointerGetAttribute", name) == 0) return HIP_API_ID_hipPointerGetAttribute; + if (strcmp("hipPointerGetAttributes", name) == 0) return HIP_API_ID_hipPointerGetAttributes; + if (strcmp("hipPointerSetAttribute", name) == 0) return HIP_API_ID_hipPointerSetAttribute; + if (strcmp("hipProfilerStart", name) == 0) return HIP_API_ID_hipProfilerStart; + if (strcmp("hipProfilerStop", name) == 0) return HIP_API_ID_hipProfilerStop; + if (strcmp("hipRuntimeGetVersion", name) == 0) return HIP_API_ID_hipRuntimeGetVersion; + if (strcmp("hipSetDevice", name) == 0) return HIP_API_ID_hipSetDevice; + if (strcmp("hipSetDeviceFlags", name) == 0) return HIP_API_ID_hipSetDeviceFlags; + if (strcmp("hipSetValidDevices", name) == 0) return HIP_API_ID_hipSetValidDevices; + if (strcmp("hipSetupArgument", name) == 0) return HIP_API_ID_hipSetupArgument; + if (strcmp("hipSignalExternalSemaphoresAsync", name) == 0) return HIP_API_ID_hipSignalExternalSemaphoresAsync; + if (strcmp("hipStreamAddCallback", name) == 0) return HIP_API_ID_hipStreamAddCallback; + if (strcmp("hipStreamAttachMemAsync", name) == 0) return HIP_API_ID_hipStreamAttachMemAsync; + if (strcmp("hipStreamBeginCapture", name) == 0) return HIP_API_ID_hipStreamBeginCapture; + if (strcmp("hipStreamBeginCaptureToGraph", name) == 0) return HIP_API_ID_hipStreamBeginCaptureToGraph; + if (strcmp("hipStreamCreate", name) == 0) return HIP_API_ID_hipStreamCreate; + if (strcmp("hipStreamCreateWithFlags", name) == 0) return HIP_API_ID_hipStreamCreateWithFlags; + if (strcmp("hipStreamCreateWithPriority", name) == 0) return HIP_API_ID_hipStreamCreateWithPriority; + if (strcmp("hipStreamDestroy", name) == 0) return HIP_API_ID_hipStreamDestroy; + if (strcmp("hipStreamEndCapture", name) == 0) return HIP_API_ID_hipStreamEndCapture; + if (strcmp("hipStreamGetCaptureInfo", name) == 0) return HIP_API_ID_hipStreamGetCaptureInfo; + if (strcmp("hipStreamGetCaptureInfo_v2", name) == 0) return HIP_API_ID_hipStreamGetCaptureInfo_v2; + if (strcmp("hipStreamGetDevice", name) == 0) return HIP_API_ID_hipStreamGetDevice; + if (strcmp("hipStreamGetFlags", name) == 0) return HIP_API_ID_hipStreamGetFlags; + if (strcmp("hipStreamGetPriority", name) == 0) return HIP_API_ID_hipStreamGetPriority; + if (strcmp("hipStreamIsCapturing", name) == 0) return HIP_API_ID_hipStreamIsCapturing; + if (strcmp("hipStreamQuery", name) == 0) return HIP_API_ID_hipStreamQuery; + if (strcmp("hipStreamSynchronize", name) == 0) return HIP_API_ID_hipStreamSynchronize; + if (strcmp("hipStreamUpdateCaptureDependencies", name) == 0) return HIP_API_ID_hipStreamUpdateCaptureDependencies; + if (strcmp("hipStreamWaitEvent", name) == 0) return HIP_API_ID_hipStreamWaitEvent; + if (strcmp("hipStreamWaitValue32", name) == 0) return HIP_API_ID_hipStreamWaitValue32; + if (strcmp("hipStreamWaitValue64", name) == 0) return HIP_API_ID_hipStreamWaitValue64; + if (strcmp("hipStreamWriteValue32", name) == 0) return HIP_API_ID_hipStreamWriteValue32; + if (strcmp("hipStreamWriteValue64", name) == 0) return HIP_API_ID_hipStreamWriteValue64; + if (strcmp("hipTexRefGetAddress", name) == 0) return HIP_API_ID_hipTexRefGetAddress; + if (strcmp("hipTexRefGetArray", name) == 0) return HIP_API_ID_hipTexRefGetArray; + if (strcmp("hipTexRefGetBorderColor", name) == 0) return HIP_API_ID_hipTexRefGetBorderColor; + if (strcmp("hipTexRefGetFlags", name) == 0) return HIP_API_ID_hipTexRefGetFlags; + if (strcmp("hipTexRefGetFormat", name) == 0) return HIP_API_ID_hipTexRefGetFormat; + if (strcmp("hipTexRefGetMaxAnisotropy", name) == 0) return HIP_API_ID_hipTexRefGetMaxAnisotropy; + if (strcmp("hipTexRefGetMipMappedArray", name) == 0) return HIP_API_ID_hipTexRefGetMipMappedArray; + if (strcmp("hipTexRefGetMipmapLevelBias", name) == 0) return HIP_API_ID_hipTexRefGetMipmapLevelBias; + if (strcmp("hipTexRefGetMipmapLevelClamp", name) == 0) return HIP_API_ID_hipTexRefGetMipmapLevelClamp; + if (strcmp("hipTexRefSetAddress", name) == 0) return HIP_API_ID_hipTexRefSetAddress; + if (strcmp("hipTexRefSetAddress2D", name) == 0) return HIP_API_ID_hipTexRefSetAddress2D; + if (strcmp("hipTexRefSetArray", name) == 0) return HIP_API_ID_hipTexRefSetArray; + if (strcmp("hipTexRefSetBorderColor", name) == 0) return HIP_API_ID_hipTexRefSetBorderColor; + if (strcmp("hipTexRefSetFlags", name) == 0) return HIP_API_ID_hipTexRefSetFlags; + if (strcmp("hipTexRefSetFormat", name) == 0) return HIP_API_ID_hipTexRefSetFormat; + if (strcmp("hipTexRefSetMaxAnisotropy", name) == 0) return HIP_API_ID_hipTexRefSetMaxAnisotropy; + if (strcmp("hipTexRefSetMipmapLevelBias", name) == 0) return HIP_API_ID_hipTexRefSetMipmapLevelBias; + if (strcmp("hipTexRefSetMipmapLevelClamp", name) == 0) return HIP_API_ID_hipTexRefSetMipmapLevelClamp; + if (strcmp("hipTexRefSetMipmappedArray", name) == 0) return HIP_API_ID_hipTexRefSetMipmappedArray; + if (strcmp("hipThreadExchangeStreamCaptureMode", name) == 0) return HIP_API_ID_hipThreadExchangeStreamCaptureMode; + if (strcmp("hipUserObjectCreate", name) == 0) return HIP_API_ID_hipUserObjectCreate; + if (strcmp("hipUserObjectRelease", name) == 0) return HIP_API_ID_hipUserObjectRelease; + if (strcmp("hipUserObjectRetain", name) == 0) return HIP_API_ID_hipUserObjectRetain; + if (strcmp("hipWaitExternalSemaphoresAsync", name) == 0) return HIP_API_ID_hipWaitExternalSemaphoresAsync; + return HIP_API_ID_NONE; +} + +// HIP API callbacks data structures +typedef struct hip_api_data_s { + uint64_t correlation_id; + uint32_t phase; + union { + struct { + dim3* gridDim; + dim3 gridDim__val; + dim3* blockDim; + dim3 blockDim__val; + size_t* sharedMem; + size_t sharedMem__val; + hipStream_t* stream; + hipStream_t stream__val; + } __hipPopCallConfiguration; + struct { + dim3 gridDim; + dim3 blockDim; + size_t sharedMem; + hipStream_t stream; + } __hipPushCallConfiguration; + struct { + hipArray_t* array; + hipArray_t array__val; + const HIP_ARRAY3D_DESCRIPTOR* pAllocateArray; + HIP_ARRAY3D_DESCRIPTOR pAllocateArray__val; + } hipArray3DCreate; + struct { + HIP_ARRAY3D_DESCRIPTOR* pArrayDescriptor; + HIP_ARRAY3D_DESCRIPTOR pArrayDescriptor__val; + hipArray_t array; + } hipArray3DGetDescriptor; + struct { + hipArray_t* pHandle; + hipArray_t pHandle__val; + const HIP_ARRAY_DESCRIPTOR* pAllocateArray; + HIP_ARRAY_DESCRIPTOR pAllocateArray__val; + } hipArrayCreate; + struct { + hipArray_t array; + } hipArrayDestroy; + struct { + HIP_ARRAY_DESCRIPTOR* pArrayDescriptor; + HIP_ARRAY_DESCRIPTOR pArrayDescriptor__val; + hipArray_t array; + } hipArrayGetDescriptor; + struct { + hipChannelFormatDesc* desc; + hipChannelFormatDesc desc__val; + hipExtent* extent; + hipExtent extent__val; + unsigned int* flags; + unsigned int flags__val; + hipArray_t array; + } hipArrayGetInfo; + struct { + int* device; + int device__val; + const hipDeviceProp_tR0000* prop; + hipDeviceProp_tR0000 prop__val; + } hipChooseDeviceR0000; + struct { + int* device; + int device__val; + const hipDeviceProp_tR0600* prop; + hipDeviceProp_tR0600 prop__val; + } hipChooseDeviceR0600; + struct { + dim3 gridDim; + dim3 blockDim; + size_t sharedMem; + hipStream_t stream; + } hipConfigureCall; + struct { + hipSurfaceObject_t* pSurfObject; + hipSurfaceObject_t pSurfObject__val; + const hipResourceDesc* pResDesc; + hipResourceDesc pResDesc__val; + } hipCreateSurfaceObject; + struct { + hipCtx_t* ctx; + hipCtx_t ctx__val; + unsigned int flags; + hipDevice_t device; + } hipCtxCreate; + struct { + hipCtx_t ctx; + } hipCtxDestroy; + struct { + hipCtx_t peerCtx; + } hipCtxDisablePeerAccess; + struct { + hipCtx_t peerCtx; + unsigned int flags; + } hipCtxEnablePeerAccess; + struct { + hipCtx_t ctx; + int* apiVersion; + int apiVersion__val; + } hipCtxGetApiVersion; + struct { + hipFuncCache_t* cacheConfig; + hipFuncCache_t cacheConfig__val; + } hipCtxGetCacheConfig; + struct { + hipCtx_t* ctx; + hipCtx_t ctx__val; + } hipCtxGetCurrent; + struct { + hipDevice_t* device; + hipDevice_t device__val; + } hipCtxGetDevice; + struct { + unsigned int* flags; + unsigned int flags__val; + } hipCtxGetFlags; + struct { + hipSharedMemConfig* pConfig; + hipSharedMemConfig pConfig__val; + } hipCtxGetSharedMemConfig; + struct { + hipCtx_t* ctx; + hipCtx_t ctx__val; + } hipCtxPopCurrent; + struct { + hipCtx_t ctx; + } hipCtxPushCurrent; + struct { + hipFuncCache_t cacheConfig; + } hipCtxSetCacheConfig; + struct { + hipCtx_t ctx; + } hipCtxSetCurrent; + struct { + hipSharedMemConfig config; + } hipCtxSetSharedMemConfig; + struct { + hipExternalMemory_t extMem; + } hipDestroyExternalMemory; + struct { + hipExternalSemaphore_t extSem; + } hipDestroyExternalSemaphore; + struct { + hipSurfaceObject_t surfaceObject; + } hipDestroySurfaceObject; + struct { + int* canAccessPeer; + int canAccessPeer__val; + int deviceId; + int peerDeviceId; + } hipDeviceCanAccessPeer; + struct { + int* major; + int major__val; + int* minor; + int minor__val; + hipDevice_t device; + } hipDeviceComputeCapability; + struct { + int peerDeviceId; + } hipDeviceDisablePeerAccess; + struct { + int peerDeviceId; + unsigned int flags; + } hipDeviceEnablePeerAccess; + struct { + hipDevice_t* device; + hipDevice_t device__val; + int ordinal; + } hipDeviceGet; + struct { + int* pi; + int pi__val; + hipDeviceAttribute_t attr; + int deviceId; + } hipDeviceGetAttribute; + struct { + int* device; + int device__val; + const char* pciBusId; + char pciBusId__val; + } hipDeviceGetByPCIBusId; + struct { + hipFuncCache_t* cacheConfig; + hipFuncCache_t cacheConfig__val; + } hipDeviceGetCacheConfig; + struct { + hipMemPool_t* mem_pool; + hipMemPool_t mem_pool__val; + int device; + } hipDeviceGetDefaultMemPool; + struct { + int device; + hipGraphMemAttributeType attr; + void* value; + } hipDeviceGetGraphMemAttribute; + struct { + size_t* pValue; + size_t pValue__val; + enum hipLimit_t limit; + } hipDeviceGetLimit; + struct { + hipMemPool_t* mem_pool; + hipMemPool_t mem_pool__val; + int device; + } hipDeviceGetMemPool; + struct { + char* name; + char name__val; + int len; + hipDevice_t device; + } hipDeviceGetName; + struct { + int* value; + int value__val; + hipDeviceP2PAttr attr; + int srcDevice; + int dstDevice; + } hipDeviceGetP2PAttribute; + struct { + char* pciBusId; + char pciBusId__val; + int len; + int device; + } hipDeviceGetPCIBusId; + struct { + hipSharedMemConfig* pConfig; + hipSharedMemConfig pConfig__val; + } hipDeviceGetSharedMemConfig; + struct { + int* leastPriority; + int leastPriority__val; + int* greatestPriority; + int greatestPriority__val; + } hipDeviceGetStreamPriorityRange; + struct { + hipUUID* uuid; + hipUUID uuid__val; + hipDevice_t device; + } hipDeviceGetUuid; + struct { + int device; + } hipDeviceGraphMemTrim; + struct { + hipDevice_t dev; + unsigned int* flags; + unsigned int flags__val; + int* active; + int active__val; + } hipDevicePrimaryCtxGetState; + struct { + hipDevice_t dev; + } hipDevicePrimaryCtxRelease; + struct { + hipDevice_t dev; + } hipDevicePrimaryCtxReset; + struct { + hipCtx_t* pctx; + hipCtx_t pctx__val; + hipDevice_t dev; + } hipDevicePrimaryCtxRetain; + struct { + hipDevice_t dev; + unsigned int flags; + } hipDevicePrimaryCtxSetFlags; + struct { + hipFuncCache_t cacheConfig; + } hipDeviceSetCacheConfig; + struct { + int device; + hipGraphMemAttributeType attr; + void* value; + } hipDeviceSetGraphMemAttribute; + struct { + enum hipLimit_t limit; + size_t value; + } hipDeviceSetLimit; + struct { + int device; + hipMemPool_t mem_pool; + } hipDeviceSetMemPool; + struct { + hipSharedMemConfig config; + } hipDeviceSetSharedMemConfig; + struct { + size_t* bytes; + size_t bytes__val; + hipDevice_t device; + } hipDeviceTotalMem; + struct { + int* driverVersion; + int driverVersion__val; + } hipDriverGetVersion; + struct { + hipGraphNode_t* phGraphNode; + hipGraphNode_t phGraphNode__val; + hipGraph_t hGraph; + const hipGraphNode_t* dependencies; + hipGraphNode_t dependencies__val; + size_t numDependencies; + const HIP_MEMCPY3D* copyParams; + HIP_MEMCPY3D copyParams__val; + hipCtx_t ctx; + } hipDrvGraphAddMemcpyNode; + struct { + hipGraphNode_t* phGraphNode; + hipGraphNode_t phGraphNode__val; + hipGraph_t hGraph; + const hipGraphNode_t* dependencies; + hipGraphNode_t dependencies__val; + size_t numDependencies; + const HIP_MEMSET_NODE_PARAMS* memsetParams; + HIP_MEMSET_NODE_PARAMS memsetParams__val; + hipCtx_t ctx; + } hipDrvGraphAddMemsetNode; + struct { + const hip_Memcpy2D* pCopy; + hip_Memcpy2D pCopy__val; + } hipDrvMemcpy2DUnaligned; + struct { + const HIP_MEMCPY3D* pCopy; + HIP_MEMCPY3D pCopy__val; + } hipDrvMemcpy3D; + struct { + const HIP_MEMCPY3D* pCopy; + HIP_MEMCPY3D pCopy__val; + hipStream_t stream; + } hipDrvMemcpy3DAsync; + struct { + unsigned int numAttributes; + hipPointer_attribute* attributes; + hipPointer_attribute attributes__val; + void** data; + void* data__val; + hipDeviceptr_t ptr; + } hipDrvPointerGetAttributes; + struct { + hipEvent_t* event; + hipEvent_t event__val; + } hipEventCreate; + struct { + hipEvent_t* event; + hipEvent_t event__val; + unsigned int flags; + } hipEventCreateWithFlags; + struct { + hipEvent_t event; + } hipEventDestroy; + struct { + float* ms; + float ms__val; + hipEvent_t start; + hipEvent_t stop; + } hipEventElapsedTime; + struct { + hipEvent_t event; + } hipEventQuery; + struct { + hipEvent_t event; + hipStream_t stream; + } hipEventRecord; + struct { + hipEvent_t event; + } hipEventSynchronize; + struct { + int device1; + int device2; + unsigned int* linktype; + unsigned int linktype__val; + unsigned int* hopcount; + unsigned int hopcount__val; + } hipExtGetLinkTypeAndHopCount; + struct { + const void* function_address; + dim3 numBlocks; + dim3 dimBlocks; + void** args; + void* args__val; + size_t sharedMemBytes; + hipStream_t stream; + hipEvent_t startEvent; + hipEvent_t stopEvent; + int flags; + } hipExtLaunchKernel; + struct { + hipLaunchParams* launchParamsList; + hipLaunchParams launchParamsList__val; + int numDevices; + unsigned int flags; + } hipExtLaunchMultiKernelMultiDevice; + struct { + void** ptr; + void* ptr__val; + size_t sizeBytes; + unsigned int flags; + } hipExtMallocWithFlags; + struct { + hipFunction_t f; + unsigned int globalWorkSizeX; + unsigned int globalWorkSizeY; + unsigned int globalWorkSizeZ; + unsigned int localWorkSizeX; + unsigned int localWorkSizeY; + unsigned int localWorkSizeZ; + size_t sharedMemBytes; + hipStream_t hStream; + void** kernelParams; + void* kernelParams__val; + void** extra; + void* extra__val; + hipEvent_t startEvent; + hipEvent_t stopEvent; + unsigned int flags; + } hipExtModuleLaunchKernel; + struct { + hipStream_t* stream; + hipStream_t stream__val; + unsigned int cuMaskSize; + const unsigned int* cuMask; + unsigned int cuMask__val; + } hipExtStreamCreateWithCUMask; + struct { + hipStream_t stream; + unsigned int cuMaskSize; + unsigned int* cuMask; + unsigned int cuMask__val; + } hipExtStreamGetCUMask; + struct { + void** devPtr; + void* devPtr__val; + hipExternalMemory_t extMem; + const hipExternalMemoryBufferDesc* bufferDesc; + hipExternalMemoryBufferDesc bufferDesc__val; + } hipExternalMemoryGetMappedBuffer; + struct { + hipMipmappedArray_t* mipmap; + hipMipmappedArray_t mipmap__val; + hipExternalMemory_t extMem; + const hipExternalMemoryMipmappedArrayDesc* mipmapDesc; + hipExternalMemoryMipmappedArrayDesc mipmapDesc__val; + } hipExternalMemoryGetMappedMipmappedArray; + struct { + void* ptr; + } hipFree; + struct { + hipArray_t array; + } hipFreeArray; + struct { + void* dev_ptr; + hipStream_t stream; + } hipFreeAsync; + struct { + void* ptr; + } hipFreeHost; + struct { + hipMipmappedArray_t mipmappedArray; + } hipFreeMipmappedArray; + struct { + int* value; + int value__val; + hipFunction_attribute attrib; + hipFunction_t hfunc; + } hipFuncGetAttribute; + struct { + hipFuncAttributes* attr; + hipFuncAttributes attr__val; + const void* func; + } hipFuncGetAttributes; + struct { + const void* func; + hipFuncAttribute attr; + int value; + } hipFuncSetAttribute; + struct { + const void* func; + hipFuncCache_t config; + } hipFuncSetCacheConfig; + struct { + const void* func; + hipSharedMemConfig config; + } hipFuncSetSharedMemConfig; + struct { + unsigned int* pHipDeviceCount; + unsigned int pHipDeviceCount__val; + int* pHipDevices; + int pHipDevices__val; + unsigned int hipDeviceCount; + hipGLDeviceList deviceList; + } hipGLGetDevices; + struct { + hipChannelFormatDesc* desc; + hipChannelFormatDesc desc__val; + hipArray_const_t array; + } hipGetChannelDesc; + struct { + int* deviceId; + int deviceId__val; + } hipGetDevice; + struct { + int* count; + int count__val; + } hipGetDeviceCount; + struct { + unsigned int* flags; + unsigned int flags__val; + } hipGetDeviceFlags; + struct { + hipDeviceProp_tR0000* prop; + hipDeviceProp_tR0000 prop__val; + int device; + } hipGetDevicePropertiesR0000; + struct { + hipDeviceProp_tR0600* prop; + hipDeviceProp_tR0600 prop__val; + int deviceId; + } hipGetDevicePropertiesR0600; + struct { + hipFunction_t* functionPtr; + hipFunction_t functionPtr__val; + const void* symbolPtr; + } hipGetFuncBySymbol; + struct { + hipArray_t* levelArray; + hipArray_t levelArray__val; + hipMipmappedArray_const_t mipmappedArray; + unsigned int level; + } hipGetMipmappedArrayLevel; + struct { + const char* symbol; + char symbol__val; + void** pfn; + void* pfn__val; + int hipVersion; + uint64_t flags; + hipDriverProcAddressQueryResult* symbolStatus; + hipDriverProcAddressQueryResult symbolStatus__val; + } hipGetProcAddress; + struct { + void** devPtr; + void* devPtr__val; + const void* symbol; + } hipGetSymbolAddress; + struct { + size_t* size; + size_t size__val; + const void* symbol; + } hipGetSymbolSize; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + hipGraph_t childGraph; + } hipGraphAddChildGraphNode; + struct { + hipGraph_t graph; + const hipGraphNode_t* from; + hipGraphNode_t from__val; + const hipGraphNode_t* to; + hipGraphNode_t to__val; + size_t numDependencies; + } hipGraphAddDependencies; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + } hipGraphAddEmptyNode; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + hipEvent_t event; + } hipGraphAddEventRecordNode; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + hipEvent_t event; + } hipGraphAddEventWaitNode; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + const hipExternalSemaphoreSignalNodeParams* nodeParams; + hipExternalSemaphoreSignalNodeParams nodeParams__val; + } hipGraphAddExternalSemaphoresSignalNode; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + const hipExternalSemaphoreWaitNodeParams* nodeParams; + hipExternalSemaphoreWaitNodeParams nodeParams__val; + } hipGraphAddExternalSemaphoresWaitNode; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + const hipHostNodeParams* pNodeParams; + hipHostNodeParams pNodeParams__val; + } hipGraphAddHostNode; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + const hipKernelNodeParams* pNodeParams; + hipKernelNodeParams pNodeParams__val; + } hipGraphAddKernelNode; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + hipMemAllocNodeParams* pNodeParams; + hipMemAllocNodeParams pNodeParams__val; + } hipGraphAddMemAllocNode; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + void* dev_ptr; + } hipGraphAddMemFreeNode; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + const hipMemcpy3DParms* pCopyParams; + hipMemcpy3DParms pCopyParams__val; + } hipGraphAddMemcpyNode; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + void* dst; + const void* src; + size_t count; + hipMemcpyKind kind; + } hipGraphAddMemcpyNode1D; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + void* dst; + const void* symbol; + size_t count; + size_t offset; + hipMemcpyKind kind; + } hipGraphAddMemcpyNodeFromSymbol; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + const void* symbol; + const void* src; + size_t count; + size_t offset; + hipMemcpyKind kind; + } hipGraphAddMemcpyNodeToSymbol; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + const hipMemsetParams* pMemsetParams; + hipMemsetParams pMemsetParams__val; + } hipGraphAddMemsetNode; + struct { + hipGraphNode_t* pGraphNode; + hipGraphNode_t pGraphNode__val; + hipGraph_t graph; + const hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t numDependencies; + hipGraphNodeParams* nodeParams; + hipGraphNodeParams nodeParams__val; + } hipGraphAddNode; + struct { + hipGraphNode_t node; + hipGraph_t* pGraph; + hipGraph_t pGraph__val; + } hipGraphChildGraphNodeGetGraph; + struct { + hipGraph_t* pGraphClone; + hipGraph_t pGraphClone__val; + hipGraph_t originalGraph; + } hipGraphClone; + struct { + hipGraph_t* pGraph; + hipGraph_t pGraph__val; + unsigned int flags; + } hipGraphCreate; + struct { + hipGraph_t graph; + const char* path; + char path__val; + unsigned int flags; + } hipGraphDebugDotPrint; + struct { + hipGraph_t graph; + } hipGraphDestroy; + struct { + hipGraphNode_t node; + } hipGraphDestroyNode; + struct { + hipGraphNode_t node; + hipEvent_t* event_out; + hipEvent_t event_out__val; + } hipGraphEventRecordNodeGetEvent; + struct { + hipGraphNode_t node; + hipEvent_t event; + } hipGraphEventRecordNodeSetEvent; + struct { + hipGraphNode_t node; + hipEvent_t* event_out; + hipEvent_t event_out__val; + } hipGraphEventWaitNodeGetEvent; + struct { + hipGraphNode_t node; + hipEvent_t event; + } hipGraphEventWaitNodeSetEvent; + struct { + hipGraphExec_t hGraphExec; + hipGraphNode_t node; + hipGraph_t childGraph; + } hipGraphExecChildGraphNodeSetParams; + struct { + hipGraphExec_t graphExec; + } hipGraphExecDestroy; + struct { + hipGraphExec_t hGraphExec; + hipGraphNode_t hNode; + hipEvent_t event; + } hipGraphExecEventRecordNodeSetEvent; + struct { + hipGraphExec_t hGraphExec; + hipGraphNode_t hNode; + hipEvent_t event; + } hipGraphExecEventWaitNodeSetEvent; + struct { + hipGraphExec_t hGraphExec; + hipGraphNode_t hNode; + const hipExternalSemaphoreSignalNodeParams* nodeParams; + hipExternalSemaphoreSignalNodeParams nodeParams__val; + } hipGraphExecExternalSemaphoresSignalNodeSetParams; + struct { + hipGraphExec_t hGraphExec; + hipGraphNode_t hNode; + const hipExternalSemaphoreWaitNodeParams* nodeParams; + hipExternalSemaphoreWaitNodeParams nodeParams__val; + } hipGraphExecExternalSemaphoresWaitNodeSetParams; + struct { + hipGraphExec_t hGraphExec; + hipGraphNode_t node; + const hipHostNodeParams* pNodeParams; + hipHostNodeParams pNodeParams__val; + } hipGraphExecHostNodeSetParams; + struct { + hipGraphExec_t hGraphExec; + hipGraphNode_t node; + const hipKernelNodeParams* pNodeParams; + hipKernelNodeParams pNodeParams__val; + } hipGraphExecKernelNodeSetParams; + struct { + hipGraphExec_t hGraphExec; + hipGraphNode_t node; + hipMemcpy3DParms* pNodeParams; + hipMemcpy3DParms pNodeParams__val; + } hipGraphExecMemcpyNodeSetParams; + struct { + hipGraphExec_t hGraphExec; + hipGraphNode_t node; + void* dst; + const void* src; + size_t count; + hipMemcpyKind kind; + } hipGraphExecMemcpyNodeSetParams1D; + struct { + hipGraphExec_t hGraphExec; + hipGraphNode_t node; + void* dst; + const void* symbol; + size_t count; + size_t offset; + hipMemcpyKind kind; + } hipGraphExecMemcpyNodeSetParamsFromSymbol; + struct { + hipGraphExec_t hGraphExec; + hipGraphNode_t node; + const void* symbol; + const void* src; + size_t count; + size_t offset; + hipMemcpyKind kind; + } hipGraphExecMemcpyNodeSetParamsToSymbol; + struct { + hipGraphExec_t hGraphExec; + hipGraphNode_t node; + const hipMemsetParams* pNodeParams; + hipMemsetParams pNodeParams__val; + } hipGraphExecMemsetNodeSetParams; + struct { + hipGraphExec_t hGraphExec; + hipGraph_t hGraph; + hipGraphNode_t* hErrorNode_out; + hipGraphNode_t hErrorNode_out__val; + hipGraphExecUpdateResult* updateResult_out; + hipGraphExecUpdateResult updateResult_out__val; + } hipGraphExecUpdate; + struct { + hipGraphNode_t hNode; + hipExternalSemaphoreSignalNodeParams* params_out; + hipExternalSemaphoreSignalNodeParams params_out__val; + } hipGraphExternalSemaphoresSignalNodeGetParams; + struct { + hipGraphNode_t hNode; + const hipExternalSemaphoreSignalNodeParams* nodeParams; + hipExternalSemaphoreSignalNodeParams nodeParams__val; + } hipGraphExternalSemaphoresSignalNodeSetParams; + struct { + hipGraphNode_t hNode; + hipExternalSemaphoreWaitNodeParams* params_out; + hipExternalSemaphoreWaitNodeParams params_out__val; + } hipGraphExternalSemaphoresWaitNodeGetParams; + struct { + hipGraphNode_t hNode; + const hipExternalSemaphoreWaitNodeParams* nodeParams; + hipExternalSemaphoreWaitNodeParams nodeParams__val; + } hipGraphExternalSemaphoresWaitNodeSetParams; + struct { + hipGraph_t graph; + hipGraphNode_t* from; + hipGraphNode_t from__val; + hipGraphNode_t* to; + hipGraphNode_t to__val; + size_t* numEdges; + size_t numEdges__val; + } hipGraphGetEdges; + struct { + hipGraph_t graph; + hipGraphNode_t* nodes; + hipGraphNode_t nodes__val; + size_t* numNodes; + size_t numNodes__val; + } hipGraphGetNodes; + struct { + hipGraph_t graph; + hipGraphNode_t* pRootNodes; + hipGraphNode_t pRootNodes__val; + size_t* pNumRootNodes; + size_t pNumRootNodes__val; + } hipGraphGetRootNodes; + struct { + hipGraphNode_t node; + hipHostNodeParams* pNodeParams; + hipHostNodeParams pNodeParams__val; + } hipGraphHostNodeGetParams; + struct { + hipGraphNode_t node; + const hipHostNodeParams* pNodeParams; + hipHostNodeParams pNodeParams__val; + } hipGraphHostNodeSetParams; + struct { + hipGraphExec_t* pGraphExec; + hipGraphExec_t pGraphExec__val; + hipGraph_t graph; + hipGraphNode_t* pErrorNode; + hipGraphNode_t pErrorNode__val; + char* pLogBuffer; + char pLogBuffer__val; + size_t bufferSize; + } hipGraphInstantiate; + struct { + hipGraphExec_t* pGraphExec; + hipGraphExec_t pGraphExec__val; + hipGraph_t graph; + unsigned long long flags; + } hipGraphInstantiateWithFlags; + struct { + hipGraphExec_t* pGraphExec; + hipGraphExec_t pGraphExec__val; + hipGraph_t graph; + hipGraphInstantiateParams* instantiateParams; + hipGraphInstantiateParams instantiateParams__val; + } hipGraphInstantiateWithParams; + struct { + hipGraphNode_t hSrc; + hipGraphNode_t hDst; + } hipGraphKernelNodeCopyAttributes; + struct { + hipGraphNode_t hNode; + hipLaunchAttributeID attr; + hipLaunchAttributeValue* value; + hipLaunchAttributeValue value__val; + } hipGraphKernelNodeGetAttribute; + struct { + hipGraphNode_t node; + hipKernelNodeParams* pNodeParams; + hipKernelNodeParams pNodeParams__val; + } hipGraphKernelNodeGetParams; + struct { + hipGraphNode_t hNode; + hipLaunchAttributeID attr; + const hipLaunchAttributeValue* value; + hipLaunchAttributeValue value__val; + } hipGraphKernelNodeSetAttribute; + struct { + hipGraphNode_t node; + const hipKernelNodeParams* pNodeParams; + hipKernelNodeParams pNodeParams__val; + } hipGraphKernelNodeSetParams; + struct { + hipGraphExec_t graphExec; + hipStream_t stream; + } hipGraphLaunch; + struct { + hipGraphNode_t node; + hipMemAllocNodeParams* pNodeParams; + hipMemAllocNodeParams pNodeParams__val; + } hipGraphMemAllocNodeGetParams; + struct { + hipGraphNode_t node; + void* dev_ptr; + } hipGraphMemFreeNodeGetParams; + struct { + hipGraphNode_t node; + hipMemcpy3DParms* pNodeParams; + hipMemcpy3DParms pNodeParams__val; + } hipGraphMemcpyNodeGetParams; + struct { + hipGraphNode_t node; + const hipMemcpy3DParms* pNodeParams; + hipMemcpy3DParms pNodeParams__val; + } hipGraphMemcpyNodeSetParams; + struct { + hipGraphNode_t node; + void* dst; + const void* src; + size_t count; + hipMemcpyKind kind; + } hipGraphMemcpyNodeSetParams1D; + struct { + hipGraphNode_t node; + void* dst; + const void* symbol; + size_t count; + size_t offset; + hipMemcpyKind kind; + } hipGraphMemcpyNodeSetParamsFromSymbol; + struct { + hipGraphNode_t node; + const void* symbol; + const void* src; + size_t count; + size_t offset; + hipMemcpyKind kind; + } hipGraphMemcpyNodeSetParamsToSymbol; + struct { + hipGraphNode_t node; + hipMemsetParams* pNodeParams; + hipMemsetParams pNodeParams__val; + } hipGraphMemsetNodeGetParams; + struct { + hipGraphNode_t node; + const hipMemsetParams* pNodeParams; + hipMemsetParams pNodeParams__val; + } hipGraphMemsetNodeSetParams; + struct { + hipGraphNode_t* pNode; + hipGraphNode_t pNode__val; + hipGraphNode_t originalNode; + hipGraph_t clonedGraph; + } hipGraphNodeFindInClone; + struct { + hipGraphNode_t node; + hipGraphNode_t* pDependencies; + hipGraphNode_t pDependencies__val; + size_t* pNumDependencies; + size_t pNumDependencies__val; + } hipGraphNodeGetDependencies; + struct { + hipGraphNode_t node; + hipGraphNode_t* pDependentNodes; + hipGraphNode_t pDependentNodes__val; + size_t* pNumDependentNodes; + size_t pNumDependentNodes__val; + } hipGraphNodeGetDependentNodes; + struct { + hipGraphExec_t hGraphExec; + hipGraphNode_t hNode; + unsigned int* isEnabled; + unsigned int isEnabled__val; + } hipGraphNodeGetEnabled; + struct { + hipGraphNode_t node; + hipGraphNodeType* pType; + hipGraphNodeType pType__val; + } hipGraphNodeGetType; + struct { + hipGraphExec_t hGraphExec; + hipGraphNode_t hNode; + unsigned int isEnabled; + } hipGraphNodeSetEnabled; + struct { + hipGraph_t graph; + hipUserObject_t object; + unsigned int count; + } hipGraphReleaseUserObject; + struct { + hipGraph_t graph; + const hipGraphNode_t* from; + hipGraphNode_t from__val; + const hipGraphNode_t* to; + hipGraphNode_t to__val; + size_t numDependencies; + } hipGraphRemoveDependencies; + struct { + hipGraph_t graph; + hipUserObject_t object; + unsigned int count; + unsigned int flags; + } hipGraphRetainUserObject; + struct { + hipGraphExec_t graphExec; + hipStream_t stream; + } hipGraphUpload; + struct { + hipGraphicsResource** resource; + hipGraphicsResource* resource__val; + GLuint buffer; + unsigned int flags; + } hipGraphicsGLRegisterBuffer; + struct { + hipGraphicsResource** resource; + hipGraphicsResource* resource__val; + GLuint image; + GLenum target; + unsigned int flags; + } hipGraphicsGLRegisterImage; + struct { + int count; + hipGraphicsResource_t* resources; + hipGraphicsResource_t resources__val; + hipStream_t stream; + } hipGraphicsMapResources; + struct { + void** devPtr; + void* devPtr__val; + size_t* size; + size_t size__val; + hipGraphicsResource_t resource; + } hipGraphicsResourceGetMappedPointer; + struct { + hipArray_t* array; + hipArray_t array__val; + hipGraphicsResource_t resource; + unsigned int arrayIndex; + unsigned int mipLevel; + } hipGraphicsSubResourceGetMappedArray; + struct { + int count; + hipGraphicsResource_t* resources; + hipGraphicsResource_t resources__val; + hipStream_t stream; + } hipGraphicsUnmapResources; + struct { + hipGraphicsResource_t resource; + } hipGraphicsUnregisterResource; + struct { + hipFunction_t f; + unsigned int globalWorkSizeX; + unsigned int globalWorkSizeY; + unsigned int globalWorkSizeZ; + unsigned int blockDimX; + unsigned int blockDimY; + unsigned int blockDimZ; + size_t sharedMemBytes; + hipStream_t hStream; + void** kernelParams; + void* kernelParams__val; + void** extra; + void* extra__val; + hipEvent_t startEvent; + hipEvent_t stopEvent; + } hipHccModuleLaunchKernel; + struct { + void** ptr; + void* ptr__val; + size_t size; + unsigned int flags; + } hipHostAlloc; + struct { + void* ptr; + } hipHostFree; + struct { + void** devPtr; + void* devPtr__val; + void* hstPtr; + unsigned int flags; + } hipHostGetDevicePointer; + struct { + unsigned int* flagsPtr; + unsigned int flagsPtr__val; + void* hostPtr; + } hipHostGetFlags; + struct { + void** ptr; + void* ptr__val; + size_t size; + unsigned int flags; + } hipHostMalloc; + struct { + void* hostPtr; + size_t sizeBytes; + unsigned int flags; + } hipHostRegister; + struct { + void* hostPtr; + } hipHostUnregister; + struct { + hipExternalMemory_t* extMem_out; + hipExternalMemory_t extMem_out__val; + const hipExternalMemoryHandleDesc* memHandleDesc; + hipExternalMemoryHandleDesc memHandleDesc__val; + } hipImportExternalMemory; + struct { + hipExternalSemaphore_t* extSem_out; + hipExternalSemaphore_t extSem_out__val; + const hipExternalSemaphoreHandleDesc* semHandleDesc; + hipExternalSemaphoreHandleDesc semHandleDesc__val; + } hipImportExternalSemaphore; + struct { + unsigned int flags; + } hipInit; + struct { + void* devPtr; + } hipIpcCloseMemHandle; + struct { + hipIpcEventHandle_t* handle; + hipIpcEventHandle_t handle__val; + hipEvent_t event; + } hipIpcGetEventHandle; + struct { + hipIpcMemHandle_t* handle; + hipIpcMemHandle_t handle__val; + void* devPtr; + } hipIpcGetMemHandle; + struct { + hipEvent_t* event; + hipEvent_t event__val; + hipIpcEventHandle_t handle; + } hipIpcOpenEventHandle; + struct { + void** devPtr; + void* devPtr__val; + hipIpcMemHandle_t handle; + unsigned int flags; + } hipIpcOpenMemHandle; + struct { + const void* hostFunction; + } hipLaunchByPtr; + struct { + const void* f; + dim3 gridDim; + dim3 blockDimX; + void** kernelParams; + void* kernelParams__val; + unsigned int sharedMemBytes; + hipStream_t stream; + } hipLaunchCooperativeKernel; + struct { + hipLaunchParams* launchParamsList; + hipLaunchParams launchParamsList__val; + int numDevices; + unsigned int flags; + } hipLaunchCooperativeKernelMultiDevice; + struct { + hipStream_t stream; + hipHostFn_t fn; + void* userData; + } hipLaunchHostFunc; + struct { + const void* function_address; + dim3 numBlocks; + dim3 dimBlocks; + void** args; + void* args__val; + size_t sharedMemBytes; + hipStream_t stream; + } hipLaunchKernel; + struct { + void** ptr; + void* ptr__val; + size_t size; + } hipMalloc; + struct { + hipPitchedPtr* pitchedDevPtr; + hipPitchedPtr pitchedDevPtr__val; + hipExtent extent; + } hipMalloc3D; + struct { + hipArray_t* array; + hipArray_t array__val; + const hipChannelFormatDesc* desc; + hipChannelFormatDesc desc__val; + hipExtent extent; + unsigned int flags; + } hipMalloc3DArray; + struct { + hipArray_t* array; + hipArray_t array__val; + const hipChannelFormatDesc* desc; + hipChannelFormatDesc desc__val; + size_t width; + size_t height; + unsigned int flags; + } hipMallocArray; + struct { + void** dev_ptr; + void* dev_ptr__val; + size_t size; + hipStream_t stream; + } hipMallocAsync; + struct { + void** dev_ptr; + void* dev_ptr__val; + size_t size; + hipMemPool_t mem_pool; + hipStream_t stream; + } hipMallocFromPoolAsync; + struct { + void** ptr; + void* ptr__val; + size_t size; + } hipMallocHost; + struct { + void** dev_ptr; + void* dev_ptr__val; + size_t size; + unsigned int flags; + } hipMallocManaged; + struct { + hipMipmappedArray_t* mipmappedArray; + hipMipmappedArray_t mipmappedArray__val; + const hipChannelFormatDesc* desc; + hipChannelFormatDesc desc__val; + hipExtent extent; + unsigned int numLevels; + unsigned int flags; + } hipMallocMipmappedArray; + struct { + void** ptr; + void* ptr__val; + size_t* pitch; + size_t pitch__val; + size_t width; + size_t height; + } hipMallocPitch; + struct { + void* devPtr; + size_t size; + } hipMemAddressFree; + struct { + void** ptr; + void* ptr__val; + size_t size; + size_t alignment; + void* addr; + unsigned long long flags; + } hipMemAddressReserve; + struct { + const void* dev_ptr; + size_t count; + hipMemoryAdvise advice; + int device; + } hipMemAdvise; + struct { + void** ptr; + void* ptr__val; + size_t size; + } hipMemAllocHost; + struct { + hipDeviceptr_t* dptr; + hipDeviceptr_t dptr__val; + size_t* pitch; + size_t pitch__val; + size_t widthInBytes; + size_t height; + unsigned int elementSizeBytes; + } hipMemAllocPitch; + struct { + hipMemGenericAllocationHandle_t* handle; + hipMemGenericAllocationHandle_t handle__val; + size_t size; + const hipMemAllocationProp* prop; + hipMemAllocationProp prop__val; + unsigned long long flags; + } hipMemCreate; + struct { + void* shareableHandle; + hipMemGenericAllocationHandle_t handle; + hipMemAllocationHandleType handleType; + unsigned long long flags; + } hipMemExportToShareableHandle; + struct { + unsigned long long* flags; + unsigned long long flags__val; + const hipMemLocation* location; + hipMemLocation location__val; + void* ptr; + } hipMemGetAccess; + struct { + hipDeviceptr_t* pbase; + hipDeviceptr_t pbase__val; + size_t* psize; + size_t psize__val; + hipDeviceptr_t dptr; + } hipMemGetAddressRange; + struct { + size_t* granularity; + size_t granularity__val; + const hipMemAllocationProp* prop; + hipMemAllocationProp prop__val; + hipMemAllocationGranularity_flags option; + } hipMemGetAllocationGranularity; + struct { + hipMemAllocationProp* prop; + hipMemAllocationProp prop__val; + hipMemGenericAllocationHandle_t handle; + } hipMemGetAllocationPropertiesFromHandle; + struct { + size_t* free; + size_t free__val; + size_t* total; + size_t total__val; + } hipMemGetInfo; + struct { + hipMemGenericAllocationHandle_t* handle; + hipMemGenericAllocationHandle_t handle__val; + void* osHandle; + hipMemAllocationHandleType shHandleType; + } hipMemImportFromShareableHandle; + struct { + void* ptr; + size_t size; + size_t offset; + hipMemGenericAllocationHandle_t handle; + unsigned long long flags; + } hipMemMap; + struct { + hipArrayMapInfo* mapInfoList; + hipArrayMapInfo mapInfoList__val; + unsigned int count; + hipStream_t stream; + } hipMemMapArrayAsync; + struct { + hipMemPool_t* mem_pool; + hipMemPool_t mem_pool__val; + const hipMemPoolProps* pool_props; + hipMemPoolProps pool_props__val; + } hipMemPoolCreate; + struct { + hipMemPool_t mem_pool; + } hipMemPoolDestroy; + struct { + hipMemPoolPtrExportData* export_data; + hipMemPoolPtrExportData export_data__val; + void* dev_ptr; + } hipMemPoolExportPointer; + struct { + void* shared_handle; + hipMemPool_t mem_pool; + hipMemAllocationHandleType handle_type; + unsigned int flags; + } hipMemPoolExportToShareableHandle; + struct { + hipMemAccessFlags* flags; + hipMemAccessFlags flags__val; + hipMemPool_t mem_pool; + hipMemLocation* location; + hipMemLocation location__val; + } hipMemPoolGetAccess; + struct { + hipMemPool_t mem_pool; + hipMemPoolAttr attr; + void* value; + } hipMemPoolGetAttribute; + struct { + hipMemPool_t* mem_pool; + hipMemPool_t mem_pool__val; + void* shared_handle; + hipMemAllocationHandleType handle_type; + unsigned int flags; + } hipMemPoolImportFromShareableHandle; + struct { + void** dev_ptr; + void* dev_ptr__val; + hipMemPool_t mem_pool; + hipMemPoolPtrExportData* export_data; + hipMemPoolPtrExportData export_data__val; + } hipMemPoolImportPointer; + struct { + hipMemPool_t mem_pool; + const hipMemAccessDesc* desc_list; + hipMemAccessDesc desc_list__val; + size_t count; + } hipMemPoolSetAccess; + struct { + hipMemPool_t mem_pool; + hipMemPoolAttr attr; + void* value; + } hipMemPoolSetAttribute; + struct { + hipMemPool_t mem_pool; + size_t min_bytes_to_hold; + } hipMemPoolTrimTo; + struct { + const void* dev_ptr; + size_t count; + int device; + hipStream_t stream; + } hipMemPrefetchAsync; + struct { + void* ptr; + size_t* size; + size_t size__val; + } hipMemPtrGetInfo; + struct { + void* data; + size_t data_size; + hipMemRangeAttribute attribute; + const void* dev_ptr; + size_t count; + } hipMemRangeGetAttribute; + struct { + void** data; + void* data__val; + size_t* data_sizes; + size_t data_sizes__val; + hipMemRangeAttribute* attributes; + hipMemRangeAttribute attributes__val; + size_t num_attributes; + const void* dev_ptr; + size_t count; + } hipMemRangeGetAttributes; + struct { + hipMemGenericAllocationHandle_t handle; + } hipMemRelease; + struct { + hipMemGenericAllocationHandle_t* handle; + hipMemGenericAllocationHandle_t handle__val; + void* addr; + } hipMemRetainAllocationHandle; + struct { + void* ptr; + size_t size; + const hipMemAccessDesc* desc; + hipMemAccessDesc desc__val; + size_t count; + } hipMemSetAccess; + struct { + void* ptr; + size_t size; + } hipMemUnmap; + struct { + void* dst; + const void* src; + size_t sizeBytes; + hipMemcpyKind kind; + } hipMemcpy; + struct { + void* dst; + size_t dpitch; + const void* src; + size_t spitch; + size_t width; + size_t height; + hipMemcpyKind kind; + } hipMemcpy2D; + struct { + hipArray_t dst; + size_t wOffsetDst; + size_t hOffsetDst; + hipArray_const_t src; + size_t wOffsetSrc; + size_t hOffsetSrc; + size_t width; + size_t height; + hipMemcpyKind kind; + } hipMemcpy2DArrayToArray; + struct { + void* dst; + size_t dpitch; + const void* src; + size_t spitch; + size_t width; + size_t height; + hipMemcpyKind kind; + hipStream_t stream; + } hipMemcpy2DAsync; + struct { + void* dst; + size_t dpitch; + hipArray_const_t src; + size_t wOffset; + size_t hOffset; + size_t width; + size_t height; + hipMemcpyKind kind; + } hipMemcpy2DFromArray; + struct { + void* dst; + size_t dpitch; + hipArray_const_t src; + size_t wOffset; + size_t hOffset; + size_t width; + size_t height; + hipMemcpyKind kind; + hipStream_t stream; + } hipMemcpy2DFromArrayAsync; + struct { + hipArray_t dst; + size_t wOffset; + size_t hOffset; + const void* src; + size_t spitch; + size_t width; + size_t height; + hipMemcpyKind kind; + } hipMemcpy2DToArray; + struct { + hipArray_t dst; + size_t wOffset; + size_t hOffset; + const void* src; + size_t spitch; + size_t width; + size_t height; + hipMemcpyKind kind; + hipStream_t stream; + } hipMemcpy2DToArrayAsync; + struct { + const hipMemcpy3DParms* p; + hipMemcpy3DParms p__val; + } hipMemcpy3D; + struct { + const hipMemcpy3DParms* p; + hipMemcpy3DParms p__val; + hipStream_t stream; + } hipMemcpy3DAsync; + struct { + void* dst; + const void* src; + size_t sizeBytes; + hipMemcpyKind kind; + hipStream_t stream; + } hipMemcpyAsync; + struct { + hipArray_t dstArray; + size_t dstOffset; + hipArray_t srcArray; + size_t srcOffset; + size_t ByteCount; + } hipMemcpyAtoA; + struct { + hipDeviceptr_t dstDevice; + hipArray_t srcArray; + size_t srcOffset; + size_t ByteCount; + } hipMemcpyAtoD; + struct { + void* dst; + hipArray_t srcArray; + size_t srcOffset; + size_t count; + } hipMemcpyAtoH; + struct { + void* dstHost; + hipArray_t srcArray; + size_t srcOffset; + size_t ByteCount; + hipStream_t stream; + } hipMemcpyAtoHAsync; + struct { + hipArray_t dstArray; + size_t dstOffset; + hipDeviceptr_t srcDevice; + size_t ByteCount; + } hipMemcpyDtoA; + struct { + hipDeviceptr_t dst; + hipDeviceptr_t src; + size_t sizeBytes; + } hipMemcpyDtoD; + struct { + hipDeviceptr_t dst; + hipDeviceptr_t src; + size_t sizeBytes; + hipStream_t stream; + } hipMemcpyDtoDAsync; + struct { + void* dst; + hipDeviceptr_t src; + size_t sizeBytes; + } hipMemcpyDtoH; + struct { + void* dst; + hipDeviceptr_t src; + size_t sizeBytes; + hipStream_t stream; + } hipMemcpyDtoHAsync; + struct { + void* dst; + hipArray_const_t srcArray; + size_t wOffset; + size_t hOffset; + size_t count; + hipMemcpyKind kind; + } hipMemcpyFromArray; + struct { + void* dst; + const void* symbol; + size_t sizeBytes; + size_t offset; + hipMemcpyKind kind; + } hipMemcpyFromSymbol; + struct { + void* dst; + const void* symbol; + size_t sizeBytes; + size_t offset; + hipMemcpyKind kind; + hipStream_t stream; + } hipMemcpyFromSymbolAsync; + struct { + hipArray_t dstArray; + size_t dstOffset; + const void* srcHost; + size_t count; + } hipMemcpyHtoA; + struct { + hipArray_t dstArray; + size_t dstOffset; + const void* srcHost; + size_t ByteCount; + hipStream_t stream; + } hipMemcpyHtoAAsync; + struct { + hipDeviceptr_t dst; + void* src; + size_t sizeBytes; + } hipMemcpyHtoD; + struct { + hipDeviceptr_t dst; + void* src; + size_t sizeBytes; + hipStream_t stream; + } hipMemcpyHtoDAsync; + struct { + const hip_Memcpy2D* pCopy; + hip_Memcpy2D pCopy__val; + } hipMemcpyParam2D; + struct { + const hip_Memcpy2D* pCopy; + hip_Memcpy2D pCopy__val; + hipStream_t stream; + } hipMemcpyParam2DAsync; + struct { + void* dst; + int dstDeviceId; + const void* src; + int srcDeviceId; + size_t sizeBytes; + } hipMemcpyPeer; + struct { + void* dst; + int dstDeviceId; + const void* src; + int srcDevice; + size_t sizeBytes; + hipStream_t stream; + } hipMemcpyPeerAsync; + struct { + hipArray_t dst; + size_t wOffset; + size_t hOffset; + const void* src; + size_t count; + hipMemcpyKind kind; + } hipMemcpyToArray; + struct { + const void* symbol; + const void* src; + size_t sizeBytes; + size_t offset; + hipMemcpyKind kind; + } hipMemcpyToSymbol; + struct { + const void* symbol; + const void* src; + size_t sizeBytes; + size_t offset; + hipMemcpyKind kind; + hipStream_t stream; + } hipMemcpyToSymbolAsync; + struct { + void* dst; + const void* src; + size_t sizeBytes; + hipMemcpyKind kind; + hipStream_t stream; + } hipMemcpyWithStream; + struct { + void* dst; + int value; + size_t sizeBytes; + } hipMemset; + struct { + void* dst; + size_t pitch; + int value; + size_t width; + size_t height; + } hipMemset2D; + struct { + void* dst; + size_t pitch; + int value; + size_t width; + size_t height; + hipStream_t stream; + } hipMemset2DAsync; + struct { + hipPitchedPtr pitchedDevPtr; + int value; + hipExtent extent; + } hipMemset3D; + struct { + hipPitchedPtr pitchedDevPtr; + int value; + hipExtent extent; + hipStream_t stream; + } hipMemset3DAsync; + struct { + void* dst; + int value; + size_t sizeBytes; + hipStream_t stream; + } hipMemsetAsync; + struct { + hipDeviceptr_t dest; + unsigned short value; + size_t count; + } hipMemsetD16; + struct { + hipDeviceptr_t dest; + unsigned short value; + size_t count; + hipStream_t stream; + } hipMemsetD16Async; + struct { + hipDeviceptr_t dest; + int value; + size_t count; + } hipMemsetD32; + struct { + hipDeviceptr_t dst; + int value; + size_t count; + hipStream_t stream; + } hipMemsetD32Async; + struct { + hipDeviceptr_t dest; + unsigned char value; + size_t count; + } hipMemsetD8; + struct { + hipDeviceptr_t dest; + unsigned char value; + size_t count; + hipStream_t stream; + } hipMemsetD8Async; + struct { + hipMipmappedArray_t* pHandle; + hipMipmappedArray_t pHandle__val; + HIP_ARRAY3D_DESCRIPTOR* pMipmappedArrayDesc; + HIP_ARRAY3D_DESCRIPTOR pMipmappedArrayDesc__val; + unsigned int numMipmapLevels; + } hipMipmappedArrayCreate; + struct { + hipMipmappedArray_t hMipmappedArray; + } hipMipmappedArrayDestroy; + struct { + hipArray_t* pLevelArray; + hipArray_t pLevelArray__val; + hipMipmappedArray_t hMipMappedArray; + unsigned int level; + } hipMipmappedArrayGetLevel; + struct { + hipFunction_t* function; + hipFunction_t function__val; + hipModule_t module; + const char* kname; + char kname__val; + } hipModuleGetFunction; + struct { + hipDeviceptr_t* dptr; + hipDeviceptr_t dptr__val; + size_t* bytes; + size_t bytes__val; + hipModule_t hmod; + const char* name; + char name__val; + } hipModuleGetGlobal; + struct { + textureReference** texRef; + textureReference* texRef__val; + hipModule_t hmod; + const char* name; + char name__val; + } hipModuleGetTexRef; + struct { + 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* kernelParams__val; + } hipModuleLaunchCooperativeKernel; + struct { + hipFunctionLaunchParams* launchParamsList; + hipFunctionLaunchParams launchParamsList__val; + unsigned int numDevices; + unsigned int flags; + } hipModuleLaunchCooperativeKernelMultiDevice; + struct { + 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* kernelParams__val; + void** extra; + void* extra__val; + } hipModuleLaunchKernel; + struct { + hipModule_t* module; + hipModule_t module__val; + const char* fname; + char fname__val; + } hipModuleLoad; + struct { + hipModule_t* module; + hipModule_t module__val; + const void* image; + } hipModuleLoadData; + struct { + hipModule_t* module; + hipModule_t module__val; + const void* image; + unsigned int numOptions; + hipJitOption* options; + hipJitOption options__val; + void** optionsValues; + void* optionsValues__val; + } hipModuleLoadDataEx; + struct { + int* numBlocks; + int numBlocks__val; + hipFunction_t f; + int blockSize; + size_t dynSharedMemPerBlk; + } hipModuleOccupancyMaxActiveBlocksPerMultiprocessor; + struct { + int* numBlocks; + int numBlocks__val; + hipFunction_t f; + int blockSize; + size_t dynSharedMemPerBlk; + unsigned int flags; + } hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags; + struct { + int* gridSize; + int gridSize__val; + int* blockSize; + int blockSize__val; + hipFunction_t f; + size_t dynSharedMemPerBlk; + int blockSizeLimit; + } hipModuleOccupancyMaxPotentialBlockSize; + struct { + int* gridSize; + int gridSize__val; + int* blockSize; + int blockSize__val; + hipFunction_t f; + size_t dynSharedMemPerBlk; + int blockSizeLimit; + unsigned int flags; + } hipModuleOccupancyMaxPotentialBlockSizeWithFlags; + struct { + hipModule_t module; + } hipModuleUnload; + struct { + int* numBlocks; + int numBlocks__val; + const void* f; + int blockSize; + size_t dynamicSMemSize; + } hipOccupancyMaxActiveBlocksPerMultiprocessor; + struct { + int* numBlocks; + int numBlocks__val; + const void* f; + int blockSize; + size_t dynamicSMemSize; + unsigned int flags; + } hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags; + struct { + int* gridSize; + int gridSize__val; + int* blockSize; + int blockSize__val; + const void* f; + size_t dynSharedMemPerBlk; + int blockSizeLimit; + } hipOccupancyMaxPotentialBlockSize; + struct { + void* data; + hipPointer_attribute attribute; + hipDeviceptr_t ptr; + } hipPointerGetAttribute; + struct { + hipPointerAttribute_t* attributes; + hipPointerAttribute_t attributes__val; + const void* ptr; + } hipPointerGetAttributes; + struct { + const void* value; + hipPointer_attribute attribute; + hipDeviceptr_t ptr; + } hipPointerSetAttribute; + struct { + int* runtimeVersion; + int runtimeVersion__val; + } hipRuntimeGetVersion; + struct { + int deviceId; + } hipSetDevice; + struct { + unsigned int flags; + } hipSetDeviceFlags; + struct { + int* device_arr; + int device_arr__val; + int len; + } hipSetValidDevices; + struct { + const void* arg; + size_t size; + size_t offset; + } hipSetupArgument; + struct { + const hipExternalSemaphore_t* extSemArray; + hipExternalSemaphore_t extSemArray__val; + const hipExternalSemaphoreSignalParams* paramsArray; + hipExternalSemaphoreSignalParams paramsArray__val; + unsigned int numExtSems; + hipStream_t stream; + } hipSignalExternalSemaphoresAsync; + struct { + hipStream_t stream; + hipStreamCallback_t callback; + void* userData; + unsigned int flags; + } hipStreamAddCallback; + struct { + hipStream_t stream; + void* dev_ptr; + size_t length; + unsigned int flags; + } hipStreamAttachMemAsync; + struct { + hipStream_t stream; + hipStreamCaptureMode mode; + } hipStreamBeginCapture; + struct { + hipStream_t stream; + hipGraph_t graph; + const hipGraphNode_t* dependencies; + hipGraphNode_t dependencies__val; + const hipGraphEdgeData* dependencyData; + hipGraphEdgeData dependencyData__val; + size_t numDependencies; + hipStreamCaptureMode mode; + } hipStreamBeginCaptureToGraph; + struct { + hipStream_t* stream; + hipStream_t stream__val; + } hipStreamCreate; + struct { + hipStream_t* stream; + hipStream_t stream__val; + unsigned int flags; + } hipStreamCreateWithFlags; + struct { + hipStream_t* stream; + hipStream_t stream__val; + unsigned int flags; + int priority; + } hipStreamCreateWithPriority; + struct { + hipStream_t stream; + } hipStreamDestroy; + struct { + hipStream_t stream; + hipGraph_t* pGraph; + hipGraph_t pGraph__val; + } hipStreamEndCapture; + struct { + hipStream_t stream; + hipStreamCaptureStatus* pCaptureStatus; + hipStreamCaptureStatus pCaptureStatus__val; + unsigned long long* pId; + unsigned long long pId__val; + } hipStreamGetCaptureInfo; + struct { + hipStream_t stream; + hipStreamCaptureStatus* captureStatus_out; + hipStreamCaptureStatus captureStatus_out__val; + unsigned long long* id_out; + unsigned long long id_out__val; + hipGraph_t* graph_out; + hipGraph_t graph_out__val; + const hipGraphNode_t** dependencies_out; + const hipGraphNode_t* dependencies_out__val; + size_t* numDependencies_out; + size_t numDependencies_out__val; + } hipStreamGetCaptureInfo_v2; + struct { + hipStream_t stream; + hipDevice_t* device; + hipDevice_t device__val; + } hipStreamGetDevice; + struct { + hipStream_t stream; + unsigned int* flags; + unsigned int flags__val; + } hipStreamGetFlags; + struct { + hipStream_t stream; + int* priority; + int priority__val; + } hipStreamGetPriority; + struct { + hipStream_t stream; + hipStreamCaptureStatus* pCaptureStatus; + hipStreamCaptureStatus pCaptureStatus__val; + } hipStreamIsCapturing; + struct { + hipStream_t stream; + } hipStreamQuery; + struct { + hipStream_t stream; + } hipStreamSynchronize; + struct { + hipStream_t stream; + hipGraphNode_t* dependencies; + hipGraphNode_t dependencies__val; + size_t numDependencies; + unsigned int flags; + } hipStreamUpdateCaptureDependencies; + struct { + hipStream_t stream; + hipEvent_t event; + unsigned int flags; + } hipStreamWaitEvent; + struct { + hipStream_t stream; + void* ptr; + unsigned int value; + unsigned int flags; + unsigned int mask; + } hipStreamWaitValue32; + struct { + hipStream_t stream; + void* ptr; + uint64_t value; + unsigned int flags; + uint64_t mask; + } hipStreamWaitValue64; + struct { + hipStream_t stream; + void* ptr; + unsigned int value; + unsigned int flags; + } hipStreamWriteValue32; + struct { + hipStream_t stream; + void* ptr; + uint64_t value; + unsigned int flags; + } hipStreamWriteValue64; + struct { + hipDeviceptr_t* dev_ptr; + hipDeviceptr_t dev_ptr__val; + const textureReference* texRef; + textureReference texRef__val; + } hipTexRefGetAddress; + struct { + hipArray_t* pArray; + hipArray_t pArray__val; + const textureReference* texRef; + textureReference texRef__val; + } hipTexRefGetArray; + struct { + float* pBorderColor; + float pBorderColor__val; + const textureReference* texRef; + textureReference texRef__val; + } hipTexRefGetBorderColor; + struct { + unsigned int* pFlags; + unsigned int pFlags__val; + const textureReference* texRef; + textureReference texRef__val; + } hipTexRefGetFlags; + struct { + hipArray_Format* pFormat; + hipArray_Format pFormat__val; + int* pNumChannels; + int pNumChannels__val; + const textureReference* texRef; + textureReference texRef__val; + } hipTexRefGetFormat; + struct { + int* pmaxAnsio; + int pmaxAnsio__val; + const textureReference* texRef; + textureReference texRef__val; + } hipTexRefGetMaxAnisotropy; + struct { + hipMipmappedArray_t* pArray; + hipMipmappedArray_t pArray__val; + const textureReference* texRef; + textureReference texRef__val; + } hipTexRefGetMipMappedArray; + struct { + float* pbias; + float pbias__val; + const textureReference* texRef; + textureReference texRef__val; + } hipTexRefGetMipmapLevelBias; + struct { + float* pminMipmapLevelClamp; + float pminMipmapLevelClamp__val; + float* pmaxMipmapLevelClamp; + float pmaxMipmapLevelClamp__val; + const textureReference* texRef; + textureReference texRef__val; + } hipTexRefGetMipmapLevelClamp; + struct { + size_t* ByteOffset; + size_t ByteOffset__val; + textureReference* texRef; + textureReference texRef__val; + hipDeviceptr_t dptr; + size_t bytes; + } hipTexRefSetAddress; + struct { + textureReference* texRef; + textureReference texRef__val; + const HIP_ARRAY_DESCRIPTOR* desc; + HIP_ARRAY_DESCRIPTOR desc__val; + hipDeviceptr_t dptr; + size_t Pitch; + } hipTexRefSetAddress2D; + struct { + textureReference* tex; + textureReference tex__val; + hipArray_const_t array; + unsigned int flags; + } hipTexRefSetArray; + struct { + textureReference* texRef; + textureReference texRef__val; + float* pBorderColor; + float pBorderColor__val; + } hipTexRefSetBorderColor; + struct { + textureReference* texRef; + textureReference texRef__val; + unsigned int Flags; + } hipTexRefSetFlags; + struct { + textureReference* texRef; + textureReference texRef__val; + hipArray_Format fmt; + int NumPackedComponents; + } hipTexRefSetFormat; + struct { + textureReference* texRef; + textureReference texRef__val; + unsigned int maxAniso; + } hipTexRefSetMaxAnisotropy; + struct { + textureReference* texRef; + textureReference texRef__val; + float bias; + } hipTexRefSetMipmapLevelBias; + struct { + textureReference* texRef; + textureReference texRef__val; + float minMipMapLevelClamp; + float maxMipMapLevelClamp; + } hipTexRefSetMipmapLevelClamp; + struct { + textureReference* texRef; + textureReference texRef__val; + hipMipmappedArray* mipmappedArray; + hipMipmappedArray mipmappedArray__val; + unsigned int Flags; + } hipTexRefSetMipmappedArray; + struct { + hipStreamCaptureMode* mode; + hipStreamCaptureMode mode__val; + } hipThreadExchangeStreamCaptureMode; + struct { + hipUserObject_t* object_out; + hipUserObject_t object_out__val; + void* ptr; + hipHostFn_t destroy; + unsigned int initialRefcount; + unsigned int flags; + } hipUserObjectCreate; + struct { + hipUserObject_t object; + unsigned int count; + } hipUserObjectRelease; + struct { + hipUserObject_t object; + unsigned int count; + } hipUserObjectRetain; + struct { + const hipExternalSemaphore_t* extSemArray; + hipExternalSemaphore_t extSemArray__val; + const hipExternalSemaphoreWaitParams* paramsArray; + hipExternalSemaphoreWaitParams paramsArray__val; + unsigned int numExtSems; + hipStream_t stream; + } hipWaitExternalSemaphoresAsync; + } args; + uint64_t *phase_data; +} hip_api_data_t; + +// HIP API callbacks args data filling macros +// __hipPopCallConfiguration[('dim3*', 'gridDim'), ('dim3*', 'blockDim'), ('size_t*', 'sharedMem'), ('hipStream_t*', 'stream')] +#define INIT___hipPopCallConfiguration_CB_ARGS_DATA(cb_data) { \ + cb_data.args.__hipPopCallConfiguration.gridDim = (dim3*)gridDim; \ + cb_data.args.__hipPopCallConfiguration.blockDim = (dim3*)blockDim; \ + cb_data.args.__hipPopCallConfiguration.sharedMem = (size_t*)sharedMem; \ + cb_data.args.__hipPopCallConfiguration.stream = (hipStream_t*)stream; \ +}; +// __hipPushCallConfiguration[('dim3', 'gridDim'), ('dim3', 'blockDim'), ('size_t', 'sharedMem'), ('hipStream_t', 'stream')] +#define INIT___hipPushCallConfiguration_CB_ARGS_DATA(cb_data) { \ + cb_data.args.__hipPushCallConfiguration.gridDim = (dim3)gridDim; \ + cb_data.args.__hipPushCallConfiguration.blockDim = (dim3)blockDim; \ + cb_data.args.__hipPushCallConfiguration.sharedMem = (size_t)sharedMem; \ + cb_data.args.__hipPushCallConfiguration.stream = (hipStream_t)stream; \ +}; +// hipArray3DCreate[('hipArray_t*', 'array'), ('const HIP_ARRAY3D_DESCRIPTOR*', 'pAllocateArray')] +#define INIT_hipArray3DCreate_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipArray3DCreate.array = (hipArray_t*)array; \ + cb_data.args.hipArray3DCreate.pAllocateArray = (const HIP_ARRAY3D_DESCRIPTOR*)pAllocateArray; \ +}; +// hipArray3DGetDescriptor[('HIP_ARRAY3D_DESCRIPTOR*', 'pArrayDescriptor'), ('hipArray_t', 'array')] +#define INIT_hipArray3DGetDescriptor_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipArray3DGetDescriptor.pArrayDescriptor = (HIP_ARRAY3D_DESCRIPTOR*)pArrayDescriptor; \ + cb_data.args.hipArray3DGetDescriptor.array = (hipArray_t)array; \ +}; +// hipArrayCreate[('hipArray_t*', 'pHandle'), ('const HIP_ARRAY_DESCRIPTOR*', 'pAllocateArray')] +#define INIT_hipArrayCreate_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipArrayCreate.pHandle = (hipArray_t*)array; \ + cb_data.args.hipArrayCreate.pAllocateArray = (const HIP_ARRAY_DESCRIPTOR*)pAllocateArray; \ +}; +// hipArrayDestroy[('hipArray_t', 'array')] +#define INIT_hipArrayDestroy_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipArrayDestroy.array = (hipArray_t)array; \ +}; +// hipArrayGetDescriptor[('HIP_ARRAY_DESCRIPTOR*', 'pArrayDescriptor'), ('hipArray_t', 'array')] +#define INIT_hipArrayGetDescriptor_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipArrayGetDescriptor.pArrayDescriptor = (HIP_ARRAY_DESCRIPTOR*)pArrayDescriptor; \ + cb_data.args.hipArrayGetDescriptor.array = (hipArray_t)array; \ +}; +// hipArrayGetInfo[('hipChannelFormatDesc*', 'desc'), ('hipExtent*', 'extent'), ('unsigned int*', 'flags'), ('hipArray_t', 'array')] +#define INIT_hipArrayGetInfo_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipArrayGetInfo.desc = (hipChannelFormatDesc*)desc; \ + cb_data.args.hipArrayGetInfo.extent = (hipExtent*)extent; \ + cb_data.args.hipArrayGetInfo.flags = (unsigned int*)flags; \ + cb_data.args.hipArrayGetInfo.array = (hipArray_t)array; \ +}; +// hipChooseDeviceR0000[('int*', 'device'), ('const hipDeviceProp_tR0000*', 'prop')] +#define INIT_hipChooseDeviceR0000_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipChooseDeviceR0000.device = (int*)device; \ + cb_data.args.hipChooseDeviceR0000.prop = (const hipDeviceProp_tR0000*)properties; \ +}; +// hipChooseDeviceR0600[('int*', 'device'), ('const hipDeviceProp_tR0600*', 'prop')] +#define INIT_hipChooseDeviceR0600_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipChooseDeviceR0600.device = (int*)device; \ + cb_data.args.hipChooseDeviceR0600.prop = (const hipDeviceProp_tR0600*)properties; \ +}; +// hipConfigureCall[('dim3', 'gridDim'), ('dim3', 'blockDim'), ('size_t', 'sharedMem'), ('hipStream_t', 'stream')] +#define INIT_hipConfigureCall_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipConfigureCall.gridDim = (dim3)gridDim; \ + cb_data.args.hipConfigureCall.blockDim = (dim3)blockDim; \ + cb_data.args.hipConfigureCall.sharedMem = (size_t)sharedMem; \ + cb_data.args.hipConfigureCall.stream = (hipStream_t)stream; \ +}; +// hipCreateSurfaceObject[('hipSurfaceObject_t*', 'pSurfObject'), ('const hipResourceDesc*', 'pResDesc')] +#define INIT_hipCreateSurfaceObject_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCreateSurfaceObject.pSurfObject = (hipSurfaceObject_t*)pSurfObject; \ + cb_data.args.hipCreateSurfaceObject.pResDesc = (const hipResourceDesc*)pResDesc; \ +}; +// hipCtxCreate[('hipCtx_t*', 'ctx'), ('unsigned int', 'flags'), ('hipDevice_t', 'device')] +#define INIT_hipCtxCreate_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCtxCreate.ctx = (hipCtx_t*)ctx; \ + cb_data.args.hipCtxCreate.flags = (unsigned int)flags; \ + cb_data.args.hipCtxCreate.device = (hipDevice_t)device; \ +}; +// hipCtxDestroy[('hipCtx_t', 'ctx')] +#define INIT_hipCtxDestroy_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCtxDestroy.ctx = (hipCtx_t)ctx; \ +}; +// hipCtxDisablePeerAccess[('hipCtx_t', 'peerCtx')] +#define INIT_hipCtxDisablePeerAccess_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCtxDisablePeerAccess.peerCtx = (hipCtx_t)peerCtx; \ +}; +// hipCtxEnablePeerAccess[('hipCtx_t', 'peerCtx'), ('unsigned int', 'flags')] +#define INIT_hipCtxEnablePeerAccess_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCtxEnablePeerAccess.peerCtx = (hipCtx_t)peerCtx; \ + cb_data.args.hipCtxEnablePeerAccess.flags = (unsigned int)flags; \ +}; +// hipCtxGetApiVersion[('hipCtx_t', 'ctx'), ('int*', 'apiVersion')] +#define INIT_hipCtxGetApiVersion_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCtxGetApiVersion.ctx = (hipCtx_t)ctx; \ + cb_data.args.hipCtxGetApiVersion.apiVersion = (int*)apiVersion; \ +}; +// hipCtxGetCacheConfig[('hipFuncCache_t*', 'cacheConfig')] +#define INIT_hipCtxGetCacheConfig_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCtxGetCacheConfig.cacheConfig = (hipFuncCache_t*)cacheConfig; \ +}; +// hipCtxGetCurrent[('hipCtx_t*', 'ctx')] +#define INIT_hipCtxGetCurrent_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCtxGetCurrent.ctx = (hipCtx_t*)ctx; \ +}; +// hipCtxGetDevice[('hipDevice_t*', 'device')] +#define INIT_hipCtxGetDevice_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCtxGetDevice.device = (hipDevice_t*)device; \ +}; +// hipCtxGetFlags[('unsigned int*', 'flags')] +#define INIT_hipCtxGetFlags_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCtxGetFlags.flags = (unsigned int*)flags; \ +}; +// hipCtxGetSharedMemConfig[('hipSharedMemConfig*', 'pConfig')] +#define INIT_hipCtxGetSharedMemConfig_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCtxGetSharedMemConfig.pConfig = (hipSharedMemConfig*)pConfig; \ +}; +// hipCtxPopCurrent[('hipCtx_t*', 'ctx')] +#define INIT_hipCtxPopCurrent_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCtxPopCurrent.ctx = (hipCtx_t*)ctx; \ +}; +// hipCtxPushCurrent[('hipCtx_t', 'ctx')] +#define INIT_hipCtxPushCurrent_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCtxPushCurrent.ctx = (hipCtx_t)ctx; \ +}; +// hipCtxSetCacheConfig[('hipFuncCache_t', 'cacheConfig')] +#define INIT_hipCtxSetCacheConfig_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCtxSetCacheConfig.cacheConfig = (hipFuncCache_t)cacheConfig; \ +}; +// hipCtxSetCurrent[('hipCtx_t', 'ctx')] +#define INIT_hipCtxSetCurrent_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCtxSetCurrent.ctx = (hipCtx_t)ctx; \ +}; +// hipCtxSetSharedMemConfig[('hipSharedMemConfig', 'config')] +#define INIT_hipCtxSetSharedMemConfig_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipCtxSetSharedMemConfig.config = (hipSharedMemConfig)config; \ +}; +// hipCtxSynchronize[] +#define INIT_hipCtxSynchronize_CB_ARGS_DATA(cb_data) { \ +}; +// hipDestroyExternalMemory[('hipExternalMemory_t', 'extMem')] +#define INIT_hipDestroyExternalMemory_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDestroyExternalMemory.extMem = (hipExternalMemory_t)extMem; \ +}; +// hipDestroyExternalSemaphore[('hipExternalSemaphore_t', 'extSem')] +#define INIT_hipDestroyExternalSemaphore_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDestroyExternalSemaphore.extSem = (hipExternalSemaphore_t)extSem; \ +}; +// hipDestroySurfaceObject[('hipSurfaceObject_t', 'surfaceObject')] +#define INIT_hipDestroySurfaceObject_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDestroySurfaceObject.surfaceObject = (hipSurfaceObject_t)surfaceObject; \ +}; +// hipDeviceCanAccessPeer[('int*', 'canAccessPeer'), ('int', 'deviceId'), ('int', 'peerDeviceId')] +#define INIT_hipDeviceCanAccessPeer_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceCanAccessPeer.canAccessPeer = (int*)canAccess; \ + cb_data.args.hipDeviceCanAccessPeer.deviceId = (int)deviceId; \ + cb_data.args.hipDeviceCanAccessPeer.peerDeviceId = (int)peerDeviceId; \ +}; +// hipDeviceComputeCapability[('int*', 'major'), ('int*', 'minor'), ('hipDevice_t', 'device')] +#define INIT_hipDeviceComputeCapability_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceComputeCapability.major = (int*)major; \ + cb_data.args.hipDeviceComputeCapability.minor = (int*)minor; \ + cb_data.args.hipDeviceComputeCapability.device = (hipDevice_t)device; \ +}; +// hipDeviceDisablePeerAccess[('int', 'peerDeviceId')] +#define INIT_hipDeviceDisablePeerAccess_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceDisablePeerAccess.peerDeviceId = (int)peerDeviceId; \ +}; +// hipDeviceEnablePeerAccess[('int', 'peerDeviceId'), ('unsigned int', 'flags')] +#define INIT_hipDeviceEnablePeerAccess_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceEnablePeerAccess.peerDeviceId = (int)peerDeviceId; \ + cb_data.args.hipDeviceEnablePeerAccess.flags = (unsigned int)flags; \ +}; +// hipDeviceGet[('hipDevice_t*', 'device'), ('int', 'ordinal')] +#define INIT_hipDeviceGet_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceGet.device = (hipDevice_t*)device; \ + cb_data.args.hipDeviceGet.ordinal = (int)deviceId; \ +}; +// hipDeviceGetAttribute[('int*', 'pi'), ('hipDeviceAttribute_t', 'attr'), ('int', 'deviceId')] +#define INIT_hipDeviceGetAttribute_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceGetAttribute.pi = (int*)pi; \ + cb_data.args.hipDeviceGetAttribute.attr = (hipDeviceAttribute_t)attr; \ + cb_data.args.hipDeviceGetAttribute.deviceId = (int)device; \ +}; +// hipDeviceGetByPCIBusId[('int*', 'device'), ('const char*', 'pciBusId')] +#define INIT_hipDeviceGetByPCIBusId_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceGetByPCIBusId.device = (int*)device; \ + cb_data.args.hipDeviceGetByPCIBusId.pciBusId = (pciBusIdstr) ? strdup(pciBusIdstr) : NULL; \ +}; +// hipDeviceGetCacheConfig[('hipFuncCache_t*', 'cacheConfig')] +#define INIT_hipDeviceGetCacheConfig_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceGetCacheConfig.cacheConfig = (hipFuncCache_t*)cacheConfig; \ +}; +// hipDeviceGetDefaultMemPool[('hipMemPool_t*', 'mem_pool'), ('int', 'device')] +#define INIT_hipDeviceGetDefaultMemPool_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceGetDefaultMemPool.mem_pool = (hipMemPool_t*)mem_pool; \ + cb_data.args.hipDeviceGetDefaultMemPool.device = (int)device; \ +}; +// hipDeviceGetGraphMemAttribute[('int', 'device'), ('hipGraphMemAttributeType', 'attr'), ('void*', 'value')] +#define INIT_hipDeviceGetGraphMemAttribute_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceGetGraphMemAttribute.device = (int)device; \ + cb_data.args.hipDeviceGetGraphMemAttribute.attr = (hipGraphMemAttributeType)attr; \ + cb_data.args.hipDeviceGetGraphMemAttribute.value = (void*)value; \ +}; +// hipDeviceGetLimit[('size_t*', 'pValue'), ('hipLimit_t', 'limit')] +#define INIT_hipDeviceGetLimit_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceGetLimit.pValue = (size_t*)pValue; \ + cb_data.args.hipDeviceGetLimit.limit = (hipLimit_t)limit; \ +}; +// hipDeviceGetMemPool[('hipMemPool_t*', 'mem_pool'), ('int', 'device')] +#define INIT_hipDeviceGetMemPool_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceGetMemPool.mem_pool = (hipMemPool_t*)mem_pool; \ + cb_data.args.hipDeviceGetMemPool.device = (int)device; \ +}; +// hipDeviceGetName[('char*', 'name'), ('int', 'len'), ('hipDevice_t', 'device')] +#define INIT_hipDeviceGetName_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceGetName.name = (char*)name; \ + cb_data.args.hipDeviceGetName.len = (int)len; \ + cb_data.args.hipDeviceGetName.device = (hipDevice_t)device; \ +}; +// hipDeviceGetP2PAttribute[('int*', 'value'), ('hipDeviceP2PAttr', 'attr'), ('int', 'srcDevice'), ('int', 'dstDevice')] +#define INIT_hipDeviceGetP2PAttribute_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceGetP2PAttribute.value = (int*)value; \ + cb_data.args.hipDeviceGetP2PAttribute.attr = (hipDeviceP2PAttr)attr; \ + cb_data.args.hipDeviceGetP2PAttribute.srcDevice = (int)srcDevice; \ + cb_data.args.hipDeviceGetP2PAttribute.dstDevice = (int)dstDevice; \ +}; +// hipDeviceGetPCIBusId[('char*', 'pciBusId'), ('int', 'len'), ('int', 'device')] +#define INIT_hipDeviceGetPCIBusId_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceGetPCIBusId.pciBusId = (char*)pciBusId; \ + cb_data.args.hipDeviceGetPCIBusId.len = (int)len; \ + cb_data.args.hipDeviceGetPCIBusId.device = (int)device; \ +}; +// hipDeviceGetSharedMemConfig[('hipSharedMemConfig*', 'pConfig')] +#define INIT_hipDeviceGetSharedMemConfig_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceGetSharedMemConfig.pConfig = (hipSharedMemConfig*)pConfig; \ +}; +// hipDeviceGetStreamPriorityRange[('int*', 'leastPriority'), ('int*', 'greatestPriority')] +#define INIT_hipDeviceGetStreamPriorityRange_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceGetStreamPriorityRange.leastPriority = (int*)leastPriority; \ + cb_data.args.hipDeviceGetStreamPriorityRange.greatestPriority = (int*)greatestPriority; \ +}; +// hipDeviceGetUuid[('hipUUID*', 'uuid'), ('hipDevice_t', 'device')] +#define INIT_hipDeviceGetUuid_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceGetUuid.uuid = (hipUUID*)uuid; \ + cb_data.args.hipDeviceGetUuid.device = (hipDevice_t)device; \ +}; +// hipDeviceGraphMemTrim[('int', 'device')] +#define INIT_hipDeviceGraphMemTrim_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceGraphMemTrim.device = (int)device; \ +}; +// hipDevicePrimaryCtxGetState[('hipDevice_t', 'dev'), ('unsigned int*', 'flags'), ('int*', 'active')] +#define INIT_hipDevicePrimaryCtxGetState_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDevicePrimaryCtxGetState.dev = (hipDevice_t)dev; \ + cb_data.args.hipDevicePrimaryCtxGetState.flags = (unsigned int*)flags; \ + cb_data.args.hipDevicePrimaryCtxGetState.active = (int*)active; \ +}; +// hipDevicePrimaryCtxRelease[('hipDevice_t', 'dev')] +#define INIT_hipDevicePrimaryCtxRelease_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDevicePrimaryCtxRelease.dev = (hipDevice_t)dev; \ +}; +// hipDevicePrimaryCtxReset[('hipDevice_t', 'dev')] +#define INIT_hipDevicePrimaryCtxReset_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDevicePrimaryCtxReset.dev = (hipDevice_t)dev; \ +}; +// hipDevicePrimaryCtxRetain[('hipCtx_t*', 'pctx'), ('hipDevice_t', 'dev')] +#define INIT_hipDevicePrimaryCtxRetain_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDevicePrimaryCtxRetain.pctx = (hipCtx_t*)pctx; \ + cb_data.args.hipDevicePrimaryCtxRetain.dev = (hipDevice_t)dev; \ +}; +// hipDevicePrimaryCtxSetFlags[('hipDevice_t', 'dev'), ('unsigned int', 'flags')] +#define INIT_hipDevicePrimaryCtxSetFlags_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDevicePrimaryCtxSetFlags.dev = (hipDevice_t)dev; \ + cb_data.args.hipDevicePrimaryCtxSetFlags.flags = (unsigned int)flags; \ +}; +// hipDeviceReset[] +#define INIT_hipDeviceReset_CB_ARGS_DATA(cb_data) { \ +}; +// hipDeviceSetCacheConfig[('hipFuncCache_t', 'cacheConfig')] +#define INIT_hipDeviceSetCacheConfig_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceSetCacheConfig.cacheConfig = (hipFuncCache_t)cacheConfig; \ +}; +// hipDeviceSetGraphMemAttribute[('int', 'device'), ('hipGraphMemAttributeType', 'attr'), ('void*', 'value')] +#define INIT_hipDeviceSetGraphMemAttribute_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceSetGraphMemAttribute.device = (int)device; \ + cb_data.args.hipDeviceSetGraphMemAttribute.attr = (hipGraphMemAttributeType)attr; \ + cb_data.args.hipDeviceSetGraphMemAttribute.value = (void*)value; \ +}; +// hipDeviceSetLimit[('hipLimit_t', 'limit'), ('size_t', 'value')] +#define INIT_hipDeviceSetLimit_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceSetLimit.limit = (hipLimit_t)limit; \ + cb_data.args.hipDeviceSetLimit.value = (size_t)value; \ +}; +// hipDeviceSetMemPool[('int', 'device'), ('hipMemPool_t', 'mem_pool')] +#define INIT_hipDeviceSetMemPool_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceSetMemPool.device = (int)device; \ + cb_data.args.hipDeviceSetMemPool.mem_pool = (hipMemPool_t)mem_pool; \ +}; +// hipDeviceSetSharedMemConfig[('hipSharedMemConfig', 'config')] +#define INIT_hipDeviceSetSharedMemConfig_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceSetSharedMemConfig.config = (hipSharedMemConfig)config; \ +}; +// hipDeviceSynchronize[] +#define INIT_hipDeviceSynchronize_CB_ARGS_DATA(cb_data) { \ +}; +// hipDeviceTotalMem[('size_t*', 'bytes'), ('hipDevice_t', 'device')] +#define INIT_hipDeviceTotalMem_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDeviceTotalMem.bytes = (size_t*)bytes; \ + cb_data.args.hipDeviceTotalMem.device = (hipDevice_t)device; \ +}; +// hipDriverGetVersion[('int*', 'driverVersion')] +#define INIT_hipDriverGetVersion_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDriverGetVersion.driverVersion = (int*)driverVersion; \ +}; +// hipDrvGraphAddMemcpyNode[('hipGraphNode_t*', 'phGraphNode'), ('hipGraph_t', 'hGraph'), ('const hipGraphNode_t*', 'dependencies'), ('size_t', 'numDependencies'), ('const HIP_MEMCPY3D*', 'copyParams'), ('hipCtx_t', 'ctx')] +#define INIT_hipDrvGraphAddMemcpyNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDrvGraphAddMemcpyNode.phGraphNode = (hipGraphNode_t*)phGraphNode; \ + cb_data.args.hipDrvGraphAddMemcpyNode.hGraph = (hipGraph_t)hGraph; \ + cb_data.args.hipDrvGraphAddMemcpyNode.dependencies = (const hipGraphNode_t*)dependencies; \ + cb_data.args.hipDrvGraphAddMemcpyNode.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipDrvGraphAddMemcpyNode.copyParams = (const HIP_MEMCPY3D*)copyParams; \ + cb_data.args.hipDrvGraphAddMemcpyNode.ctx = (hipCtx_t)ctx; \ +}; +// hipDrvGraphAddMemsetNode[('hipGraphNode_t*', 'phGraphNode'), ('hipGraph_t', 'hGraph'), ('const hipGraphNode_t*', 'dependencies'), ('size_t', 'numDependencies'), ('const HIP_MEMSET_NODE_PARAMS*', 'memsetParams'), ('hipCtx_t', 'ctx')] +#define INIT_hipDrvGraphAddMemsetNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDrvGraphAddMemsetNode.phGraphNode = (hipGraphNode_t*)phGraphNode; \ + cb_data.args.hipDrvGraphAddMemsetNode.hGraph = (hipGraph_t)hGraph; \ + cb_data.args.hipDrvGraphAddMemsetNode.dependencies = (const hipGraphNode_t*)dependencies; \ + cb_data.args.hipDrvGraphAddMemsetNode.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipDrvGraphAddMemsetNode.memsetParams = (const HIP_MEMSET_NODE_PARAMS*)memsetParams; \ + cb_data.args.hipDrvGraphAddMemsetNode.ctx = (hipCtx_t)ctx; \ +}; +// hipDrvMemcpy2DUnaligned[('const hip_Memcpy2D*', 'pCopy')] +#define INIT_hipDrvMemcpy2DUnaligned_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDrvMemcpy2DUnaligned.pCopy = (const hip_Memcpy2D*)pCopy; \ +}; +// hipDrvMemcpy3D[('const HIP_MEMCPY3D*', 'pCopy')] +#define INIT_hipDrvMemcpy3D_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDrvMemcpy3D.pCopy = (const HIP_MEMCPY3D*)pCopy; \ +}; +// hipDrvMemcpy3DAsync[('const HIP_MEMCPY3D*', 'pCopy'), ('hipStream_t', 'stream')] +#define INIT_hipDrvMemcpy3DAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDrvMemcpy3DAsync.pCopy = (const HIP_MEMCPY3D*)pCopy; \ + cb_data.args.hipDrvMemcpy3DAsync.stream = (hipStream_t)stream; \ +}; +// hipDrvPointerGetAttributes[('unsigned int', 'numAttributes'), ('hipPointer_attribute*', 'attributes'), ('void**', 'data'), ('hipDeviceptr_t', 'ptr')] +#define INIT_hipDrvPointerGetAttributes_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipDrvPointerGetAttributes.numAttributes = (unsigned int)numAttributes; \ + cb_data.args.hipDrvPointerGetAttributes.attributes = (hipPointer_attribute*)attributes; \ + cb_data.args.hipDrvPointerGetAttributes.data = (void**)data; \ + cb_data.args.hipDrvPointerGetAttributes.ptr = (hipDeviceptr_t)ptr; \ +}; +// hipEventCreate[('hipEvent_t*', 'event')] +#define INIT_hipEventCreate_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipEventCreate.event = (hipEvent_t*)event; \ +}; +// hipEventCreateWithFlags[('hipEvent_t*', 'event'), ('unsigned int', 'flags')] +#define INIT_hipEventCreateWithFlags_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipEventCreateWithFlags.event = (hipEvent_t*)event; \ + cb_data.args.hipEventCreateWithFlags.flags = (unsigned int)flags; \ +}; +// hipEventDestroy[('hipEvent_t', 'event')] +#define INIT_hipEventDestroy_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipEventDestroy.event = (hipEvent_t)event; \ +}; +// hipEventElapsedTime[('float*', 'ms'), ('hipEvent_t', 'start'), ('hipEvent_t', 'stop')] +#define INIT_hipEventElapsedTime_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipEventElapsedTime.ms = (float*)ms; \ + cb_data.args.hipEventElapsedTime.start = (hipEvent_t)start; \ + cb_data.args.hipEventElapsedTime.stop = (hipEvent_t)stop; \ +}; +// hipEventQuery[('hipEvent_t', 'event')] +#define INIT_hipEventQuery_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipEventQuery.event = (hipEvent_t)event; \ +}; +// hipEventRecord[('hipEvent_t', 'event'), ('hipStream_t', 'stream')] +#define INIT_hipEventRecord_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipEventRecord.event = (hipEvent_t)event; \ + cb_data.args.hipEventRecord.stream = (hipStream_t)stream; \ +}; +// hipEventSynchronize[('hipEvent_t', 'event')] +#define INIT_hipEventSynchronize_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipEventSynchronize.event = (hipEvent_t)event; \ +}; +// hipExtGetLastError[] +#define INIT_hipExtGetLastError_CB_ARGS_DATA(cb_data) { \ +}; +// hipExtGetLinkTypeAndHopCount[('int', 'device1'), ('int', 'device2'), ('unsigned int*', 'linktype'), ('unsigned int*', 'hopcount')] +#define INIT_hipExtGetLinkTypeAndHopCount_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipExtGetLinkTypeAndHopCount.device1 = (int)device1; \ + cb_data.args.hipExtGetLinkTypeAndHopCount.device2 = (int)device2; \ + cb_data.args.hipExtGetLinkTypeAndHopCount.linktype = (unsigned int*)linktype; \ + cb_data.args.hipExtGetLinkTypeAndHopCount.hopcount = (unsigned int*)hopcount; \ +}; +// hipExtLaunchKernel[('const void*', 'function_address'), ('dim3', 'numBlocks'), ('dim3', 'dimBlocks'), ('void**', 'args'), ('size_t', 'sharedMemBytes'), ('hipStream_t', 'stream'), ('hipEvent_t', 'startEvent'), ('hipEvent_t', 'stopEvent'), ('int', 'flags')] +#define INIT_hipExtLaunchKernel_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipExtLaunchKernel.function_address = (const void*)hostFunction; \ + cb_data.args.hipExtLaunchKernel.numBlocks = (dim3)gridDim; \ + cb_data.args.hipExtLaunchKernel.dimBlocks = (dim3)blockDim; \ + cb_data.args.hipExtLaunchKernel.args = (void**)args; \ + cb_data.args.hipExtLaunchKernel.sharedMemBytes = (size_t)sharedMemBytes; \ + cb_data.args.hipExtLaunchKernel.stream = (hipStream_t)stream; \ + cb_data.args.hipExtLaunchKernel.startEvent = (hipEvent_t)startEvent; \ + cb_data.args.hipExtLaunchKernel.stopEvent = (hipEvent_t)stopEvent; \ + cb_data.args.hipExtLaunchKernel.flags = (int)flags; \ +}; +// hipExtLaunchMultiKernelMultiDevice[('hipLaunchParams*', 'launchParamsList'), ('int', 'numDevices'), ('unsigned int', 'flags')] +#define INIT_hipExtLaunchMultiKernelMultiDevice_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipExtLaunchMultiKernelMultiDevice.launchParamsList = (hipLaunchParams*)launchParamsList; \ + cb_data.args.hipExtLaunchMultiKernelMultiDevice.numDevices = (int)numDevices; \ + cb_data.args.hipExtLaunchMultiKernelMultiDevice.flags = (unsigned int)flags; \ +}; +// hipExtMallocWithFlags[('void**', 'ptr'), ('size_t', 'sizeBytes'), ('unsigned int', 'flags')] +#define INIT_hipExtMallocWithFlags_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipExtMallocWithFlags.ptr = (void**)ptr; \ + cb_data.args.hipExtMallocWithFlags.sizeBytes = (size_t)sizeBytes; \ + cb_data.args.hipExtMallocWithFlags.flags = (unsigned int)flags; \ +}; +// hipExtModuleLaunchKernel[('hipFunction_t', 'f'), ('unsigned int', 'globalWorkSizeX'), ('unsigned int', 'globalWorkSizeY'), ('unsigned int', 'globalWorkSizeZ'), ('unsigned int', 'localWorkSizeX'), ('unsigned int', 'localWorkSizeY'), ('unsigned int', 'localWorkSizeZ'), ('size_t', 'sharedMemBytes'), ('hipStream_t', 'hStream'), ('void**', 'kernelParams'), ('void**', 'extra'), ('hipEvent_t', 'startEvent'), ('hipEvent_t', 'stopEvent'), ('unsigned int', 'flags')] +#define INIT_hipExtModuleLaunchKernel_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipExtModuleLaunchKernel.f = (hipFunction_t)f; \ + cb_data.args.hipExtModuleLaunchKernel.globalWorkSizeX = (unsigned int)globalWorkSizeX; \ + cb_data.args.hipExtModuleLaunchKernel.globalWorkSizeY = (unsigned int)globalWorkSizeY; \ + cb_data.args.hipExtModuleLaunchKernel.globalWorkSizeZ = (unsigned int)globalWorkSizeZ; \ + cb_data.args.hipExtModuleLaunchKernel.localWorkSizeX = (unsigned int)localWorkSizeX; \ + cb_data.args.hipExtModuleLaunchKernel.localWorkSizeY = (unsigned int)localWorkSizeY; \ + cb_data.args.hipExtModuleLaunchKernel.localWorkSizeZ = (unsigned int)localWorkSizeZ; \ + cb_data.args.hipExtModuleLaunchKernel.sharedMemBytes = (size_t)sharedMemBytes; \ + cb_data.args.hipExtModuleLaunchKernel.hStream = (hipStream_t)hStream; \ + cb_data.args.hipExtModuleLaunchKernel.kernelParams = (void**)kernelParams; \ + cb_data.args.hipExtModuleLaunchKernel.extra = (void**)extra; \ + cb_data.args.hipExtModuleLaunchKernel.startEvent = (hipEvent_t)startEvent; \ + cb_data.args.hipExtModuleLaunchKernel.stopEvent = (hipEvent_t)stopEvent; \ + cb_data.args.hipExtModuleLaunchKernel.flags = (unsigned int)flags; \ +}; +// hipExtStreamCreateWithCUMask[('hipStream_t*', 'stream'), ('unsigned int', 'cuMaskSize'), ('const unsigned int*', 'cuMask')] +#define INIT_hipExtStreamCreateWithCUMask_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipExtStreamCreateWithCUMask.stream = (hipStream_t*)stream; \ + cb_data.args.hipExtStreamCreateWithCUMask.cuMaskSize = (unsigned int)cuMaskSize; \ + cb_data.args.hipExtStreamCreateWithCUMask.cuMask = (const unsigned int*)cuMask; \ +}; +// hipExtStreamGetCUMask[('hipStream_t', 'stream'), ('unsigned int', 'cuMaskSize'), ('unsigned int*', 'cuMask')] +#define INIT_hipExtStreamGetCUMask_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipExtStreamGetCUMask.stream = (hipStream_t)stream; \ + cb_data.args.hipExtStreamGetCUMask.cuMaskSize = (unsigned int)cuMaskSize; \ + cb_data.args.hipExtStreamGetCUMask.cuMask = (unsigned int*)cuMask; \ +}; +// hipExternalMemoryGetMappedBuffer[('void**', 'devPtr'), ('hipExternalMemory_t', 'extMem'), ('const hipExternalMemoryBufferDesc*', 'bufferDesc')] +#define INIT_hipExternalMemoryGetMappedBuffer_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipExternalMemoryGetMappedBuffer.devPtr = (void**)devPtr; \ + cb_data.args.hipExternalMemoryGetMappedBuffer.extMem = (hipExternalMemory_t)extMem; \ + cb_data.args.hipExternalMemoryGetMappedBuffer.bufferDesc = (const hipExternalMemoryBufferDesc*)bufferDesc; \ +}; +// hipExternalMemoryGetMappedMipmappedArray[('hipMipmappedArray_t*', 'mipmap'), ('hipExternalMemory_t', 'extMem'), ('const hipExternalMemoryMipmappedArrayDesc*', 'mipmapDesc')] +#define INIT_hipExternalMemoryGetMappedMipmappedArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipExternalMemoryGetMappedMipmappedArray.mipmap = (hipMipmappedArray_t*)mipmap; \ + cb_data.args.hipExternalMemoryGetMappedMipmappedArray.extMem = (hipExternalMemory_t)extMem; \ + cb_data.args.hipExternalMemoryGetMappedMipmappedArray.mipmapDesc = (const hipExternalMemoryMipmappedArrayDesc*)mipmapDesc; \ +}; +// hipFree[('void*', 'ptr')] +#define INIT_hipFree_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipFree.ptr = (void*)ptr; \ +}; +// hipFreeArray[('hipArray_t', 'array')] +#define INIT_hipFreeArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipFreeArray.array = (hipArray_t)array; \ +}; +// hipFreeAsync[('void*', 'dev_ptr'), ('hipStream_t', 'stream')] +#define INIT_hipFreeAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipFreeAsync.dev_ptr = (void*)dev_ptr; \ + cb_data.args.hipFreeAsync.stream = (hipStream_t)stream; \ +}; +// hipFreeHost[('void*', 'ptr')] +#define INIT_hipFreeHost_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipFreeHost.ptr = (void*)ptr; \ +}; +// hipFreeMipmappedArray[('hipMipmappedArray_t', 'mipmappedArray')] +#define INIT_hipFreeMipmappedArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipFreeMipmappedArray.mipmappedArray = (hipMipmappedArray_t)mipmappedArray; \ +}; +// hipFuncGetAttribute[('int*', 'value'), ('hipFunction_attribute', 'attrib'), ('hipFunction_t', 'hfunc')] +#define INIT_hipFuncGetAttribute_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipFuncGetAttribute.value = (int*)value; \ + cb_data.args.hipFuncGetAttribute.attrib = (hipFunction_attribute)attrib; \ + cb_data.args.hipFuncGetAttribute.hfunc = (hipFunction_t)hfunc; \ +}; +// hipFuncGetAttributes[('hipFuncAttributes*', 'attr'), ('const void*', 'func')] +#define INIT_hipFuncGetAttributes_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipFuncGetAttributes.attr = (hipFuncAttributes*)attr; \ + cb_data.args.hipFuncGetAttributes.func = (const void*)func; \ +}; +// hipFuncSetAttribute[('const void*', 'func'), ('hipFuncAttribute', 'attr'), ('int', 'value')] +#define INIT_hipFuncSetAttribute_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipFuncSetAttribute.func = (const void*)func; \ + cb_data.args.hipFuncSetAttribute.attr = (hipFuncAttribute)attr; \ + cb_data.args.hipFuncSetAttribute.value = (int)value; \ +}; +// hipFuncSetCacheConfig[('const void*', 'func'), ('hipFuncCache_t', 'config')] +#define INIT_hipFuncSetCacheConfig_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipFuncSetCacheConfig.func = (const void*)func; \ + cb_data.args.hipFuncSetCacheConfig.config = (hipFuncCache_t)cacheConfig; \ +}; +// hipFuncSetSharedMemConfig[('const void*', 'func'), ('hipSharedMemConfig', 'config')] +#define INIT_hipFuncSetSharedMemConfig_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipFuncSetSharedMemConfig.func = (const void*)func; \ + cb_data.args.hipFuncSetSharedMemConfig.config = (hipSharedMemConfig)config; \ +}; +// hipGLGetDevices[('unsigned int*', 'pHipDeviceCount'), ('int*', 'pHipDevices'), ('unsigned int', 'hipDeviceCount'), ('hipGLDeviceList', 'deviceList')] +#define INIT_hipGLGetDevices_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGLGetDevices.pHipDeviceCount = (unsigned int*)pHipDeviceCount; \ + cb_data.args.hipGLGetDevices.pHipDevices = (int*)pHipDevices; \ + cb_data.args.hipGLGetDevices.hipDeviceCount = (unsigned int)hipDeviceCount; \ + cb_data.args.hipGLGetDevices.deviceList = (hipGLDeviceList)deviceList; \ +}; +// hipGetChannelDesc[('hipChannelFormatDesc*', 'desc'), ('hipArray_const_t', 'array')] +#define INIT_hipGetChannelDesc_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGetChannelDesc.desc = (hipChannelFormatDesc*)desc; \ + cb_data.args.hipGetChannelDesc.array = (hipArray_const_t)array; \ +}; +// hipGetDevice[('int*', 'deviceId')] +#define INIT_hipGetDevice_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGetDevice.deviceId = (int*)deviceId; \ +}; +// hipGetDeviceCount[('int*', 'count')] +#define INIT_hipGetDeviceCount_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGetDeviceCount.count = (int*)count; \ +}; +// hipGetDeviceFlags[('unsigned int*', 'flags')] +#define INIT_hipGetDeviceFlags_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGetDeviceFlags.flags = (unsigned int*)flags; \ +}; +// hipGetDevicePropertiesR0000[('hipDeviceProp_tR0000*', 'prop'), ('int', 'device')] +#define INIT_hipGetDevicePropertiesR0000_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGetDevicePropertiesR0000.prop = (hipDeviceProp_tR0000*)prop; \ + cb_data.args.hipGetDevicePropertiesR0000.device = (int)device; \ +}; +// hipGetDevicePropertiesR0600[('hipDeviceProp_tR0600*', 'prop'), ('int', 'deviceId')] +#define INIT_hipGetDevicePropertiesR0600_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGetDevicePropertiesR0600.prop = (hipDeviceProp_tR0600*)prop; \ + cb_data.args.hipGetDevicePropertiesR0600.deviceId = (int)device; \ +}; +// hipGetErrorString[] +#define INIT_hipGetErrorString_CB_ARGS_DATA(cb_data) { \ +}; +// hipGetFuncBySymbol[('hipFunction_t*', 'functionPtr'), ('const void*', 'symbolPtr')] +#define INIT_hipGetFuncBySymbol_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGetFuncBySymbol.functionPtr = (hipFunction_t*)functionPtr; \ + cb_data.args.hipGetFuncBySymbol.symbolPtr = (const void*)symbolPtr; \ +}; +// hipGetLastError[] +#define INIT_hipGetLastError_CB_ARGS_DATA(cb_data) { \ +}; +// hipGetMipmappedArrayLevel[('hipArray_t*', 'levelArray'), ('hipMipmappedArray_const_t', 'mipmappedArray'), ('unsigned int', 'level')] +#define INIT_hipGetMipmappedArrayLevel_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGetMipmappedArrayLevel.levelArray = (hipArray_t*)levelArray; \ + cb_data.args.hipGetMipmappedArrayLevel.mipmappedArray = (hipMipmappedArray_const_t)mipmappedArray; \ + cb_data.args.hipGetMipmappedArrayLevel.level = (unsigned int)level; \ +}; +// hipGetProcAddress[('const char*', 'symbol'), ('void**', 'pfn'), ('int', 'hipVersion'), ('uint64_t', 'flags'), ('hipDriverProcAddressQueryResult*', 'symbolStatus')] +#define INIT_hipGetProcAddress_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGetProcAddress.symbol = (symbol) ? strdup(symbol) : NULL; \ + cb_data.args.hipGetProcAddress.pfn = (void**)pfn; \ + cb_data.args.hipGetProcAddress.hipVersion = (int)hipVersion; \ + cb_data.args.hipGetProcAddress.flags = (uint64_t)flags; \ + cb_data.args.hipGetProcAddress.symbolStatus = (hipDriverProcAddressQueryResult*)symbolStatus; \ +}; +// hipGetSymbolAddress[('void**', 'devPtr'), ('const void*', 'symbol')] +#define INIT_hipGetSymbolAddress_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGetSymbolAddress.devPtr = (void**)devPtr; \ + cb_data.args.hipGetSymbolAddress.symbol = (const void*)symbol; \ +}; +// hipGetSymbolSize[('size_t*', 'size'), ('const void*', 'symbol')] +#define INIT_hipGetSymbolSize_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGetSymbolSize.size = (size_t*)sizePtr; \ + cb_data.args.hipGetSymbolSize.symbol = (const void*)symbol; \ +}; +// hipGraphAddChildGraphNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('hipGraph_t', 'childGraph')] +#define INIT_hipGraphAddChildGraphNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddChildGraphNode.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddChildGraphNode.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddChildGraphNode.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddChildGraphNode.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipGraphAddChildGraphNode.childGraph = (hipGraph_t)childGraph; \ +}; +// hipGraphAddDependencies[('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'from'), ('const hipGraphNode_t*', 'to'), ('size_t', 'numDependencies')] +#define INIT_hipGraphAddDependencies_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddDependencies.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddDependencies.from = (const hipGraphNode_t*)from; \ + cb_data.args.hipGraphAddDependencies.to = (const hipGraphNode_t*)to; \ + cb_data.args.hipGraphAddDependencies.numDependencies = (size_t)numDependencies; \ +}; +// hipGraphAddEmptyNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies')] +#define INIT_hipGraphAddEmptyNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddEmptyNode.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddEmptyNode.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddEmptyNode.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddEmptyNode.numDependencies = (size_t)numDependencies; \ +}; +// hipGraphAddEventRecordNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('hipEvent_t', 'event')] +#define INIT_hipGraphAddEventRecordNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddEventRecordNode.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddEventRecordNode.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddEventRecordNode.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddEventRecordNode.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipGraphAddEventRecordNode.event = (hipEvent_t)event; \ +}; +// hipGraphAddEventWaitNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('hipEvent_t', 'event')] +#define INIT_hipGraphAddEventWaitNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddEventWaitNode.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddEventWaitNode.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddEventWaitNode.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddEventWaitNode.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipGraphAddEventWaitNode.event = (hipEvent_t)event; \ +}; +// hipGraphAddExternalSemaphoresSignalNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('const hipExternalSemaphoreSignalNodeParams*', 'nodeParams')] +#define INIT_hipGraphAddExternalSemaphoresSignalNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddExternalSemaphoresSignalNode.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddExternalSemaphoresSignalNode.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddExternalSemaphoresSignalNode.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddExternalSemaphoresSignalNode.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipGraphAddExternalSemaphoresSignalNode.nodeParams = (const hipExternalSemaphoreSignalNodeParams*)nodeParams; \ +}; +// hipGraphAddExternalSemaphoresWaitNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('const hipExternalSemaphoreWaitNodeParams*', 'nodeParams')] +#define INIT_hipGraphAddExternalSemaphoresWaitNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddExternalSemaphoresWaitNode.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddExternalSemaphoresWaitNode.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddExternalSemaphoresWaitNode.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddExternalSemaphoresWaitNode.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipGraphAddExternalSemaphoresWaitNode.nodeParams = (const hipExternalSemaphoreWaitNodeParams*)nodeParams; \ +}; +// hipGraphAddHostNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('const hipHostNodeParams*', 'pNodeParams')] +#define INIT_hipGraphAddHostNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddHostNode.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddHostNode.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddHostNode.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddHostNode.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipGraphAddHostNode.pNodeParams = (const hipHostNodeParams*)pNodeParams; \ +}; +// hipGraphAddKernelNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('const hipKernelNodeParams*', 'pNodeParams')] +#define INIT_hipGraphAddKernelNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddKernelNode.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddKernelNode.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddKernelNode.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddKernelNode.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipGraphAddKernelNode.pNodeParams = (const hipKernelNodeParams*)pNodeParams; \ +}; +// hipGraphAddMemAllocNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('hipMemAllocNodeParams*', 'pNodeParams')] +#define INIT_hipGraphAddMemAllocNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddMemAllocNode.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddMemAllocNode.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddMemAllocNode.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddMemAllocNode.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipGraphAddMemAllocNode.pNodeParams = (hipMemAllocNodeParams*)pNodeParams; \ +}; +// hipGraphAddMemFreeNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('void*', 'dev_ptr')] +#define INIT_hipGraphAddMemFreeNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddMemFreeNode.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddMemFreeNode.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddMemFreeNode.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddMemFreeNode.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipGraphAddMemFreeNode.dev_ptr = (void*)dev_ptr; \ +}; +// hipGraphAddMemcpyNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('const hipMemcpy3DParms*', 'pCopyParams')] +#define INIT_hipGraphAddMemcpyNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddMemcpyNode.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddMemcpyNode.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddMemcpyNode.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddMemcpyNode.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipGraphAddMemcpyNode.pCopyParams = (const hipMemcpy3DParms*)pCopyParams; \ +}; +// hipGraphAddMemcpyNode1D[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('void*', 'dst'), ('const void*', 'src'), ('size_t', 'count'), ('hipMemcpyKind', 'kind')] +#define INIT_hipGraphAddMemcpyNode1D_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddMemcpyNode1D.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddMemcpyNode1D.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddMemcpyNode1D.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddMemcpyNode1D.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipGraphAddMemcpyNode1D.dst = (void*)dst; \ + cb_data.args.hipGraphAddMemcpyNode1D.src = (const void*)src; \ + cb_data.args.hipGraphAddMemcpyNode1D.count = (size_t)count; \ + cb_data.args.hipGraphAddMemcpyNode1D.kind = (hipMemcpyKind)kind; \ +}; +// hipGraphAddMemcpyNodeFromSymbol[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('void*', 'dst'), ('const void*', 'symbol'), ('size_t', 'count'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] +#define INIT_hipGraphAddMemcpyNodeFromSymbol_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddMemcpyNodeFromSymbol.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddMemcpyNodeFromSymbol.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddMemcpyNodeFromSymbol.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddMemcpyNodeFromSymbol.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipGraphAddMemcpyNodeFromSymbol.dst = (void*)dst; \ + cb_data.args.hipGraphAddMemcpyNodeFromSymbol.symbol = (const void*)symbol; \ + cb_data.args.hipGraphAddMemcpyNodeFromSymbol.count = (size_t)count; \ + cb_data.args.hipGraphAddMemcpyNodeFromSymbol.offset = (size_t)offset; \ + cb_data.args.hipGraphAddMemcpyNodeFromSymbol.kind = (hipMemcpyKind)kind; \ +}; +// hipGraphAddMemcpyNodeToSymbol[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('const void*', 'symbol'), ('const void*', 'src'), ('size_t', 'count'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] +#define INIT_hipGraphAddMemcpyNodeToSymbol_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddMemcpyNodeToSymbol.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddMemcpyNodeToSymbol.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddMemcpyNodeToSymbol.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddMemcpyNodeToSymbol.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipGraphAddMemcpyNodeToSymbol.symbol = (const void*)symbol; \ + cb_data.args.hipGraphAddMemcpyNodeToSymbol.src = (const void*)src; \ + cb_data.args.hipGraphAddMemcpyNodeToSymbol.count = (size_t)count; \ + cb_data.args.hipGraphAddMemcpyNodeToSymbol.offset = (size_t)offset; \ + cb_data.args.hipGraphAddMemcpyNodeToSymbol.kind = (hipMemcpyKind)kind; \ +}; +// hipGraphAddMemsetNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('const hipMemsetParams*', 'pMemsetParams')] +#define INIT_hipGraphAddMemsetNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddMemsetNode.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddMemsetNode.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddMemsetNode.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddMemsetNode.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipGraphAddMemsetNode.pMemsetParams = (const hipMemsetParams*)pMemsetParams; \ +}; +// hipGraphAddNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('hipGraphNodeParams*', 'nodeParams')] +#define INIT_hipGraphAddNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphAddNode.pGraphNode = (hipGraphNode_t*)pGraphNode; \ + cb_data.args.hipGraphAddNode.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphAddNode.pDependencies = (const hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphAddNode.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipGraphAddNode.nodeParams = (hipGraphNodeParams*)nodeParams; \ +}; +// hipGraphChildGraphNodeGetGraph[('hipGraphNode_t', 'node'), ('hipGraph_t*', 'pGraph')] +#define INIT_hipGraphChildGraphNodeGetGraph_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphChildGraphNodeGetGraph.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphChildGraphNodeGetGraph.pGraph = (hipGraph_t*)pGraph; \ +}; +// hipGraphClone[('hipGraph_t*', 'pGraphClone'), ('hipGraph_t', 'originalGraph')] +#define INIT_hipGraphClone_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphClone.pGraphClone = (hipGraph_t*)pGraphClone; \ + cb_data.args.hipGraphClone.originalGraph = (hipGraph_t)originalGraph; \ +}; +// hipGraphCreate[('hipGraph_t*', 'pGraph'), ('unsigned int', 'flags')] +#define INIT_hipGraphCreate_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphCreate.pGraph = (hipGraph_t*)pGraph; \ + cb_data.args.hipGraphCreate.flags = (unsigned int)flags; \ +}; +// hipGraphDebugDotPrint[('hipGraph_t', 'graph'), ('const char*', 'path'), ('unsigned int', 'flags')] +#define INIT_hipGraphDebugDotPrint_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphDebugDotPrint.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphDebugDotPrint.path = (path) ? strdup(path) : NULL; \ + cb_data.args.hipGraphDebugDotPrint.flags = (unsigned int)flags; \ +}; +// hipGraphDestroy[('hipGraph_t', 'graph')] +#define INIT_hipGraphDestroy_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphDestroy.graph = (hipGraph_t)graph; \ +}; +// hipGraphDestroyNode[('hipGraphNode_t', 'node')] +#define INIT_hipGraphDestroyNode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphDestroyNode.node = (hipGraphNode_t)node; \ +}; +// hipGraphEventRecordNodeGetEvent[('hipGraphNode_t', 'node'), ('hipEvent_t*', 'event_out')] +#define INIT_hipGraphEventRecordNodeGetEvent_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphEventRecordNodeGetEvent.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphEventRecordNodeGetEvent.event_out = (hipEvent_t*)event_out; \ +}; +// hipGraphEventRecordNodeSetEvent[('hipGraphNode_t', 'node'), ('hipEvent_t', 'event')] +#define INIT_hipGraphEventRecordNodeSetEvent_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphEventRecordNodeSetEvent.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphEventRecordNodeSetEvent.event = (hipEvent_t)event; \ +}; +// hipGraphEventWaitNodeGetEvent[('hipGraphNode_t', 'node'), ('hipEvent_t*', 'event_out')] +#define INIT_hipGraphEventWaitNodeGetEvent_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphEventWaitNodeGetEvent.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphEventWaitNodeGetEvent.event_out = (hipEvent_t*)event_out; \ +}; +// hipGraphEventWaitNodeSetEvent[('hipGraphNode_t', 'node'), ('hipEvent_t', 'event')] +#define INIT_hipGraphEventWaitNodeSetEvent_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphEventWaitNodeSetEvent.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphEventWaitNodeSetEvent.event = (hipEvent_t)event; \ +}; +// hipGraphExecChildGraphNodeSetParams[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('hipGraph_t', 'childGraph')] +#define INIT_hipGraphExecChildGraphNodeSetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExecChildGraphNodeSetParams.hGraphExec = (hipGraphExec_t)hGraphExec; \ + cb_data.args.hipGraphExecChildGraphNodeSetParams.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphExecChildGraphNodeSetParams.childGraph = (hipGraph_t)childGraph; \ +}; +// hipGraphExecDestroy[('hipGraphExec_t', 'graphExec')] +#define INIT_hipGraphExecDestroy_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExecDestroy.graphExec = (hipGraphExec_t)pGraphExec; \ +}; +// hipGraphExecEventRecordNodeSetEvent[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'hNode'), ('hipEvent_t', 'event')] +#define INIT_hipGraphExecEventRecordNodeSetEvent_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExecEventRecordNodeSetEvent.hGraphExec = (hipGraphExec_t)hGraphExec; \ + cb_data.args.hipGraphExecEventRecordNodeSetEvent.hNode = (hipGraphNode_t)hNode; \ + cb_data.args.hipGraphExecEventRecordNodeSetEvent.event = (hipEvent_t)event; \ +}; +// hipGraphExecEventWaitNodeSetEvent[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'hNode'), ('hipEvent_t', 'event')] +#define INIT_hipGraphExecEventWaitNodeSetEvent_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExecEventWaitNodeSetEvent.hGraphExec = (hipGraphExec_t)hGraphExec; \ + cb_data.args.hipGraphExecEventWaitNodeSetEvent.hNode = (hipGraphNode_t)hNode; \ + cb_data.args.hipGraphExecEventWaitNodeSetEvent.event = (hipEvent_t)event; \ +}; +// hipGraphExecExternalSemaphoresSignalNodeSetParams[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'hNode'), ('const hipExternalSemaphoreSignalNodeParams*', 'nodeParams')] +#define INIT_hipGraphExecExternalSemaphoresSignalNodeSetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExecExternalSemaphoresSignalNodeSetParams.hGraphExec = (hipGraphExec_t)hGraphExec; \ + cb_data.args.hipGraphExecExternalSemaphoresSignalNodeSetParams.hNode = (hipGraphNode_t)hNode; \ + cb_data.args.hipGraphExecExternalSemaphoresSignalNodeSetParams.nodeParams = (const hipExternalSemaphoreSignalNodeParams*)nodeParams; \ +}; +// hipGraphExecExternalSemaphoresWaitNodeSetParams[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'hNode'), ('const hipExternalSemaphoreWaitNodeParams*', 'nodeParams')] +#define INIT_hipGraphExecExternalSemaphoresWaitNodeSetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExecExternalSemaphoresWaitNodeSetParams.hGraphExec = (hipGraphExec_t)hGraphExec; \ + cb_data.args.hipGraphExecExternalSemaphoresWaitNodeSetParams.hNode = (hipGraphNode_t)hNode; \ + cb_data.args.hipGraphExecExternalSemaphoresWaitNodeSetParams.nodeParams = (const hipExternalSemaphoreWaitNodeParams*)nodeParams; \ +}; +// hipGraphExecHostNodeSetParams[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('const hipHostNodeParams*', 'pNodeParams')] +#define INIT_hipGraphExecHostNodeSetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExecHostNodeSetParams.hGraphExec = (hipGraphExec_t)hGraphExec; \ + cb_data.args.hipGraphExecHostNodeSetParams.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphExecHostNodeSetParams.pNodeParams = (const hipHostNodeParams*)pNodeParams; \ +}; +// hipGraphExecKernelNodeSetParams[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('const hipKernelNodeParams*', 'pNodeParams')] +#define INIT_hipGraphExecKernelNodeSetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExecKernelNodeSetParams.hGraphExec = (hipGraphExec_t)hGraphExec; \ + cb_data.args.hipGraphExecKernelNodeSetParams.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphExecKernelNodeSetParams.pNodeParams = (const hipKernelNodeParams*)pNodeParams; \ +}; +// hipGraphExecMemcpyNodeSetParams[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('hipMemcpy3DParms*', 'pNodeParams')] +#define INIT_hipGraphExecMemcpyNodeSetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExecMemcpyNodeSetParams.hGraphExec = (hipGraphExec_t)hGraphExec; \ + cb_data.args.hipGraphExecMemcpyNodeSetParams.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphExecMemcpyNodeSetParams.pNodeParams = (hipMemcpy3DParms*)pNodeParams; \ +}; +// hipGraphExecMemcpyNodeSetParams1D[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('void*', 'dst'), ('const void*', 'src'), ('size_t', 'count'), ('hipMemcpyKind', 'kind')] +#define INIT_hipGraphExecMemcpyNodeSetParams1D_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExecMemcpyNodeSetParams1D.hGraphExec = (hipGraphExec_t)hGraphExec; \ + cb_data.args.hipGraphExecMemcpyNodeSetParams1D.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphExecMemcpyNodeSetParams1D.dst = (void*)dst; \ + cb_data.args.hipGraphExecMemcpyNodeSetParams1D.src = (const void*)src; \ + cb_data.args.hipGraphExecMemcpyNodeSetParams1D.count = (size_t)count; \ + cb_data.args.hipGraphExecMemcpyNodeSetParams1D.kind = (hipMemcpyKind)kind; \ +}; +// hipGraphExecMemcpyNodeSetParamsFromSymbol[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('void*', 'dst'), ('const void*', 'symbol'), ('size_t', 'count'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] +#define INIT_hipGraphExecMemcpyNodeSetParamsFromSymbol_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExecMemcpyNodeSetParamsFromSymbol.hGraphExec = (hipGraphExec_t)hGraphExec; \ + cb_data.args.hipGraphExecMemcpyNodeSetParamsFromSymbol.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphExecMemcpyNodeSetParamsFromSymbol.dst = (void*)dst; \ + cb_data.args.hipGraphExecMemcpyNodeSetParamsFromSymbol.symbol = (const void*)symbol; \ + cb_data.args.hipGraphExecMemcpyNodeSetParamsFromSymbol.count = (size_t)count; \ + cb_data.args.hipGraphExecMemcpyNodeSetParamsFromSymbol.offset = (size_t)offset; \ + cb_data.args.hipGraphExecMemcpyNodeSetParamsFromSymbol.kind = (hipMemcpyKind)kind; \ +}; +// hipGraphExecMemcpyNodeSetParamsToSymbol[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('const void*', 'symbol'), ('const void*', 'src'), ('size_t', 'count'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] +#define INIT_hipGraphExecMemcpyNodeSetParamsToSymbol_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExecMemcpyNodeSetParamsToSymbol.hGraphExec = (hipGraphExec_t)hGraphExec; \ + cb_data.args.hipGraphExecMemcpyNodeSetParamsToSymbol.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphExecMemcpyNodeSetParamsToSymbol.symbol = (const void*)symbol; \ + cb_data.args.hipGraphExecMemcpyNodeSetParamsToSymbol.src = (const void*)src; \ + cb_data.args.hipGraphExecMemcpyNodeSetParamsToSymbol.count = (size_t)count; \ + cb_data.args.hipGraphExecMemcpyNodeSetParamsToSymbol.offset = (size_t)offset; \ + cb_data.args.hipGraphExecMemcpyNodeSetParamsToSymbol.kind = (hipMemcpyKind)kind; \ +}; +// hipGraphExecMemsetNodeSetParams[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('const hipMemsetParams*', 'pNodeParams')] +#define INIT_hipGraphExecMemsetNodeSetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExecMemsetNodeSetParams.hGraphExec = (hipGraphExec_t)hGraphExec; \ + cb_data.args.hipGraphExecMemsetNodeSetParams.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphExecMemsetNodeSetParams.pNodeParams = (const hipMemsetParams*)pNodeParams; \ +}; +// hipGraphExecUpdate[('hipGraphExec_t', 'hGraphExec'), ('hipGraph_t', 'hGraph'), ('hipGraphNode_t*', 'hErrorNode_out'), ('hipGraphExecUpdateResult*', 'updateResult_out')] +#define INIT_hipGraphExecUpdate_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExecUpdate.hGraphExec = (hipGraphExec_t)hGraphExec; \ + cb_data.args.hipGraphExecUpdate.hGraph = (hipGraph_t)hGraph; \ + cb_data.args.hipGraphExecUpdate.hErrorNode_out = (hipGraphNode_t*)hErrorNode_out; \ + cb_data.args.hipGraphExecUpdate.updateResult_out = (hipGraphExecUpdateResult*)updateResult_out; \ +}; +// hipGraphExternalSemaphoresSignalNodeGetParams[('hipGraphNode_t', 'hNode'), ('hipExternalSemaphoreSignalNodeParams*', 'params_out')] +#define INIT_hipGraphExternalSemaphoresSignalNodeGetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExternalSemaphoresSignalNodeGetParams.hNode = (hipGraphNode_t)hNode; \ + cb_data.args.hipGraphExternalSemaphoresSignalNodeGetParams.params_out = (hipExternalSemaphoreSignalNodeParams*)params_out; \ +}; +// hipGraphExternalSemaphoresSignalNodeSetParams[('hipGraphNode_t', 'hNode'), ('const hipExternalSemaphoreSignalNodeParams*', 'nodeParams')] +#define INIT_hipGraphExternalSemaphoresSignalNodeSetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExternalSemaphoresSignalNodeSetParams.hNode = (hipGraphNode_t)hNode; \ + cb_data.args.hipGraphExternalSemaphoresSignalNodeSetParams.nodeParams = (const hipExternalSemaphoreSignalNodeParams*)nodeParams; \ +}; +// hipGraphExternalSemaphoresWaitNodeGetParams[('hipGraphNode_t', 'hNode'), ('hipExternalSemaphoreWaitNodeParams*', 'params_out')] +#define INIT_hipGraphExternalSemaphoresWaitNodeGetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExternalSemaphoresWaitNodeGetParams.hNode = (hipGraphNode_t)hNode; \ + cb_data.args.hipGraphExternalSemaphoresWaitNodeGetParams.params_out = (hipExternalSemaphoreWaitNodeParams*)params_out; \ +}; +// hipGraphExternalSemaphoresWaitNodeSetParams[('hipGraphNode_t', 'hNode'), ('const hipExternalSemaphoreWaitNodeParams*', 'nodeParams')] +#define INIT_hipGraphExternalSemaphoresWaitNodeSetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphExternalSemaphoresWaitNodeSetParams.hNode = (hipGraphNode_t)hNode; \ + cb_data.args.hipGraphExternalSemaphoresWaitNodeSetParams.nodeParams = (const hipExternalSemaphoreWaitNodeParams*)nodeParams; \ +}; +// hipGraphGetEdges[('hipGraph_t', 'graph'), ('hipGraphNode_t*', 'from'), ('hipGraphNode_t*', 'to'), ('size_t*', 'numEdges')] +#define INIT_hipGraphGetEdges_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphGetEdges.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphGetEdges.from = (hipGraphNode_t*)from; \ + cb_data.args.hipGraphGetEdges.to = (hipGraphNode_t*)to; \ + cb_data.args.hipGraphGetEdges.numEdges = (size_t*)numEdges; \ +}; +// hipGraphGetNodes[('hipGraph_t', 'graph'), ('hipGraphNode_t*', 'nodes'), ('size_t*', 'numNodes')] +#define INIT_hipGraphGetNodes_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphGetNodes.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphGetNodes.nodes = (hipGraphNode_t*)nodes; \ + cb_data.args.hipGraphGetNodes.numNodes = (size_t*)numNodes; \ +}; +// hipGraphGetRootNodes[('hipGraph_t', 'graph'), ('hipGraphNode_t*', 'pRootNodes'), ('size_t*', 'pNumRootNodes')] +#define INIT_hipGraphGetRootNodes_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphGetRootNodes.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphGetRootNodes.pRootNodes = (hipGraphNode_t*)pRootNodes; \ + cb_data.args.hipGraphGetRootNodes.pNumRootNodes = (size_t*)pNumRootNodes; \ +}; +// hipGraphHostNodeGetParams[('hipGraphNode_t', 'node'), ('hipHostNodeParams*', 'pNodeParams')] +#define INIT_hipGraphHostNodeGetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphHostNodeGetParams.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphHostNodeGetParams.pNodeParams = (hipHostNodeParams*)pNodeParams; \ +}; +// hipGraphHostNodeSetParams[('hipGraphNode_t', 'node'), ('const hipHostNodeParams*', 'pNodeParams')] +#define INIT_hipGraphHostNodeSetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphHostNodeSetParams.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphHostNodeSetParams.pNodeParams = (const hipHostNodeParams*)pNodeParams; \ +}; +// hipGraphInstantiate[('hipGraphExec_t*', 'pGraphExec'), ('hipGraph_t', 'graph'), ('hipGraphNode_t*', 'pErrorNode'), ('char*', 'pLogBuffer'), ('size_t', 'bufferSize')] +#define INIT_hipGraphInstantiate_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphInstantiate.pGraphExec = (hipGraphExec_t*)pGraphExec; \ + cb_data.args.hipGraphInstantiate.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphInstantiate.pErrorNode = (hipGraphNode_t*)pErrorNode; \ + cb_data.args.hipGraphInstantiate.pLogBuffer = (char*)pLogBuffer; \ + cb_data.args.hipGraphInstantiate.bufferSize = (size_t)bufferSize; \ +}; +// hipGraphInstantiateWithFlags[('hipGraphExec_t*', 'pGraphExec'), ('hipGraph_t', 'graph'), ('unsigned long long', 'flags')] +#define INIT_hipGraphInstantiateWithFlags_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphInstantiateWithFlags.pGraphExec = (hipGraphExec_t*)pGraphExec; \ + cb_data.args.hipGraphInstantiateWithFlags.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphInstantiateWithFlags.flags = (unsigned long long)flags; \ +}; +// hipGraphInstantiateWithParams[('hipGraphExec_t*', 'pGraphExec'), ('hipGraph_t', 'graph'), ('hipGraphInstantiateParams*', 'instantiateParams')] +#define INIT_hipGraphInstantiateWithParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphInstantiateWithParams.pGraphExec = (hipGraphExec_t*)pGraphExec; \ + cb_data.args.hipGraphInstantiateWithParams.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphInstantiateWithParams.instantiateParams = (hipGraphInstantiateParams*)instantiateParams; \ +}; +// hipGraphKernelNodeCopyAttributes[('hipGraphNode_t', 'hSrc'), ('hipGraphNode_t', 'hDst')] +#define INIT_hipGraphKernelNodeCopyAttributes_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphKernelNodeCopyAttributes.hSrc = (hipGraphNode_t)hSrc; \ + cb_data.args.hipGraphKernelNodeCopyAttributes.hDst = (hipGraphNode_t)hDst; \ +}; +// hipGraphKernelNodeGetAttribute[('hipGraphNode_t', 'hNode'), ('hipLaunchAttributeID', 'attr'), ('hipLaunchAttributeValue*', 'value')] +#define INIT_hipGraphKernelNodeGetAttribute_CB_ARGS_DATA(cb_data) { \ +}; +// hipGraphKernelNodeGetParams[('hipGraphNode_t', 'node'), ('hipKernelNodeParams*', 'pNodeParams')] +#define INIT_hipGraphKernelNodeGetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphKernelNodeGetParams.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphKernelNodeGetParams.pNodeParams = (hipKernelNodeParams*)pNodeParams; \ +}; +// hipGraphKernelNodeSetAttribute[('hipGraphNode_t', 'hNode'), ('hipLaunchAttributeID', 'attr'), ('const hipLaunchAttributeValue*', 'value')] +#define INIT_hipGraphKernelNodeSetAttribute_CB_ARGS_DATA(cb_data) { \ +}; +// hipGraphKernelNodeSetParams[('hipGraphNode_t', 'node'), ('const hipKernelNodeParams*', 'pNodeParams')] +#define INIT_hipGraphKernelNodeSetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphKernelNodeSetParams.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphKernelNodeSetParams.pNodeParams = (const hipKernelNodeParams*)pNodeParams; \ +}; +// hipGraphLaunch[('hipGraphExec_t', 'graphExec'), ('hipStream_t', 'stream')] +#define INIT_hipGraphLaunch_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphLaunch.graphExec = (hipGraphExec_t)graphExec; \ + cb_data.args.hipGraphLaunch.stream = (hipStream_t)stream; \ +}; +// hipGraphMemAllocNodeGetParams[('hipGraphNode_t', 'node'), ('hipMemAllocNodeParams*', 'pNodeParams')] +#define INIT_hipGraphMemAllocNodeGetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphMemAllocNodeGetParams.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphMemAllocNodeGetParams.pNodeParams = (hipMemAllocNodeParams*)pNodeParams; \ +}; +// hipGraphMemFreeNodeGetParams[('hipGraphNode_t', 'node'), ('void*', 'dev_ptr')] +#define INIT_hipGraphMemFreeNodeGetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphMemFreeNodeGetParams.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphMemFreeNodeGetParams.dev_ptr = (void*)dev_ptr; \ +}; +// hipGraphMemcpyNodeGetParams[('hipGraphNode_t', 'node'), ('hipMemcpy3DParms*', 'pNodeParams')] +#define INIT_hipGraphMemcpyNodeGetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphMemcpyNodeGetParams.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphMemcpyNodeGetParams.pNodeParams = (hipMemcpy3DParms*)pNodeParams; \ +}; +// hipGraphMemcpyNodeSetParams[('hipGraphNode_t', 'node'), ('const hipMemcpy3DParms*', 'pNodeParams')] +#define INIT_hipGraphMemcpyNodeSetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphMemcpyNodeSetParams.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphMemcpyNodeSetParams.pNodeParams = (const hipMemcpy3DParms*)pNodeParams; \ +}; +// hipGraphMemcpyNodeSetParams1D[('hipGraphNode_t', 'node'), ('void*', 'dst'), ('const void*', 'src'), ('size_t', 'count'), ('hipMemcpyKind', 'kind')] +#define INIT_hipGraphMemcpyNodeSetParams1D_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphMemcpyNodeSetParams1D.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphMemcpyNodeSetParams1D.dst = (void*)dst; \ + cb_data.args.hipGraphMemcpyNodeSetParams1D.src = (const void*)src; \ + cb_data.args.hipGraphMemcpyNodeSetParams1D.count = (size_t)count; \ + cb_data.args.hipGraphMemcpyNodeSetParams1D.kind = (hipMemcpyKind)kind; \ +}; +// hipGraphMemcpyNodeSetParamsFromSymbol[('hipGraphNode_t', 'node'), ('void*', 'dst'), ('const void*', 'symbol'), ('size_t', 'count'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] +#define INIT_hipGraphMemcpyNodeSetParamsFromSymbol_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphMemcpyNodeSetParamsFromSymbol.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphMemcpyNodeSetParamsFromSymbol.dst = (void*)dst; \ + cb_data.args.hipGraphMemcpyNodeSetParamsFromSymbol.symbol = (const void*)symbol; \ + cb_data.args.hipGraphMemcpyNodeSetParamsFromSymbol.count = (size_t)count; \ + cb_data.args.hipGraphMemcpyNodeSetParamsFromSymbol.offset = (size_t)offset; \ + cb_data.args.hipGraphMemcpyNodeSetParamsFromSymbol.kind = (hipMemcpyKind)kind; \ +}; +// hipGraphMemcpyNodeSetParamsToSymbol[('hipGraphNode_t', 'node'), ('const void*', 'symbol'), ('const void*', 'src'), ('size_t', 'count'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] +#define INIT_hipGraphMemcpyNodeSetParamsToSymbol_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphMemcpyNodeSetParamsToSymbol.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphMemcpyNodeSetParamsToSymbol.symbol = (const void*)symbol; \ + cb_data.args.hipGraphMemcpyNodeSetParamsToSymbol.src = (const void*)src; \ + cb_data.args.hipGraphMemcpyNodeSetParamsToSymbol.count = (size_t)count; \ + cb_data.args.hipGraphMemcpyNodeSetParamsToSymbol.offset = (size_t)offset; \ + cb_data.args.hipGraphMemcpyNodeSetParamsToSymbol.kind = (hipMemcpyKind)kind; \ +}; +// hipGraphMemsetNodeGetParams[('hipGraphNode_t', 'node'), ('hipMemsetParams*', 'pNodeParams')] +#define INIT_hipGraphMemsetNodeGetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphMemsetNodeGetParams.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphMemsetNodeGetParams.pNodeParams = (hipMemsetParams*)pNodeParams; \ +}; +// hipGraphMemsetNodeSetParams[('hipGraphNode_t', 'node'), ('const hipMemsetParams*', 'pNodeParams')] +#define INIT_hipGraphMemsetNodeSetParams_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphMemsetNodeSetParams.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphMemsetNodeSetParams.pNodeParams = (const hipMemsetParams*)pNodeParams; \ +}; +// hipGraphNodeFindInClone[('hipGraphNode_t*', 'pNode'), ('hipGraphNode_t', 'originalNode'), ('hipGraph_t', 'clonedGraph')] +#define INIT_hipGraphNodeFindInClone_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphNodeFindInClone.pNode = (hipGraphNode_t*)pNode; \ + cb_data.args.hipGraphNodeFindInClone.originalNode = (hipGraphNode_t)originalNode; \ + cb_data.args.hipGraphNodeFindInClone.clonedGraph = (hipGraph_t)clonedGraph; \ +}; +// hipGraphNodeGetDependencies[('hipGraphNode_t', 'node'), ('hipGraphNode_t*', 'pDependencies'), ('size_t*', 'pNumDependencies')] +#define INIT_hipGraphNodeGetDependencies_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphNodeGetDependencies.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphNodeGetDependencies.pDependencies = (hipGraphNode_t*)pDependencies; \ + cb_data.args.hipGraphNodeGetDependencies.pNumDependencies = (size_t*)pNumDependencies; \ +}; +// hipGraphNodeGetDependentNodes[('hipGraphNode_t', 'node'), ('hipGraphNode_t*', 'pDependentNodes'), ('size_t*', 'pNumDependentNodes')] +#define INIT_hipGraphNodeGetDependentNodes_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphNodeGetDependentNodes.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphNodeGetDependentNodes.pDependentNodes = (hipGraphNode_t*)pDependentNodes; \ + cb_data.args.hipGraphNodeGetDependentNodes.pNumDependentNodes = (size_t*)pNumDependentNodes; \ +}; +// hipGraphNodeGetEnabled[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'hNode'), ('unsigned int*', 'isEnabled')] +#define INIT_hipGraphNodeGetEnabled_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphNodeGetEnabled.hGraphExec = (hipGraphExec_t)hGraphExec; \ + cb_data.args.hipGraphNodeGetEnabled.hNode = (hipGraphNode_t)hNode; \ + cb_data.args.hipGraphNodeGetEnabled.isEnabled = (unsigned int*)isEnabled; \ +}; +// hipGraphNodeGetType[('hipGraphNode_t', 'node'), ('hipGraphNodeType*', 'pType')] +#define INIT_hipGraphNodeGetType_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphNodeGetType.node = (hipGraphNode_t)node; \ + cb_data.args.hipGraphNodeGetType.pType = (hipGraphNodeType*)pType; \ +}; +// hipGraphNodeSetEnabled[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'hNode'), ('unsigned int', 'isEnabled')] +#define INIT_hipGraphNodeSetEnabled_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphNodeSetEnabled.hGraphExec = (hipGraphExec_t)hGraphExec; \ + cb_data.args.hipGraphNodeSetEnabled.hNode = (hipGraphNode_t)hNode; \ + cb_data.args.hipGraphNodeSetEnabled.isEnabled = (unsigned int)isEnabled; \ +}; +// hipGraphReleaseUserObject[('hipGraph_t', 'graph'), ('hipUserObject_t', 'object'), ('unsigned int', 'count')] +#define INIT_hipGraphReleaseUserObject_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphReleaseUserObject.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphReleaseUserObject.object = (hipUserObject_t)object; \ + cb_data.args.hipGraphReleaseUserObject.count = (unsigned int)count; \ +}; +// hipGraphRemoveDependencies[('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'from'), ('const hipGraphNode_t*', 'to'), ('size_t', 'numDependencies')] +#define INIT_hipGraphRemoveDependencies_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphRemoveDependencies.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphRemoveDependencies.from = (const hipGraphNode_t*)from; \ + cb_data.args.hipGraphRemoveDependencies.to = (const hipGraphNode_t*)to; \ + cb_data.args.hipGraphRemoveDependencies.numDependencies = (size_t)numDependencies; \ +}; +// hipGraphRetainUserObject[('hipGraph_t', 'graph'), ('hipUserObject_t', 'object'), ('unsigned int', 'count'), ('unsigned int', 'flags')] +#define INIT_hipGraphRetainUserObject_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphRetainUserObject.graph = (hipGraph_t)graph; \ + cb_data.args.hipGraphRetainUserObject.object = (hipUserObject_t)object; \ + cb_data.args.hipGraphRetainUserObject.count = (unsigned int)count; \ + cb_data.args.hipGraphRetainUserObject.flags = (unsigned int)flags; \ +}; +// hipGraphUpload[('hipGraphExec_t', 'graphExec'), ('hipStream_t', 'stream')] +#define INIT_hipGraphUpload_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphUpload.graphExec = (hipGraphExec_t)graphExec; \ + cb_data.args.hipGraphUpload.stream = (hipStream_t)stream; \ +}; +// hipGraphicsGLRegisterBuffer[('hipGraphicsResource**', 'resource'), ('GLuint', 'buffer'), ('unsigned int', 'flags')] +#define INIT_hipGraphicsGLRegisterBuffer_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphicsGLRegisterBuffer.resource = (hipGraphicsResource**)resource; \ + cb_data.args.hipGraphicsGLRegisterBuffer.buffer = (GLuint)buffer; \ + cb_data.args.hipGraphicsGLRegisterBuffer.flags = (unsigned int)flags; \ +}; +// hipGraphicsGLRegisterImage[('hipGraphicsResource**', 'resource'), ('GLuint', 'image'), ('GLenum', 'target'), ('unsigned int', 'flags')] +#define INIT_hipGraphicsGLRegisterImage_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphicsGLRegisterImage.resource = (hipGraphicsResource**)resource; \ + cb_data.args.hipGraphicsGLRegisterImage.image = (GLuint)image; \ + cb_data.args.hipGraphicsGLRegisterImage.target = (GLenum)target; \ + cb_data.args.hipGraphicsGLRegisterImage.flags = (unsigned int)flags; \ +}; +// hipGraphicsMapResources[('int', 'count'), ('hipGraphicsResource_t*', 'resources'), ('hipStream_t', 'stream')] +#define INIT_hipGraphicsMapResources_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphicsMapResources.count = (int)count; \ + cb_data.args.hipGraphicsMapResources.resources = (hipGraphicsResource_t*)resources; \ + cb_data.args.hipGraphicsMapResources.stream = (hipStream_t)stream; \ +}; +// hipGraphicsResourceGetMappedPointer[('void**', 'devPtr'), ('size_t*', 'size'), ('hipGraphicsResource_t', 'resource')] +#define INIT_hipGraphicsResourceGetMappedPointer_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphicsResourceGetMappedPointer.devPtr = (void**)devPtr; \ + cb_data.args.hipGraphicsResourceGetMappedPointer.size = (size_t*)size; \ + cb_data.args.hipGraphicsResourceGetMappedPointer.resource = (hipGraphicsResource_t)resource; \ +}; +// hipGraphicsSubResourceGetMappedArray[('hipArray_t*', 'array'), ('hipGraphicsResource_t', 'resource'), ('unsigned int', 'arrayIndex'), ('unsigned int', 'mipLevel')] +#define INIT_hipGraphicsSubResourceGetMappedArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphicsSubResourceGetMappedArray.array = (hipArray_t*)array; \ + cb_data.args.hipGraphicsSubResourceGetMappedArray.resource = (hipGraphicsResource_t)resource; \ + cb_data.args.hipGraphicsSubResourceGetMappedArray.arrayIndex = (unsigned int)arrayIndex; \ + cb_data.args.hipGraphicsSubResourceGetMappedArray.mipLevel = (unsigned int)mipLevel; \ +}; +// hipGraphicsUnmapResources[('int', 'count'), ('hipGraphicsResource_t*', 'resources'), ('hipStream_t', 'stream')] +#define INIT_hipGraphicsUnmapResources_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphicsUnmapResources.count = (int)count; \ + cb_data.args.hipGraphicsUnmapResources.resources = (hipGraphicsResource_t*)resources; \ + cb_data.args.hipGraphicsUnmapResources.stream = (hipStream_t)stream; \ +}; +// hipGraphicsUnregisterResource[('hipGraphicsResource_t', 'resource')] +#define INIT_hipGraphicsUnregisterResource_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipGraphicsUnregisterResource.resource = (hipGraphicsResource_t)resource; \ +}; +// hipHccModuleLaunchKernel[('hipFunction_t', 'f'), ('unsigned int', 'globalWorkSizeX'), ('unsigned int', 'globalWorkSizeY'), ('unsigned int', 'globalWorkSizeZ'), ('unsigned int', 'blockDimX'), ('unsigned int', 'blockDimY'), ('unsigned int', 'blockDimZ'), ('size_t', 'sharedMemBytes'), ('hipStream_t', 'hStream'), ('void**', 'kernelParams'), ('void**', 'extra'), ('hipEvent_t', 'startEvent'), ('hipEvent_t', 'stopEvent')] +#define INIT_hipHccModuleLaunchKernel_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipHccModuleLaunchKernel.f = (hipFunction_t)f; \ + cb_data.args.hipHccModuleLaunchKernel.globalWorkSizeX = (unsigned int)globalWorkSizeX; \ + cb_data.args.hipHccModuleLaunchKernel.globalWorkSizeY = (unsigned int)globalWorkSizeY; \ + cb_data.args.hipHccModuleLaunchKernel.globalWorkSizeZ = (unsigned int)globalWorkSizeZ; \ + cb_data.args.hipHccModuleLaunchKernel.blockDimX = (unsigned int)blockDimX; \ + cb_data.args.hipHccModuleLaunchKernel.blockDimY = (unsigned int)blockDimY; \ + cb_data.args.hipHccModuleLaunchKernel.blockDimZ = (unsigned int)blockDimZ; \ + cb_data.args.hipHccModuleLaunchKernel.sharedMemBytes = (size_t)sharedMemBytes; \ + cb_data.args.hipHccModuleLaunchKernel.hStream = (hipStream_t)hStream; \ + cb_data.args.hipHccModuleLaunchKernel.kernelParams = (void**)kernelParams; \ + cb_data.args.hipHccModuleLaunchKernel.extra = (void**)extra; \ + cb_data.args.hipHccModuleLaunchKernel.startEvent = (hipEvent_t)startEvent; \ + cb_data.args.hipHccModuleLaunchKernel.stopEvent = (hipEvent_t)stopEvent; \ +}; +// hipHostAlloc[('void**', 'ptr'), ('size_t', 'size'), ('unsigned int', 'flags')] +#define INIT_hipHostAlloc_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipHostAlloc.ptr = (void**)ptr; \ + cb_data.args.hipHostAlloc.size = (size_t)sizeBytes; \ + cb_data.args.hipHostAlloc.flags = (unsigned int)flags; \ +}; +// hipHostFree[('void*', 'ptr')] +#define INIT_hipHostFree_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipHostFree.ptr = (void*)ptr; \ +}; +// hipHostGetDevicePointer[('void**', 'devPtr'), ('void*', 'hstPtr'), ('unsigned int', 'flags')] +#define INIT_hipHostGetDevicePointer_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipHostGetDevicePointer.devPtr = (void**)devicePointer; \ + cb_data.args.hipHostGetDevicePointer.hstPtr = (void*)hostPointer; \ + cb_data.args.hipHostGetDevicePointer.flags = (unsigned int)flags; \ +}; +// hipHostGetFlags[('unsigned int*', 'flagsPtr'), ('void*', 'hostPtr')] +#define INIT_hipHostGetFlags_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipHostGetFlags.flagsPtr = (unsigned int*)flagsPtr; \ + cb_data.args.hipHostGetFlags.hostPtr = (void*)hostPtr; \ +}; +// hipHostMalloc[('void**', 'ptr'), ('size_t', 'size'), ('unsigned int', 'flags')] +#define INIT_hipHostMalloc_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipHostMalloc.ptr = (void**)ptr; \ + cb_data.args.hipHostMalloc.size = (size_t)sizeBytes; \ + cb_data.args.hipHostMalloc.flags = (unsigned int)flags; \ +}; +// hipHostRegister[('void*', 'hostPtr'), ('size_t', 'sizeBytes'), ('unsigned int', 'flags')] +#define INIT_hipHostRegister_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipHostRegister.hostPtr = (void*)hostPtr; \ + cb_data.args.hipHostRegister.sizeBytes = (size_t)sizeBytes; \ + cb_data.args.hipHostRegister.flags = (unsigned int)flags; \ +}; +// hipHostUnregister[('void*', 'hostPtr')] +#define INIT_hipHostUnregister_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipHostUnregister.hostPtr = (void*)hostPtr; \ +}; +// hipImportExternalMemory[('hipExternalMemory_t*', 'extMem_out'), ('const hipExternalMemoryHandleDesc*', 'memHandleDesc')] +#define INIT_hipImportExternalMemory_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipImportExternalMemory.extMem_out = (hipExternalMemory_t*)extMem_out; \ + cb_data.args.hipImportExternalMemory.memHandleDesc = (const hipExternalMemoryHandleDesc*)memHandleDesc; \ +}; +// hipImportExternalSemaphore[('hipExternalSemaphore_t*', 'extSem_out'), ('const hipExternalSemaphoreHandleDesc*', 'semHandleDesc')] +#define INIT_hipImportExternalSemaphore_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipImportExternalSemaphore.extSem_out = (hipExternalSemaphore_t*)extSem_out; \ + cb_data.args.hipImportExternalSemaphore.semHandleDesc = (const hipExternalSemaphoreHandleDesc*)semHandleDesc; \ +}; +// hipInit[('unsigned int', 'flags')] +#define INIT_hipInit_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipInit.flags = (unsigned int)flags; \ +}; +// hipIpcCloseMemHandle[('void*', 'devPtr')] +#define INIT_hipIpcCloseMemHandle_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipIpcCloseMemHandle.devPtr = (void*)dev_ptr; \ +}; +// hipIpcGetEventHandle[('hipIpcEventHandle_t*', 'handle'), ('hipEvent_t', 'event')] +#define INIT_hipIpcGetEventHandle_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipIpcGetEventHandle.handle = (hipIpcEventHandle_t*)handle; \ + cb_data.args.hipIpcGetEventHandle.event = (hipEvent_t)event; \ +}; +// hipIpcGetMemHandle[('hipIpcMemHandle_t*', 'handle'), ('void*', 'devPtr')] +#define INIT_hipIpcGetMemHandle_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipIpcGetMemHandle.handle = (hipIpcMemHandle_t*)handle; \ + cb_data.args.hipIpcGetMemHandle.devPtr = (void*)dev_ptr; \ +}; +// hipIpcOpenEventHandle[('hipEvent_t*', 'event'), ('hipIpcEventHandle_t', 'handle')] +#define INIT_hipIpcOpenEventHandle_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipIpcOpenEventHandle.event = (hipEvent_t*)event; \ + cb_data.args.hipIpcOpenEventHandle.handle = (hipIpcEventHandle_t)handle; \ +}; +// hipIpcOpenMemHandle[('void**', 'devPtr'), ('hipIpcMemHandle_t', 'handle'), ('unsigned int', 'flags')] +#define INIT_hipIpcOpenMemHandle_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipIpcOpenMemHandle.devPtr = (void**)dev_ptr; \ + cb_data.args.hipIpcOpenMemHandle.handle = (hipIpcMemHandle_t)handle; \ + cb_data.args.hipIpcOpenMemHandle.flags = (unsigned int)flags; \ +}; +// hipLaunchByPtr[('const void*', 'hostFunction')] +#define INIT_hipLaunchByPtr_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipLaunchByPtr.hostFunction = (const void*)hostFunction; \ +}; +// hipLaunchCooperativeKernel[('const void*', 'f'), ('dim3', 'gridDim'), ('dim3', 'blockDimX'), ('void**', 'kernelParams'), ('unsigned int', 'sharedMemBytes'), ('hipStream_t', 'stream')] +#define INIT_hipLaunchCooperativeKernel_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipLaunchCooperativeKernel.f = (const void*)f; \ + cb_data.args.hipLaunchCooperativeKernel.gridDim = (dim3)gridDim; \ + cb_data.args.hipLaunchCooperativeKernel.blockDimX = (dim3)blockDim; \ + cb_data.args.hipLaunchCooperativeKernel.kernelParams = (void**)kernelParams; \ + cb_data.args.hipLaunchCooperativeKernel.sharedMemBytes = (unsigned int)sharedMemBytes; \ + cb_data.args.hipLaunchCooperativeKernel.stream = (hipStream_t)hStream; \ +}; +// hipLaunchCooperativeKernelMultiDevice[('hipLaunchParams*', 'launchParamsList'), ('int', 'numDevices'), ('unsigned int', 'flags')] +#define INIT_hipLaunchCooperativeKernelMultiDevice_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipLaunchCooperativeKernelMultiDevice.launchParamsList = (hipLaunchParams*)launchParamsList; \ + cb_data.args.hipLaunchCooperativeKernelMultiDevice.numDevices = (int)numDevices; \ + cb_data.args.hipLaunchCooperativeKernelMultiDevice.flags = (unsigned int)flags; \ +}; +// hipLaunchHostFunc[('hipStream_t', 'stream'), ('hipHostFn_t', 'fn'), ('void*', 'userData')] +#define INIT_hipLaunchHostFunc_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipLaunchHostFunc.stream = (hipStream_t)stream; \ + cb_data.args.hipLaunchHostFunc.fn = (hipHostFn_t)fn; \ + cb_data.args.hipLaunchHostFunc.userData = (void*)userData; \ +}; +// hipLaunchKernel[('const void*', 'function_address'), ('dim3', 'numBlocks'), ('dim3', 'dimBlocks'), ('void**', 'args'), ('size_t', 'sharedMemBytes'), ('hipStream_t', 'stream')] +#define INIT_hipLaunchKernel_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipLaunchKernel.function_address = (const void*)hostFunction; \ + cb_data.args.hipLaunchKernel.numBlocks = (dim3)gridDim; \ + cb_data.args.hipLaunchKernel.dimBlocks = (dim3)blockDim; \ + cb_data.args.hipLaunchKernel.args = (void**)args; \ + cb_data.args.hipLaunchKernel.sharedMemBytes = (size_t)sharedMemBytes; \ + cb_data.args.hipLaunchKernel.stream = (hipStream_t)stream; \ +}; +// hipMalloc[('void**', 'ptr'), ('size_t', 'size')] +#define INIT_hipMalloc_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMalloc.ptr = (void**)ptr; \ + cb_data.args.hipMalloc.size = (size_t)sizeBytes; \ +}; +// hipMalloc3D[('hipPitchedPtr*', 'pitchedDevPtr'), ('hipExtent', 'extent')] +#define INIT_hipMalloc3D_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMalloc3D.pitchedDevPtr = (hipPitchedPtr*)pitchedDevPtr; \ + cb_data.args.hipMalloc3D.extent = (hipExtent)extent; \ +}; +// hipMalloc3DArray[('hipArray_t*', 'array'), ('const hipChannelFormatDesc*', 'desc'), ('hipExtent', 'extent'), ('unsigned int', 'flags')] +#define INIT_hipMalloc3DArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMalloc3DArray.array = (hipArray_t*)array; \ + cb_data.args.hipMalloc3DArray.desc = (const hipChannelFormatDesc*)desc; \ + cb_data.args.hipMalloc3DArray.extent = (hipExtent)extent; \ + cb_data.args.hipMalloc3DArray.flags = (unsigned int)flags; \ +}; +// hipMallocArray[('hipArray_t*', 'array'), ('const hipChannelFormatDesc*', 'desc'), ('size_t', 'width'), ('size_t', 'height'), ('unsigned int', 'flags')] +#define INIT_hipMallocArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMallocArray.array = (hipArray_t*)array; \ + cb_data.args.hipMallocArray.desc = (const hipChannelFormatDesc*)desc; \ + cb_data.args.hipMallocArray.width = (size_t)width; \ + cb_data.args.hipMallocArray.height = (size_t)height; \ + cb_data.args.hipMallocArray.flags = (unsigned int)flags; \ +}; +// hipMallocAsync[('void**', 'dev_ptr'), ('size_t', 'size'), ('hipStream_t', 'stream')] +#define INIT_hipMallocAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMallocAsync.dev_ptr = (void**)dev_ptr; \ + cb_data.args.hipMallocAsync.size = (size_t)size; \ + cb_data.args.hipMallocAsync.stream = (hipStream_t)stream; \ +}; +// hipMallocFromPoolAsync[('void**', 'dev_ptr'), ('size_t', 'size'), ('hipMemPool_t', 'mem_pool'), ('hipStream_t', 'stream')] +#define INIT_hipMallocFromPoolAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMallocFromPoolAsync.dev_ptr = (void**)dev_ptr; \ + cb_data.args.hipMallocFromPoolAsync.size = (size_t)size; \ + cb_data.args.hipMallocFromPoolAsync.mem_pool = (hipMemPool_t)mem_pool; \ + cb_data.args.hipMallocFromPoolAsync.stream = (hipStream_t)stream; \ +}; +// hipMallocHost[('void**', 'ptr'), ('size_t', 'size')] +#define INIT_hipMallocHost_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMallocHost.ptr = (void**)ptr; \ + cb_data.args.hipMallocHost.size = (size_t)size; \ +}; +// hipMallocManaged[('void**', 'dev_ptr'), ('size_t', 'size'), ('unsigned int', 'flags')] +#define INIT_hipMallocManaged_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMallocManaged.dev_ptr = (void**)dev_ptr; \ + cb_data.args.hipMallocManaged.size = (size_t)size; \ + cb_data.args.hipMallocManaged.flags = (unsigned int)flags; \ +}; +// hipMallocMipmappedArray[('hipMipmappedArray_t*', 'mipmappedArray'), ('const hipChannelFormatDesc*', 'desc'), ('hipExtent', 'extent'), ('unsigned int', 'numLevels'), ('unsigned int', 'flags')] +#define INIT_hipMallocMipmappedArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMallocMipmappedArray.mipmappedArray = (hipMipmappedArray_t*)mipmappedArray; \ + cb_data.args.hipMallocMipmappedArray.desc = (const hipChannelFormatDesc*)desc; \ + cb_data.args.hipMallocMipmappedArray.extent = (hipExtent)extent; \ + cb_data.args.hipMallocMipmappedArray.numLevels = (unsigned int)numLevels; \ + cb_data.args.hipMallocMipmappedArray.flags = (unsigned int)flags; \ +}; +// hipMallocPitch[('void**', 'ptr'), ('size_t*', 'pitch'), ('size_t', 'width'), ('size_t', 'height')] +#define INIT_hipMallocPitch_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMallocPitch.ptr = (void**)ptr; \ + cb_data.args.hipMallocPitch.pitch = (size_t*)pitch; \ + cb_data.args.hipMallocPitch.width = (size_t)width; \ + cb_data.args.hipMallocPitch.height = (size_t)height; \ +}; +// hipMemAddressFree[('void*', 'devPtr'), ('size_t', 'size')] +#define INIT_hipMemAddressFree_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemAddressFree.devPtr = (void*)devPtr; \ + cb_data.args.hipMemAddressFree.size = (size_t)size; \ +}; +// hipMemAddressReserve[('void**', 'ptr'), ('size_t', 'size'), ('size_t', 'alignment'), ('void*', 'addr'), ('unsigned long long', 'flags')] +#define INIT_hipMemAddressReserve_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemAddressReserve.ptr = (void**)ptr; \ + cb_data.args.hipMemAddressReserve.size = (size_t)size; \ + cb_data.args.hipMemAddressReserve.alignment = (size_t)alignment; \ + cb_data.args.hipMemAddressReserve.addr = (void*)addr; \ + cb_data.args.hipMemAddressReserve.flags = (unsigned long long)flags; \ +}; +// hipMemAdvise[('const void*', 'dev_ptr'), ('size_t', 'count'), ('hipMemoryAdvise', 'advice'), ('int', 'device')] +#define INIT_hipMemAdvise_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemAdvise.dev_ptr = (const void*)dev_ptr; \ + cb_data.args.hipMemAdvise.count = (size_t)count; \ + cb_data.args.hipMemAdvise.advice = (hipMemoryAdvise)advice; \ + cb_data.args.hipMemAdvise.device = (int)device; \ +}; +// hipMemAllocHost[('void**', 'ptr'), ('size_t', 'size')] +#define INIT_hipMemAllocHost_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemAllocHost.ptr = (void**)ptr; \ + cb_data.args.hipMemAllocHost.size = (size_t)size; \ +}; +// hipMemAllocPitch[('hipDeviceptr_t*', 'dptr'), ('size_t*', 'pitch'), ('size_t', 'widthInBytes'), ('size_t', 'height'), ('unsigned int', 'elementSizeBytes')] +#define INIT_hipMemAllocPitch_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemAllocPitch.dptr = (hipDeviceptr_t*)dptr; \ + cb_data.args.hipMemAllocPitch.pitch = (size_t*)pitch; \ + cb_data.args.hipMemAllocPitch.widthInBytes = (size_t)widthInBytes; \ + cb_data.args.hipMemAllocPitch.height = (size_t)height; \ + cb_data.args.hipMemAllocPitch.elementSizeBytes = (unsigned int)elementSizeBytes; \ +}; +// hipMemCreate[('hipMemGenericAllocationHandle_t*', 'handle'), ('size_t', 'size'), ('const hipMemAllocationProp*', 'prop'), ('unsigned long long', 'flags')] +#define INIT_hipMemCreate_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemCreate.handle = (hipMemGenericAllocationHandle_t*)handle; \ + cb_data.args.hipMemCreate.size = (size_t)size; \ + cb_data.args.hipMemCreate.prop = (const hipMemAllocationProp*)prop; \ + cb_data.args.hipMemCreate.flags = (unsigned long long)flags; \ +}; +// hipMemExportToShareableHandle[('void*', 'shareableHandle'), ('hipMemGenericAllocationHandle_t', 'handle'), ('hipMemAllocationHandleType', 'handleType'), ('unsigned long long', 'flags')] +#define INIT_hipMemExportToShareableHandle_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemExportToShareableHandle.shareableHandle = (void*)shareableHandle; \ + cb_data.args.hipMemExportToShareableHandle.handle = (hipMemGenericAllocationHandle_t)handle; \ + cb_data.args.hipMemExportToShareableHandle.handleType = (hipMemAllocationHandleType)handleType; \ + cb_data.args.hipMemExportToShareableHandle.flags = (unsigned long long)flags; \ +}; +// hipMemGetAccess[('unsigned long long*', 'flags'), ('const hipMemLocation*', 'location'), ('void*', 'ptr')] +#define INIT_hipMemGetAccess_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemGetAccess.flags = (unsigned long long*)flags; \ + cb_data.args.hipMemGetAccess.location = (const hipMemLocation*)location; \ + cb_data.args.hipMemGetAccess.ptr = (void*)ptr; \ +}; +// hipMemGetAddressRange[('hipDeviceptr_t*', 'pbase'), ('size_t*', 'psize'), ('hipDeviceptr_t', 'dptr')] +#define INIT_hipMemGetAddressRange_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemGetAddressRange.pbase = (hipDeviceptr_t*)pbase; \ + cb_data.args.hipMemGetAddressRange.psize = (size_t*)psize; \ + cb_data.args.hipMemGetAddressRange.dptr = (hipDeviceptr_t)dptr; \ +}; +// hipMemGetAllocationGranularity[('size_t*', 'granularity'), ('const hipMemAllocationProp*', 'prop'), ('hipMemAllocationGranularity_flags', 'option')] +#define INIT_hipMemGetAllocationGranularity_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemGetAllocationGranularity.granularity = (size_t*)granularity; \ + cb_data.args.hipMemGetAllocationGranularity.prop = (const hipMemAllocationProp*)prop; \ + cb_data.args.hipMemGetAllocationGranularity.option = (hipMemAllocationGranularity_flags)option; \ +}; +// hipMemGetAllocationPropertiesFromHandle[('hipMemAllocationProp*', 'prop'), ('hipMemGenericAllocationHandle_t', 'handle')] +#define INIT_hipMemGetAllocationPropertiesFromHandle_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemGetAllocationPropertiesFromHandle.prop = (hipMemAllocationProp*)prop; \ + cb_data.args.hipMemGetAllocationPropertiesFromHandle.handle = (hipMemGenericAllocationHandle_t)handle; \ +}; +// hipMemGetInfo[('size_t*', 'free'), ('size_t*', 'total')] +#define INIT_hipMemGetInfo_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemGetInfo.free = (size_t*)free; \ + cb_data.args.hipMemGetInfo.total = (size_t*)total; \ +}; +// hipMemImportFromShareableHandle[('hipMemGenericAllocationHandle_t*', 'handle'), ('void*', 'osHandle'), ('hipMemAllocationHandleType', 'shHandleType')] +#define INIT_hipMemImportFromShareableHandle_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemImportFromShareableHandle.handle = (hipMemGenericAllocationHandle_t*)handle; \ + cb_data.args.hipMemImportFromShareableHandle.osHandle = (void*)osHandle; \ + cb_data.args.hipMemImportFromShareableHandle.shHandleType = (hipMemAllocationHandleType)shHandleType; \ +}; +// hipMemMap[('void*', 'ptr'), ('size_t', 'size'), ('size_t', 'offset'), ('hipMemGenericAllocationHandle_t', 'handle'), ('unsigned long long', 'flags')] +#define INIT_hipMemMap_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemMap.ptr = (void*)ptr; \ + cb_data.args.hipMemMap.size = (size_t)size; \ + cb_data.args.hipMemMap.offset = (size_t)offset; \ + cb_data.args.hipMemMap.handle = (hipMemGenericAllocationHandle_t)handle; \ + cb_data.args.hipMemMap.flags = (unsigned long long)flags; \ +}; +// hipMemMapArrayAsync[('hipArrayMapInfo*', 'mapInfoList'), ('unsigned int', 'count'), ('hipStream_t', 'stream')] +#define INIT_hipMemMapArrayAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemMapArrayAsync.mapInfoList = (hipArrayMapInfo*)mapInfoList; \ + cb_data.args.hipMemMapArrayAsync.count = (unsigned int)count; \ + cb_data.args.hipMemMapArrayAsync.stream = (hipStream_t)stream; \ +}; +// hipMemPoolCreate[('hipMemPool_t*', 'mem_pool'), ('const hipMemPoolProps*', 'pool_props')] +#define INIT_hipMemPoolCreate_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemPoolCreate.mem_pool = (hipMemPool_t*)mem_pool; \ + cb_data.args.hipMemPoolCreate.pool_props = (const hipMemPoolProps*)pool_props; \ +}; +// hipMemPoolDestroy[('hipMemPool_t', 'mem_pool')] +#define INIT_hipMemPoolDestroy_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemPoolDestroy.mem_pool = (hipMemPool_t)mem_pool; \ +}; +// hipMemPoolExportPointer[('hipMemPoolPtrExportData*', 'export_data'), ('void*', 'dev_ptr')] +#define INIT_hipMemPoolExportPointer_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemPoolExportPointer.export_data = (hipMemPoolPtrExportData*)export_data; \ + cb_data.args.hipMemPoolExportPointer.dev_ptr = (void*)ptr; \ +}; +// hipMemPoolExportToShareableHandle[('void*', 'shared_handle'), ('hipMemPool_t', 'mem_pool'), ('hipMemAllocationHandleType', 'handle_type'), ('unsigned int', 'flags')] +#define INIT_hipMemPoolExportToShareableHandle_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemPoolExportToShareableHandle.shared_handle = (void*)shared_handle; \ + cb_data.args.hipMemPoolExportToShareableHandle.mem_pool = (hipMemPool_t)mem_pool; \ + cb_data.args.hipMemPoolExportToShareableHandle.handle_type = (hipMemAllocationHandleType)handle_type; \ + cb_data.args.hipMemPoolExportToShareableHandle.flags = (unsigned int)flags; \ +}; +// hipMemPoolGetAccess[('hipMemAccessFlags*', 'flags'), ('hipMemPool_t', 'mem_pool'), ('hipMemLocation*', 'location')] +#define INIT_hipMemPoolGetAccess_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemPoolGetAccess.flags = (hipMemAccessFlags*)flags; \ + cb_data.args.hipMemPoolGetAccess.mem_pool = (hipMemPool_t)mem_pool; \ + cb_data.args.hipMemPoolGetAccess.location = (hipMemLocation*)location; \ +}; +// hipMemPoolGetAttribute[('hipMemPool_t', 'mem_pool'), ('hipMemPoolAttr', 'attr'), ('void*', 'value')] +#define INIT_hipMemPoolGetAttribute_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemPoolGetAttribute.mem_pool = (hipMemPool_t)mem_pool; \ + cb_data.args.hipMemPoolGetAttribute.attr = (hipMemPoolAttr)attr; \ + cb_data.args.hipMemPoolGetAttribute.value = (void*)value; \ +}; +// hipMemPoolImportFromShareableHandle[('hipMemPool_t*', 'mem_pool'), ('void*', 'shared_handle'), ('hipMemAllocationHandleType', 'handle_type'), ('unsigned int', 'flags')] +#define INIT_hipMemPoolImportFromShareableHandle_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemPoolImportFromShareableHandle.mem_pool = (hipMemPool_t*)mem_pool; \ + cb_data.args.hipMemPoolImportFromShareableHandle.shared_handle = (void*)shared_handle; \ + cb_data.args.hipMemPoolImportFromShareableHandle.handle_type = (hipMemAllocationHandleType)handle_type; \ + cb_data.args.hipMemPoolImportFromShareableHandle.flags = (unsigned int)flags; \ +}; +// hipMemPoolImportPointer[('void**', 'dev_ptr'), ('hipMemPool_t', 'mem_pool'), ('hipMemPoolPtrExportData*', 'export_data')] +#define INIT_hipMemPoolImportPointer_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemPoolImportPointer.dev_ptr = (void**)ptr; \ + cb_data.args.hipMemPoolImportPointer.mem_pool = (hipMemPool_t)mem_pool; \ + cb_data.args.hipMemPoolImportPointer.export_data = (hipMemPoolPtrExportData*)export_data; \ +}; +// hipMemPoolSetAccess[('hipMemPool_t', 'mem_pool'), ('const hipMemAccessDesc*', 'desc_list'), ('size_t', 'count')] +#define INIT_hipMemPoolSetAccess_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemPoolSetAccess.mem_pool = (hipMemPool_t)mem_pool; \ + cb_data.args.hipMemPoolSetAccess.desc_list = (const hipMemAccessDesc*)desc_list; \ + cb_data.args.hipMemPoolSetAccess.count = (size_t)count; \ +}; +// hipMemPoolSetAttribute[('hipMemPool_t', 'mem_pool'), ('hipMemPoolAttr', 'attr'), ('void*', 'value')] +#define INIT_hipMemPoolSetAttribute_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemPoolSetAttribute.mem_pool = (hipMemPool_t)mem_pool; \ + cb_data.args.hipMemPoolSetAttribute.attr = (hipMemPoolAttr)attr; \ + cb_data.args.hipMemPoolSetAttribute.value = (void*)value; \ +}; +// hipMemPoolTrimTo[('hipMemPool_t', 'mem_pool'), ('size_t', 'min_bytes_to_hold')] +#define INIT_hipMemPoolTrimTo_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemPoolTrimTo.mem_pool = (hipMemPool_t)mem_pool; \ + cb_data.args.hipMemPoolTrimTo.min_bytes_to_hold = (size_t)min_bytes_to_hold; \ +}; +// hipMemPrefetchAsync[('const void*', 'dev_ptr'), ('size_t', 'count'), ('int', 'device'), ('hipStream_t', 'stream')] +#define INIT_hipMemPrefetchAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemPrefetchAsync.dev_ptr = (const void*)dev_ptr; \ + cb_data.args.hipMemPrefetchAsync.count = (size_t)count; \ + cb_data.args.hipMemPrefetchAsync.device = (int)device; \ + cb_data.args.hipMemPrefetchAsync.stream = (hipStream_t)stream; \ +}; +// hipMemPtrGetInfo[('void*', 'ptr'), ('size_t*', 'size')] +#define INIT_hipMemPtrGetInfo_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemPtrGetInfo.ptr = (void*)ptr; \ + cb_data.args.hipMemPtrGetInfo.size = (size_t*)size; \ +}; +// hipMemRangeGetAttribute[('void*', 'data'), ('size_t', 'data_size'), ('hipMemRangeAttribute', 'attribute'), ('const void*', 'dev_ptr'), ('size_t', 'count')] +#define INIT_hipMemRangeGetAttribute_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemRangeGetAttribute.data = (void*)data; \ + cb_data.args.hipMemRangeGetAttribute.data_size = (size_t)data_size; \ + cb_data.args.hipMemRangeGetAttribute.attribute = (hipMemRangeAttribute)attribute; \ + cb_data.args.hipMemRangeGetAttribute.dev_ptr = (const void*)dev_ptr; \ + cb_data.args.hipMemRangeGetAttribute.count = (size_t)count; \ +}; +// hipMemRangeGetAttributes[('void**', 'data'), ('size_t*', 'data_sizes'), ('hipMemRangeAttribute*', 'attributes'), ('size_t', 'num_attributes'), ('const void*', 'dev_ptr'), ('size_t', 'count')] +#define INIT_hipMemRangeGetAttributes_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemRangeGetAttributes.data = (void**)data; \ + cb_data.args.hipMemRangeGetAttributes.data_sizes = (size_t*)data_sizes; \ + cb_data.args.hipMemRangeGetAttributes.attributes = (hipMemRangeAttribute*)attributes; \ + cb_data.args.hipMemRangeGetAttributes.num_attributes = (size_t)num_attributes; \ + cb_data.args.hipMemRangeGetAttributes.dev_ptr = (const void*)dev_ptr; \ + cb_data.args.hipMemRangeGetAttributes.count = (size_t)count; \ +}; +// hipMemRelease[('hipMemGenericAllocationHandle_t', 'handle')] +#define INIT_hipMemRelease_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemRelease.handle = (hipMemGenericAllocationHandle_t)handle; \ +}; +// hipMemRetainAllocationHandle[('hipMemGenericAllocationHandle_t*', 'handle'), ('void*', 'addr')] +#define INIT_hipMemRetainAllocationHandle_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemRetainAllocationHandle.handle = (hipMemGenericAllocationHandle_t*)handle; \ + cb_data.args.hipMemRetainAllocationHandle.addr = (void*)addr; \ +}; +// hipMemSetAccess[('void*', 'ptr'), ('size_t', 'size'), ('const hipMemAccessDesc*', 'desc'), ('size_t', 'count')] +#define INIT_hipMemSetAccess_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemSetAccess.ptr = (void*)ptr; \ + cb_data.args.hipMemSetAccess.size = (size_t)size; \ + cb_data.args.hipMemSetAccess.desc = (const hipMemAccessDesc*)desc; \ + cb_data.args.hipMemSetAccess.count = (size_t)count; \ +}; +// hipMemUnmap[('void*', 'ptr'), ('size_t', 'size')] +#define INIT_hipMemUnmap_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemUnmap.ptr = (void*)ptr; \ + cb_data.args.hipMemUnmap.size = (size_t)size; \ +}; +// hipMemcpy[('void*', 'dst'), ('const void*', 'src'), ('size_t', 'sizeBytes'), ('hipMemcpyKind', 'kind')] +#define INIT_hipMemcpy_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpy.dst = (void*)dst; \ + cb_data.args.hipMemcpy.src = (const void*)src; \ + cb_data.args.hipMemcpy.sizeBytes = (size_t)sizeBytes; \ + cb_data.args.hipMemcpy.kind = (hipMemcpyKind)kind; \ +}; +// hipMemcpy2D[('void*', 'dst'), ('size_t', 'dpitch'), ('const void*', 'src'), ('size_t', 'spitch'), ('size_t', 'width'), ('size_t', 'height'), ('hipMemcpyKind', 'kind')] +#define INIT_hipMemcpy2D_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpy2D.dst = (void*)dst; \ + cb_data.args.hipMemcpy2D.dpitch = (size_t)dpitch; \ + cb_data.args.hipMemcpy2D.src = (const void*)src; \ + cb_data.args.hipMemcpy2D.spitch = (size_t)spitch; \ + cb_data.args.hipMemcpy2D.width = (size_t)width; \ + cb_data.args.hipMemcpy2D.height = (size_t)height; \ + cb_data.args.hipMemcpy2D.kind = (hipMemcpyKind)kind; \ +}; +// hipMemcpy2DArrayToArray[('hipArray_t', 'dst'), ('size_t', 'wOffsetDst'), ('size_t', 'hOffsetDst'), ('hipArray_const_t', 'src'), ('size_t', 'wOffsetSrc'), ('size_t', 'hOffsetSrc'), ('size_t', 'width'), ('size_t', 'height'), ('hipMemcpyKind', 'kind')] +#define INIT_hipMemcpy2DArrayToArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpy2DArrayToArray.dst = (hipArray_t)dst; \ + cb_data.args.hipMemcpy2DArrayToArray.wOffsetDst = (size_t)wOffsetDst; \ + cb_data.args.hipMemcpy2DArrayToArray.hOffsetDst = (size_t)hOffsetDst; \ + cb_data.args.hipMemcpy2DArrayToArray.src = (hipArray_const_t)src; \ + cb_data.args.hipMemcpy2DArrayToArray.wOffsetSrc = (size_t)wOffsetSrc; \ + cb_data.args.hipMemcpy2DArrayToArray.hOffsetSrc = (size_t)hOffsetSrc; \ + cb_data.args.hipMemcpy2DArrayToArray.width = (size_t)width; \ + cb_data.args.hipMemcpy2DArrayToArray.height = (size_t)height; \ + cb_data.args.hipMemcpy2DArrayToArray.kind = (hipMemcpyKind)kind; \ +}; +// hipMemcpy2DAsync[('void*', 'dst'), ('size_t', 'dpitch'), ('const void*', 'src'), ('size_t', 'spitch'), ('size_t', 'width'), ('size_t', 'height'), ('hipMemcpyKind', 'kind'), ('hipStream_t', 'stream')] +#define INIT_hipMemcpy2DAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpy2DAsync.dst = (void*)dst; \ + cb_data.args.hipMemcpy2DAsync.dpitch = (size_t)dpitch; \ + cb_data.args.hipMemcpy2DAsync.src = (const void*)src; \ + cb_data.args.hipMemcpy2DAsync.spitch = (size_t)spitch; \ + cb_data.args.hipMemcpy2DAsync.width = (size_t)width; \ + cb_data.args.hipMemcpy2DAsync.height = (size_t)height; \ + cb_data.args.hipMemcpy2DAsync.kind = (hipMemcpyKind)kind; \ + cb_data.args.hipMemcpy2DAsync.stream = (hipStream_t)stream; \ +}; +// hipMemcpy2DFromArray[('void*', 'dst'), ('size_t', 'dpitch'), ('hipArray_const_t', 'src'), ('size_t', 'wOffset'), ('size_t', 'hOffset'), ('size_t', 'width'), ('size_t', 'height'), ('hipMemcpyKind', 'kind')] +#define INIT_hipMemcpy2DFromArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpy2DFromArray.dst = (void*)dst; \ + cb_data.args.hipMemcpy2DFromArray.dpitch = (size_t)dpitch; \ + cb_data.args.hipMemcpy2DFromArray.src = (hipArray_const_t)src; \ + cb_data.args.hipMemcpy2DFromArray.wOffset = (size_t)wOffsetSrc; \ + cb_data.args.hipMemcpy2DFromArray.hOffset = (size_t)hOffset; \ + cb_data.args.hipMemcpy2DFromArray.width = (size_t)width; \ + cb_data.args.hipMemcpy2DFromArray.height = (size_t)height; \ + cb_data.args.hipMemcpy2DFromArray.kind = (hipMemcpyKind)kind; \ +}; +// hipMemcpy2DFromArrayAsync[('void*', 'dst'), ('size_t', 'dpitch'), ('hipArray_const_t', 'src'), ('size_t', 'wOffset'), ('size_t', 'hOffset'), ('size_t', 'width'), ('size_t', 'height'), ('hipMemcpyKind', 'kind'), ('hipStream_t', 'stream')] +#define INIT_hipMemcpy2DFromArrayAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpy2DFromArrayAsync.dst = (void*)dst; \ + cb_data.args.hipMemcpy2DFromArrayAsync.dpitch = (size_t)dpitch; \ + cb_data.args.hipMemcpy2DFromArrayAsync.src = (hipArray_const_t)src; \ + cb_data.args.hipMemcpy2DFromArrayAsync.wOffset = (size_t)wOffsetSrc; \ + cb_data.args.hipMemcpy2DFromArrayAsync.hOffset = (size_t)hOffsetSrc; \ + cb_data.args.hipMemcpy2DFromArrayAsync.width = (size_t)width; \ + cb_data.args.hipMemcpy2DFromArrayAsync.height = (size_t)height; \ + cb_data.args.hipMemcpy2DFromArrayAsync.kind = (hipMemcpyKind)kind; \ + cb_data.args.hipMemcpy2DFromArrayAsync.stream = (hipStream_t)stream; \ +}; +// hipMemcpy2DToArray[('hipArray_t', 'dst'), ('size_t', 'wOffset'), ('size_t', 'hOffset'), ('const void*', 'src'), ('size_t', 'spitch'), ('size_t', 'width'), ('size_t', 'height'), ('hipMemcpyKind', 'kind')] +#define INIT_hipMemcpy2DToArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpy2DToArray.dst = (hipArray_t)dst; \ + cb_data.args.hipMemcpy2DToArray.wOffset = (size_t)wOffset; \ + cb_data.args.hipMemcpy2DToArray.hOffset = (size_t)hOffset; \ + cb_data.args.hipMemcpy2DToArray.src = (const void*)src; \ + cb_data.args.hipMemcpy2DToArray.spitch = (size_t)spitch; \ + cb_data.args.hipMemcpy2DToArray.width = (size_t)width; \ + cb_data.args.hipMemcpy2DToArray.height = (size_t)height; \ + cb_data.args.hipMemcpy2DToArray.kind = (hipMemcpyKind)kind; \ +}; +// hipMemcpy2DToArrayAsync[('hipArray_t', 'dst'), ('size_t', 'wOffset'), ('size_t', 'hOffset'), ('const void*', 'src'), ('size_t', 'spitch'), ('size_t', 'width'), ('size_t', 'height'), ('hipMemcpyKind', 'kind'), ('hipStream_t', 'stream')] +#define INIT_hipMemcpy2DToArrayAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpy2DToArrayAsync.dst = (hipArray_t)dst; \ + cb_data.args.hipMemcpy2DToArrayAsync.wOffset = (size_t)wOffset; \ + cb_data.args.hipMemcpy2DToArrayAsync.hOffset = (size_t)hOffset; \ + cb_data.args.hipMemcpy2DToArrayAsync.src = (const void*)src; \ + cb_data.args.hipMemcpy2DToArrayAsync.spitch = (size_t)spitch; \ + cb_data.args.hipMemcpy2DToArrayAsync.width = (size_t)width; \ + cb_data.args.hipMemcpy2DToArrayAsync.height = (size_t)height; \ + cb_data.args.hipMemcpy2DToArrayAsync.kind = (hipMemcpyKind)kind; \ + cb_data.args.hipMemcpy2DToArrayAsync.stream = (hipStream_t)stream; \ +}; +// hipMemcpy3D[('const hipMemcpy3DParms*', 'p')] +#define INIT_hipMemcpy3D_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpy3D.p = (const hipMemcpy3DParms*)p; \ +}; +// hipMemcpy3DAsync[('const hipMemcpy3DParms*', 'p'), ('hipStream_t', 'stream')] +#define INIT_hipMemcpy3DAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpy3DAsync.p = (const hipMemcpy3DParms*)p; \ + cb_data.args.hipMemcpy3DAsync.stream = (hipStream_t)stream; \ +}; +// hipMemcpyAsync[('void*', 'dst'), ('const void*', 'src'), ('size_t', 'sizeBytes'), ('hipMemcpyKind', 'kind'), ('hipStream_t', 'stream')] +#define INIT_hipMemcpyAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyAsync.dst = (void*)dst; \ + cb_data.args.hipMemcpyAsync.src = (const void*)src; \ + cb_data.args.hipMemcpyAsync.sizeBytes = (size_t)sizeBytes; \ + cb_data.args.hipMemcpyAsync.kind = (hipMemcpyKind)kind; \ + cb_data.args.hipMemcpyAsync.stream = (hipStream_t)stream; \ +}; +// hipMemcpyAtoA[('hipArray_t', 'dstArray'), ('size_t', 'dstOffset'), ('hipArray_t', 'srcArray'), ('size_t', 'srcOffset'), ('size_t', 'ByteCount')] +#define INIT_hipMemcpyAtoA_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyAtoA.dstArray = (hipArray_t)dstArray; \ + cb_data.args.hipMemcpyAtoA.dstOffset = (size_t)dstOffset; \ + cb_data.args.hipMemcpyAtoA.srcArray = (hipArray_t)srcArray; \ + cb_data.args.hipMemcpyAtoA.srcOffset = (size_t)srcOffset; \ + cb_data.args.hipMemcpyAtoA.ByteCount = (size_t)ByteCount; \ +}; +// hipMemcpyAtoD[('hipDeviceptr_t', 'dstDevice'), ('hipArray_t', 'srcArray'), ('size_t', 'srcOffset'), ('size_t', 'ByteCount')] +#define INIT_hipMemcpyAtoD_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyAtoD.dstDevice = (hipDeviceptr_t)dstDevice; \ + cb_data.args.hipMemcpyAtoD.srcArray = (hipArray_t)srcArray; \ + cb_data.args.hipMemcpyAtoD.srcOffset = (size_t)srcOffset; \ + cb_data.args.hipMemcpyAtoD.ByteCount = (size_t)ByteCount; \ +}; +// hipMemcpyAtoH[('void*', 'dst'), ('hipArray_t', 'srcArray'), ('size_t', 'srcOffset'), ('size_t', 'count')] +#define INIT_hipMemcpyAtoH_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyAtoH.dst = (void*)dstHost; \ + cb_data.args.hipMemcpyAtoH.srcArray = (hipArray_t)srcArray; \ + cb_data.args.hipMemcpyAtoH.srcOffset = (size_t)srcOffset; \ + cb_data.args.hipMemcpyAtoH.count = (size_t)ByteCount; \ +}; +// hipMemcpyAtoHAsync[('void*', 'dstHost'), ('hipArray_t', 'srcArray'), ('size_t', 'srcOffset'), ('size_t', 'ByteCount'), ('hipStream_t', 'stream')] +#define INIT_hipMemcpyAtoHAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyAtoHAsync.dstHost = (void*)dstHost; \ + cb_data.args.hipMemcpyAtoHAsync.srcArray = (hipArray_t)srcArray; \ + cb_data.args.hipMemcpyAtoHAsync.srcOffset = (size_t)srcOffset; \ + cb_data.args.hipMemcpyAtoHAsync.ByteCount = (size_t)ByteCount; \ + cb_data.args.hipMemcpyAtoHAsync.stream = (hipStream_t)stream; \ +}; +// hipMemcpyDtoA[('hipArray_t', 'dstArray'), ('size_t', 'dstOffset'), ('hipDeviceptr_t', 'srcDevice'), ('size_t', 'ByteCount')] +#define INIT_hipMemcpyDtoA_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyDtoA.dstArray = (hipArray_t)dstArray; \ + cb_data.args.hipMemcpyDtoA.dstOffset = (size_t)dstOffset; \ + cb_data.args.hipMemcpyDtoA.srcDevice = (hipDeviceptr_t)srcDevice; \ + cb_data.args.hipMemcpyDtoA.ByteCount = (size_t)ByteCount; \ +}; +// hipMemcpyDtoD[('hipDeviceptr_t', 'dst'), ('hipDeviceptr_t', 'src'), ('size_t', 'sizeBytes')] +#define INIT_hipMemcpyDtoD_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyDtoD.dst = (hipDeviceptr_t)dstDevice; \ + cb_data.args.hipMemcpyDtoD.src = (hipDeviceptr_t)srcDevice; \ + cb_data.args.hipMemcpyDtoD.sizeBytes = (size_t)ByteCount; \ +}; +// hipMemcpyDtoDAsync[('hipDeviceptr_t', 'dst'), ('hipDeviceptr_t', 'src'), ('size_t', 'sizeBytes'), ('hipStream_t', 'stream')] +#define INIT_hipMemcpyDtoDAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyDtoDAsync.dst = (hipDeviceptr_t)dstDevice; \ + cb_data.args.hipMemcpyDtoDAsync.src = (hipDeviceptr_t)srcDevice; \ + cb_data.args.hipMemcpyDtoDAsync.sizeBytes = (size_t)ByteCount; \ + cb_data.args.hipMemcpyDtoDAsync.stream = (hipStream_t)stream; \ +}; +// hipMemcpyDtoH[('void*', 'dst'), ('hipDeviceptr_t', 'src'), ('size_t', 'sizeBytes')] +#define INIT_hipMemcpyDtoH_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyDtoH.dst = (void*)dstHost; \ + cb_data.args.hipMemcpyDtoH.src = (hipDeviceptr_t)srcDevice; \ + cb_data.args.hipMemcpyDtoH.sizeBytes = (size_t)ByteCount; \ +}; +// hipMemcpyDtoHAsync[('void*', 'dst'), ('hipDeviceptr_t', 'src'), ('size_t', 'sizeBytes'), ('hipStream_t', 'stream')] +#define INIT_hipMemcpyDtoHAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyDtoHAsync.dst = (void*)dstHost; \ + cb_data.args.hipMemcpyDtoHAsync.src = (hipDeviceptr_t)srcDevice; \ + cb_data.args.hipMemcpyDtoHAsync.sizeBytes = (size_t)ByteCount; \ + cb_data.args.hipMemcpyDtoHAsync.stream = (hipStream_t)stream; \ +}; +// hipMemcpyFromArray[('void*', 'dst'), ('hipArray_const_t', 'srcArray'), ('size_t', 'wOffset'), ('size_t', 'hOffset'), ('size_t', 'count'), ('hipMemcpyKind', 'kind')] +#define INIT_hipMemcpyFromArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyFromArray.dst = (void*)dst; \ + cb_data.args.hipMemcpyFromArray.srcArray = (hipArray_const_t)src; \ + cb_data.args.hipMemcpyFromArray.wOffset = (size_t)wOffsetSrc; \ + cb_data.args.hipMemcpyFromArray.hOffset = (size_t)hOffset; \ + cb_data.args.hipMemcpyFromArray.count = (size_t)count; \ + cb_data.args.hipMemcpyFromArray.kind = (hipMemcpyKind)kind; \ +}; +// hipMemcpyFromSymbol[('void*', 'dst'), ('const void*', 'symbol'), ('size_t', 'sizeBytes'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] +#define INIT_hipMemcpyFromSymbol_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyFromSymbol.dst = (void*)dst; \ + cb_data.args.hipMemcpyFromSymbol.symbol = (const void*)symbol; \ + cb_data.args.hipMemcpyFromSymbol.sizeBytes = (size_t)sizeBytes; \ + cb_data.args.hipMemcpyFromSymbol.offset = (size_t)offset; \ + cb_data.args.hipMemcpyFromSymbol.kind = (hipMemcpyKind)kind; \ +}; +// hipMemcpyFromSymbolAsync[('void*', 'dst'), ('const void*', 'symbol'), ('size_t', 'sizeBytes'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind'), ('hipStream_t', 'stream')] +#define INIT_hipMemcpyFromSymbolAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyFromSymbolAsync.dst = (void*)dst; \ + cb_data.args.hipMemcpyFromSymbolAsync.symbol = (const void*)symbol; \ + cb_data.args.hipMemcpyFromSymbolAsync.sizeBytes = (size_t)sizeBytes; \ + cb_data.args.hipMemcpyFromSymbolAsync.offset = (size_t)offset; \ + cb_data.args.hipMemcpyFromSymbolAsync.kind = (hipMemcpyKind)kind; \ + cb_data.args.hipMemcpyFromSymbolAsync.stream = (hipStream_t)stream; \ +}; +// hipMemcpyHtoA[('hipArray_t', 'dstArray'), ('size_t', 'dstOffset'), ('const void*', 'srcHost'), ('size_t', 'count')] +#define INIT_hipMemcpyHtoA_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyHtoA.dstArray = (hipArray_t)dstArray; \ + cb_data.args.hipMemcpyHtoA.dstOffset = (size_t)dstOffset; \ + cb_data.args.hipMemcpyHtoA.srcHost = (const void*)srcHost; \ + cb_data.args.hipMemcpyHtoA.count = (size_t)ByteCount; \ +}; +// hipMemcpyHtoAAsync[('hipArray_t', 'dstArray'), ('size_t', 'dstOffset'), ('const void*', 'srcHost'), ('size_t', 'ByteCount'), ('hipStream_t', 'stream')] +#define INIT_hipMemcpyHtoAAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyHtoAAsync.dstArray = (hipArray_t)dstArray; \ + cb_data.args.hipMemcpyHtoAAsync.dstOffset = (size_t)dstOffset; \ + cb_data.args.hipMemcpyHtoAAsync.srcHost = (const void*)srcHost; \ + cb_data.args.hipMemcpyHtoAAsync.ByteCount = (size_t)ByteCount; \ + cb_data.args.hipMemcpyHtoAAsync.stream = (hipStream_t)stream; \ +}; +// hipMemcpyHtoD[('hipDeviceptr_t', 'dst'), ('void*', 'src'), ('size_t', 'sizeBytes')] +#define INIT_hipMemcpyHtoD_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyHtoD.dst = (hipDeviceptr_t)dstDevice; \ + cb_data.args.hipMemcpyHtoD.src = (void*)srcHost; \ + cb_data.args.hipMemcpyHtoD.sizeBytes = (size_t)ByteCount; \ +}; +// hipMemcpyHtoDAsync[('hipDeviceptr_t', 'dst'), ('void*', 'src'), ('size_t', 'sizeBytes'), ('hipStream_t', 'stream')] +#define INIT_hipMemcpyHtoDAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyHtoDAsync.dst = (hipDeviceptr_t)dstDevice; \ + cb_data.args.hipMemcpyHtoDAsync.src = (void*)srcHost; \ + cb_data.args.hipMemcpyHtoDAsync.sizeBytes = (size_t)ByteCount; \ + cb_data.args.hipMemcpyHtoDAsync.stream = (hipStream_t)stream; \ +}; +// hipMemcpyParam2D[('const hip_Memcpy2D*', 'pCopy')] +#define INIT_hipMemcpyParam2D_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyParam2D.pCopy = (const hip_Memcpy2D*)pCopy; \ +}; +// hipMemcpyParam2DAsync[('const hip_Memcpy2D*', 'pCopy'), ('hipStream_t', 'stream')] +#define INIT_hipMemcpyParam2DAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyParam2DAsync.pCopy = (const hip_Memcpy2D*)pCopy; \ + cb_data.args.hipMemcpyParam2DAsync.stream = (hipStream_t)stream; \ +}; +// hipMemcpyPeer[('void*', 'dst'), ('int', 'dstDeviceId'), ('const void*', 'src'), ('int', 'srcDeviceId'), ('size_t', 'sizeBytes')] +#define INIT_hipMemcpyPeer_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyPeer.dst = (void*)dst; \ + cb_data.args.hipMemcpyPeer.dstDeviceId = (int)dstDevice; \ + cb_data.args.hipMemcpyPeer.src = (const void*)src; \ + cb_data.args.hipMemcpyPeer.srcDeviceId = (int)srcDevice; \ + cb_data.args.hipMemcpyPeer.sizeBytes = (size_t)sizeBytes; \ +}; +// hipMemcpyPeerAsync[('void*', 'dst'), ('int', 'dstDeviceId'), ('const void*', 'src'), ('int', 'srcDevice'), ('size_t', 'sizeBytes'), ('hipStream_t', 'stream')] +#define INIT_hipMemcpyPeerAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyPeerAsync.dst = (void*)dst; \ + cb_data.args.hipMemcpyPeerAsync.dstDeviceId = (int)dstDevice; \ + cb_data.args.hipMemcpyPeerAsync.src = (const void*)src; \ + cb_data.args.hipMemcpyPeerAsync.srcDevice = (int)srcDevice; \ + cb_data.args.hipMemcpyPeerAsync.sizeBytes = (size_t)sizeBytes; \ + cb_data.args.hipMemcpyPeerAsync.stream = (hipStream_t)stream; \ +}; +// hipMemcpyToArray[('hipArray_t', 'dst'), ('size_t', 'wOffset'), ('size_t', 'hOffset'), ('const void*', 'src'), ('size_t', 'count'), ('hipMemcpyKind', 'kind')] +#define INIT_hipMemcpyToArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyToArray.dst = (hipArray_t)dst; \ + cb_data.args.hipMemcpyToArray.wOffset = (size_t)wOffset; \ + cb_data.args.hipMemcpyToArray.hOffset = (size_t)hOffset; \ + cb_data.args.hipMemcpyToArray.src = (const void*)src; \ + cb_data.args.hipMemcpyToArray.count = (size_t)count; \ + cb_data.args.hipMemcpyToArray.kind = (hipMemcpyKind)kind; \ +}; +// hipMemcpyToSymbol[('const void*', 'symbol'), ('const void*', 'src'), ('size_t', 'sizeBytes'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] +#define INIT_hipMemcpyToSymbol_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyToSymbol.symbol = (const void*)symbol; \ + cb_data.args.hipMemcpyToSymbol.src = (const void*)src; \ + cb_data.args.hipMemcpyToSymbol.sizeBytes = (size_t)sizeBytes; \ + cb_data.args.hipMemcpyToSymbol.offset = (size_t)offset; \ + cb_data.args.hipMemcpyToSymbol.kind = (hipMemcpyKind)kind; \ +}; +// hipMemcpyToSymbolAsync[('const void*', 'symbol'), ('const void*', 'src'), ('size_t', 'sizeBytes'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind'), ('hipStream_t', 'stream')] +#define INIT_hipMemcpyToSymbolAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyToSymbolAsync.symbol = (const void*)symbol; \ + cb_data.args.hipMemcpyToSymbolAsync.src = (const void*)src; \ + cb_data.args.hipMemcpyToSymbolAsync.sizeBytes = (size_t)sizeBytes; \ + cb_data.args.hipMemcpyToSymbolAsync.offset = (size_t)offset; \ + cb_data.args.hipMemcpyToSymbolAsync.kind = (hipMemcpyKind)kind; \ + cb_data.args.hipMemcpyToSymbolAsync.stream = (hipStream_t)stream; \ +}; +// hipMemcpyWithStream[('void*', 'dst'), ('const void*', 'src'), ('size_t', 'sizeBytes'), ('hipMemcpyKind', 'kind'), ('hipStream_t', 'stream')] +#define INIT_hipMemcpyWithStream_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemcpyWithStream.dst = (void*)dst; \ + cb_data.args.hipMemcpyWithStream.src = (const void*)src; \ + cb_data.args.hipMemcpyWithStream.sizeBytes = (size_t)sizeBytes; \ + cb_data.args.hipMemcpyWithStream.kind = (hipMemcpyKind)kind; \ + cb_data.args.hipMemcpyWithStream.stream = (hipStream_t)stream; \ +}; +// hipMemset[('void*', 'dst'), ('int', 'value'), ('size_t', 'sizeBytes')] +#define INIT_hipMemset_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemset.dst = (void*)dst; \ + cb_data.args.hipMemset.value = (int)value; \ + cb_data.args.hipMemset.sizeBytes = (size_t)sizeBytes; \ +}; +// hipMemset2D[('void*', 'dst'), ('size_t', 'pitch'), ('int', 'value'), ('size_t', 'width'), ('size_t', 'height')] +#define INIT_hipMemset2D_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemset2D.dst = (void*)dst; \ + cb_data.args.hipMemset2D.pitch = (size_t)pitch; \ + cb_data.args.hipMemset2D.value = (int)value; \ + cb_data.args.hipMemset2D.width = (size_t)width; \ + cb_data.args.hipMemset2D.height = (size_t)height; \ +}; +// hipMemset2DAsync[('void*', 'dst'), ('size_t', 'pitch'), ('int', 'value'), ('size_t', 'width'), ('size_t', 'height'), ('hipStream_t', 'stream')] +#define INIT_hipMemset2DAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemset2DAsync.dst = (void*)dst; \ + cb_data.args.hipMemset2DAsync.pitch = (size_t)pitch; \ + cb_data.args.hipMemset2DAsync.value = (int)value; \ + cb_data.args.hipMemset2DAsync.width = (size_t)width; \ + cb_data.args.hipMemset2DAsync.height = (size_t)height; \ + cb_data.args.hipMemset2DAsync.stream = (hipStream_t)stream; \ +}; +// hipMemset3D[('hipPitchedPtr', 'pitchedDevPtr'), ('int', 'value'), ('hipExtent', 'extent')] +#define INIT_hipMemset3D_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemset3D.pitchedDevPtr = (hipPitchedPtr)pitchedDevPtr; \ + cb_data.args.hipMemset3D.value = (int)value; \ + cb_data.args.hipMemset3D.extent = (hipExtent)extent; \ +}; +// hipMemset3DAsync[('hipPitchedPtr', 'pitchedDevPtr'), ('int', 'value'), ('hipExtent', 'extent'), ('hipStream_t', 'stream')] +#define INIT_hipMemset3DAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemset3DAsync.pitchedDevPtr = (hipPitchedPtr)pitchedDevPtr; \ + cb_data.args.hipMemset3DAsync.value = (int)value; \ + cb_data.args.hipMemset3DAsync.extent = (hipExtent)extent; \ + cb_data.args.hipMemset3DAsync.stream = (hipStream_t)stream; \ +}; +// hipMemsetAsync[('void*', 'dst'), ('int', 'value'), ('size_t', 'sizeBytes'), ('hipStream_t', 'stream')] +#define INIT_hipMemsetAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemsetAsync.dst = (void*)dst; \ + cb_data.args.hipMemsetAsync.value = (int)value; \ + cb_data.args.hipMemsetAsync.sizeBytes = (size_t)sizeBytes; \ + cb_data.args.hipMemsetAsync.stream = (hipStream_t)stream; \ +}; +// hipMemsetD16[('hipDeviceptr_t', 'dest'), ('unsigned short', 'value'), ('size_t', 'count')] +#define INIT_hipMemsetD16_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemsetD16.dest = (hipDeviceptr_t)dst; \ + cb_data.args.hipMemsetD16.value = (unsigned short)value; \ + cb_data.args.hipMemsetD16.count = (size_t)count; \ +}; +// hipMemsetD16Async[('hipDeviceptr_t', 'dest'), ('unsigned short', 'value'), ('size_t', 'count'), ('hipStream_t', 'stream')] +#define INIT_hipMemsetD16Async_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemsetD16Async.dest = (hipDeviceptr_t)dst; \ + cb_data.args.hipMemsetD16Async.value = (unsigned short)value; \ + cb_data.args.hipMemsetD16Async.count = (size_t)count; \ + cb_data.args.hipMemsetD16Async.stream = (hipStream_t)stream; \ +}; +// hipMemsetD32[('hipDeviceptr_t', 'dest'), ('int', 'value'), ('size_t', 'count')] +#define INIT_hipMemsetD32_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemsetD32.dest = (hipDeviceptr_t)dst; \ + cb_data.args.hipMemsetD32.value = (int)value; \ + cb_data.args.hipMemsetD32.count = (size_t)count; \ +}; +// hipMemsetD32Async[('hipDeviceptr_t', 'dst'), ('int', 'value'), ('size_t', 'count'), ('hipStream_t', 'stream')] +#define INIT_hipMemsetD32Async_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemsetD32Async.dst = (hipDeviceptr_t)dst; \ + cb_data.args.hipMemsetD32Async.value = (int)value; \ + cb_data.args.hipMemsetD32Async.count = (size_t)count; \ + cb_data.args.hipMemsetD32Async.stream = (hipStream_t)stream; \ +}; +// hipMemsetD8[('hipDeviceptr_t', 'dest'), ('unsigned char', 'value'), ('size_t', 'count')] +#define INIT_hipMemsetD8_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemsetD8.dest = (hipDeviceptr_t)dst; \ + cb_data.args.hipMemsetD8.value = (unsigned char)value; \ + cb_data.args.hipMemsetD8.count = (size_t)count; \ +}; +// hipMemsetD8Async[('hipDeviceptr_t', 'dest'), ('unsigned char', 'value'), ('size_t', 'count'), ('hipStream_t', 'stream')] +#define INIT_hipMemsetD8Async_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMemsetD8Async.dest = (hipDeviceptr_t)dst; \ + cb_data.args.hipMemsetD8Async.value = (unsigned char)value; \ + cb_data.args.hipMemsetD8Async.count = (size_t)count; \ + cb_data.args.hipMemsetD8Async.stream = (hipStream_t)stream; \ +}; +// hipMipmappedArrayCreate[('hipMipmappedArray_t*', 'pHandle'), ('HIP_ARRAY3D_DESCRIPTOR*', 'pMipmappedArrayDesc'), ('unsigned int', 'numMipmapLevels')] +#define INIT_hipMipmappedArrayCreate_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMipmappedArrayCreate.pHandle = (hipMipmappedArray_t*)mipmapped_array_pptr; \ + cb_data.args.hipMipmappedArrayCreate.pMipmappedArrayDesc = (HIP_ARRAY3D_DESCRIPTOR*)mipmapped_array_desc_ptr; \ + cb_data.args.hipMipmappedArrayCreate.numMipmapLevels = (unsigned int)num_mipmap_levels; \ +}; +// hipMipmappedArrayDestroy[('hipMipmappedArray_t', 'hMipmappedArray')] +#define INIT_hipMipmappedArrayDestroy_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMipmappedArrayDestroy.hMipmappedArray = (hipMipmappedArray_t)mipmapped_array_ptr; \ +}; +// hipMipmappedArrayGetLevel[('hipArray_t*', 'pLevelArray'), ('hipMipmappedArray_t', 'hMipMappedArray'), ('unsigned int', 'level')] +#define INIT_hipMipmappedArrayGetLevel_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipMipmappedArrayGetLevel.pLevelArray = (hipArray_t*)level_array_pptr; \ + cb_data.args.hipMipmappedArrayGetLevel.hMipMappedArray = (hipMipmappedArray_t)mipmapped_array_ptr; \ + cb_data.args.hipMipmappedArrayGetLevel.level = (unsigned int)mip_level; \ +}; +// hipModuleGetFunction[('hipFunction_t*', 'function'), ('hipModule_t', 'module'), ('const char*', 'kname')] +#define INIT_hipModuleGetFunction_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipModuleGetFunction.function = (hipFunction_t*)hfunc; \ + cb_data.args.hipModuleGetFunction.module = (hipModule_t)hmod; \ + cb_data.args.hipModuleGetFunction.kname = (name) ? strdup(name) : NULL; \ +}; +// hipModuleGetGlobal[('hipDeviceptr_t*', 'dptr'), ('size_t*', 'bytes'), ('hipModule_t', 'hmod'), ('const char*', 'name')] +#define INIT_hipModuleGetGlobal_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipModuleGetGlobal.dptr = (hipDeviceptr_t*)dptr; \ + cb_data.args.hipModuleGetGlobal.bytes = (size_t*)bytes; \ + cb_data.args.hipModuleGetGlobal.hmod = (hipModule_t)hmod; \ + cb_data.args.hipModuleGetGlobal.name = (name) ? strdup(name) : NULL; \ +}; +// hipModuleGetTexRef[('textureReference**', 'texRef'), ('hipModule_t', 'hmod'), ('const char*', 'name')] +#define INIT_hipModuleGetTexRef_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipModuleGetTexRef.texRef = (textureReference**)texRef; \ + cb_data.args.hipModuleGetTexRef.hmod = (hipModule_t)hmod; \ + cb_data.args.hipModuleGetTexRef.name = (name) ? strdup(name) : NULL; \ +}; +// 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')] +#define INIT_hipModuleLaunchCooperativeKernel_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipModuleLaunchCooperativeKernel.f = (hipFunction_t)f; \ + cb_data.args.hipModuleLaunchCooperativeKernel.gridDimX = (unsigned int)gridDimX; \ + cb_data.args.hipModuleLaunchCooperativeKernel.gridDimY = (unsigned int)gridDimY; \ + cb_data.args.hipModuleLaunchCooperativeKernel.gridDimZ = (unsigned int)gridDimZ; \ + cb_data.args.hipModuleLaunchCooperativeKernel.blockDimX = (unsigned int)blockDimX; \ + cb_data.args.hipModuleLaunchCooperativeKernel.blockDimY = (unsigned int)blockDimY; \ + cb_data.args.hipModuleLaunchCooperativeKernel.blockDimZ = (unsigned int)blockDimZ; \ + cb_data.args.hipModuleLaunchCooperativeKernel.sharedMemBytes = (unsigned int)sharedMemBytes; \ + cb_data.args.hipModuleLaunchCooperativeKernel.stream = (hipStream_t)stream; \ + cb_data.args.hipModuleLaunchCooperativeKernel.kernelParams = (void**)kernelParams; \ +}; +// hipModuleLaunchCooperativeKernelMultiDevice[('hipFunctionLaunchParams*', 'launchParamsList'), ('unsigned int', 'numDevices'), ('unsigned int', 'flags')] +#define INIT_hipModuleLaunchCooperativeKernelMultiDevice_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipModuleLaunchCooperativeKernelMultiDevice.launchParamsList = (hipFunctionLaunchParams*)launchParamsList; \ + cb_data.args.hipModuleLaunchCooperativeKernelMultiDevice.numDevices = (unsigned int)numDevices; \ + cb_data.args.hipModuleLaunchCooperativeKernelMultiDevice.flags = (unsigned int)flags; \ +}; +// 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')] +#define INIT_hipModuleLaunchKernel_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipModuleLaunchKernel.f = (hipFunction_t)f; \ + cb_data.args.hipModuleLaunchKernel.gridDimX = (unsigned int)gridDimX; \ + cb_data.args.hipModuleLaunchKernel.gridDimY = (unsigned int)gridDimY; \ + cb_data.args.hipModuleLaunchKernel.gridDimZ = (unsigned int)gridDimZ; \ + cb_data.args.hipModuleLaunchKernel.blockDimX = (unsigned int)blockDimX; \ + cb_data.args.hipModuleLaunchKernel.blockDimY = (unsigned int)blockDimY; \ + cb_data.args.hipModuleLaunchKernel.blockDimZ = (unsigned int)blockDimZ; \ + cb_data.args.hipModuleLaunchKernel.sharedMemBytes = (unsigned int)sharedMemBytes; \ + cb_data.args.hipModuleLaunchKernel.stream = (hipStream_t)hStream; \ + cb_data.args.hipModuleLaunchKernel.kernelParams = (void**)kernelParams; \ + cb_data.args.hipModuleLaunchKernel.extra = (void**)extra; \ +}; +// hipModuleLoad[('hipModule_t*', 'module'), ('const char*', 'fname')] +#define INIT_hipModuleLoad_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipModuleLoad.module = (hipModule_t*)module; \ + cb_data.args.hipModuleLoad.fname = (fname) ? strdup(fname) : NULL; \ +}; +// hipModuleLoadData[('hipModule_t*', 'module'), ('const void*', 'image')] +#define INIT_hipModuleLoadData_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipModuleLoadData.module = (hipModule_t*)module; \ + cb_data.args.hipModuleLoadData.image = (const void*)image; \ +}; +// hipModuleLoadDataEx[('hipModule_t*', 'module'), ('const void*', 'image'), ('unsigned int', 'numOptions'), ('hipJitOption*', 'options'), ('void**', 'optionsValues')] +#define INIT_hipModuleLoadDataEx_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipModuleLoadDataEx.module = (hipModule_t*)module; \ + cb_data.args.hipModuleLoadDataEx.image = (const void*)image; \ + cb_data.args.hipModuleLoadDataEx.numOptions = (unsigned int)numOptions; \ + cb_data.args.hipModuleLoadDataEx.options = (hipJitOption*)options; \ + cb_data.args.hipModuleLoadDataEx.optionsValues = (void**)optionsValues; \ +}; +// hipModuleOccupancyMaxActiveBlocksPerMultiprocessor[('int*', 'numBlocks'), ('hipFunction_t', 'f'), ('int', 'blockSize'), ('size_t', 'dynSharedMemPerBlk')] +#define INIT_hipModuleOccupancyMaxActiveBlocksPerMultiprocessor_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessor.numBlocks = (int*)numBlocks; \ + cb_data.args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessor.f = (hipFunction_t)f; \ + cb_data.args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessor.blockSize = (int)blockSize; \ + cb_data.args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessor.dynSharedMemPerBlk = (size_t)dynSharedMemPerBlk; \ +}; +// hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags[('int*', 'numBlocks'), ('hipFunction_t', 'f'), ('int', 'blockSize'), ('size_t', 'dynSharedMemPerBlk'), ('unsigned int', 'flags')] +#define INIT_hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.numBlocks = (int*)numBlocks; \ + cb_data.args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.f = (hipFunction_t)f; \ + cb_data.args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.blockSize = (int)blockSize; \ + cb_data.args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.dynSharedMemPerBlk = (size_t)dynSharedMemPerBlk; \ + cb_data.args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.flags = (unsigned int)flags; \ +}; +// hipModuleOccupancyMaxPotentialBlockSize[('int*', 'gridSize'), ('int*', 'blockSize'), ('hipFunction_t', 'f'), ('size_t', 'dynSharedMemPerBlk'), ('int', 'blockSizeLimit')] +#define INIT_hipModuleOccupancyMaxPotentialBlockSize_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipModuleOccupancyMaxPotentialBlockSize.gridSize = (int*)gridSize; \ + cb_data.args.hipModuleOccupancyMaxPotentialBlockSize.blockSize = (int*)blockSize; \ + cb_data.args.hipModuleOccupancyMaxPotentialBlockSize.f = (hipFunction_t)f; \ + cb_data.args.hipModuleOccupancyMaxPotentialBlockSize.dynSharedMemPerBlk = (size_t)dynSharedMemPerBlk; \ + cb_data.args.hipModuleOccupancyMaxPotentialBlockSize.blockSizeLimit = (int)blockSizeLimit; \ +}; +// hipModuleOccupancyMaxPotentialBlockSizeWithFlags[('int*', 'gridSize'), ('int*', 'blockSize'), ('hipFunction_t', 'f'), ('size_t', 'dynSharedMemPerBlk'), ('int', 'blockSizeLimit'), ('unsigned int', 'flags')] +#define INIT_hipModuleOccupancyMaxPotentialBlockSizeWithFlags_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.gridSize = (int*)gridSize; \ + cb_data.args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.blockSize = (int*)blockSize; \ + cb_data.args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.f = (hipFunction_t)f; \ + cb_data.args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.dynSharedMemPerBlk = (size_t)dynSharedMemPerBlk; \ + cb_data.args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.blockSizeLimit = (int)blockSizeLimit; \ + cb_data.args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.flags = (unsigned int)flags; \ +}; +// hipModuleUnload[('hipModule_t', 'module')] +#define INIT_hipModuleUnload_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipModuleUnload.module = (hipModule_t)hmod; \ +}; +// hipOccupancyMaxActiveBlocksPerMultiprocessor[('int*', 'numBlocks'), ('const void*', 'f'), ('int', 'blockSize'), ('size_t', 'dynamicSMemSize')] +#define INIT_hipOccupancyMaxActiveBlocksPerMultiprocessor_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipOccupancyMaxActiveBlocksPerMultiprocessor.numBlocks = (int*)numBlocks; \ + cb_data.args.hipOccupancyMaxActiveBlocksPerMultiprocessor.f = (const void*)f; \ + cb_data.args.hipOccupancyMaxActiveBlocksPerMultiprocessor.blockSize = (int)blockSize; \ + cb_data.args.hipOccupancyMaxActiveBlocksPerMultiprocessor.dynamicSMemSize = (size_t)dynamicSMemSize; \ +}; +// hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags[('int*', 'numBlocks'), ('const void*', 'f'), ('int', 'blockSize'), ('size_t', 'dynamicSMemSize'), ('unsigned int', 'flags')] +#define INIT_hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.numBlocks = (int*)numBlocks; \ + cb_data.args.hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.f = (const void*)f; \ + cb_data.args.hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.blockSize = (int)blockSize; \ + cb_data.args.hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.dynamicSMemSize = (size_t)dynamicSMemSize; \ + cb_data.args.hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.flags = (unsigned int)flags; \ +}; +// hipOccupancyMaxPotentialBlockSize[('int*', 'gridSize'), ('int*', 'blockSize'), ('const void*', 'f'), ('size_t', 'dynSharedMemPerBlk'), ('int', 'blockSizeLimit')] +#define INIT_hipOccupancyMaxPotentialBlockSize_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipOccupancyMaxPotentialBlockSize.gridSize = (int*)gridSize; \ + cb_data.args.hipOccupancyMaxPotentialBlockSize.blockSize = (int*)blockSize; \ + cb_data.args.hipOccupancyMaxPotentialBlockSize.f = (const void*)f; \ + cb_data.args.hipOccupancyMaxPotentialBlockSize.dynSharedMemPerBlk = (size_t)dynSharedMemPerBlk; \ + cb_data.args.hipOccupancyMaxPotentialBlockSize.blockSizeLimit = (int)blockSizeLimit; \ +}; +// hipPeekAtLastError[] +#define INIT_hipPeekAtLastError_CB_ARGS_DATA(cb_data) { \ +}; +// hipPointerGetAttribute[('void*', 'data'), ('hipPointer_attribute', 'attribute'), ('hipDeviceptr_t', 'ptr')] +#define INIT_hipPointerGetAttribute_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipPointerGetAttribute.data = (void*)data; \ + cb_data.args.hipPointerGetAttribute.attribute = (hipPointer_attribute)attribute; \ + cb_data.args.hipPointerGetAttribute.ptr = (hipDeviceptr_t)ptr; \ +}; +// hipPointerGetAttributes[('hipPointerAttribute_t*', 'attributes'), ('const void*', 'ptr')] +#define INIT_hipPointerGetAttributes_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipPointerGetAttributes.attributes = (hipPointerAttribute_t*)attributes; \ + cb_data.args.hipPointerGetAttributes.ptr = (const void*)ptr; \ +}; +// hipPointerSetAttribute[('const void*', 'value'), ('hipPointer_attribute', 'attribute'), ('hipDeviceptr_t', 'ptr')] +#define INIT_hipPointerSetAttribute_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipPointerSetAttribute.value = (const void*)value; \ + cb_data.args.hipPointerSetAttribute.attribute = (hipPointer_attribute)attribute; \ + cb_data.args.hipPointerSetAttribute.ptr = (hipDeviceptr_t)ptr; \ +}; +// hipProfilerStart[] +#define INIT_hipProfilerStart_CB_ARGS_DATA(cb_data) { \ +}; +// hipProfilerStop[] +#define INIT_hipProfilerStop_CB_ARGS_DATA(cb_data) { \ +}; +// hipRuntimeGetVersion[('int*', 'runtimeVersion')] +#define INIT_hipRuntimeGetVersion_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipRuntimeGetVersion.runtimeVersion = (int*)runtimeVersion; \ +}; +// hipSetDevice[('int', 'deviceId')] +#define INIT_hipSetDevice_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipSetDevice.deviceId = (int)device; \ +}; +// hipSetDeviceFlags[('unsigned int', 'flags')] +#define INIT_hipSetDeviceFlags_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipSetDeviceFlags.flags = (unsigned int)flags; \ +}; +// hipSetValidDevices[('int*', 'device_arr'), ('int', 'len')] +#define INIT_hipSetValidDevices_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipSetValidDevices.device_arr = (int*)device_arr; \ + cb_data.args.hipSetValidDevices.len = (int)len; \ +}; +// hipSetupArgument[('const void*', 'arg'), ('size_t', 'size'), ('size_t', 'offset')] +#define INIT_hipSetupArgument_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipSetupArgument.arg = (const void*)arg; \ + cb_data.args.hipSetupArgument.size = (size_t)size; \ + cb_data.args.hipSetupArgument.offset = (size_t)offset; \ +}; +// hipSignalExternalSemaphoresAsync[('const hipExternalSemaphore_t*', 'extSemArray'), ('const hipExternalSemaphoreSignalParams*', 'paramsArray'), ('unsigned int', 'numExtSems'), ('hipStream_t', 'stream')] +#define INIT_hipSignalExternalSemaphoresAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipSignalExternalSemaphoresAsync.extSemArray = (const hipExternalSemaphore_t*)extSemArray; \ + cb_data.args.hipSignalExternalSemaphoresAsync.paramsArray = (const hipExternalSemaphoreSignalParams*)paramsArray; \ + cb_data.args.hipSignalExternalSemaphoresAsync.numExtSems = (unsigned int)numExtSems; \ + cb_data.args.hipSignalExternalSemaphoresAsync.stream = (hipStream_t)stream; \ +}; +// hipStreamAddCallback[('hipStream_t', 'stream'), ('hipStreamCallback_t', 'callback'), ('void*', 'userData'), ('unsigned int', 'flags')] +#define INIT_hipStreamAddCallback_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamAddCallback.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamAddCallback.callback = (hipStreamCallback_t)callback; \ + cb_data.args.hipStreamAddCallback.userData = (void*)userData; \ + cb_data.args.hipStreamAddCallback.flags = (unsigned int)flags; \ +}; +// hipStreamAttachMemAsync[('hipStream_t', 'stream'), ('void*', 'dev_ptr'), ('size_t', 'length'), ('unsigned int', 'flags')] +#define INIT_hipStreamAttachMemAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamAttachMemAsync.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamAttachMemAsync.dev_ptr = (void*)dev_ptr; \ + cb_data.args.hipStreamAttachMemAsync.length = (size_t)length; \ + cb_data.args.hipStreamAttachMemAsync.flags = (unsigned int)flags; \ +}; +// hipStreamBeginCapture[('hipStream_t', 'stream'), ('hipStreamCaptureMode', 'mode')] +#define INIT_hipStreamBeginCapture_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamBeginCapture.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamBeginCapture.mode = (hipStreamCaptureMode)mode; \ +}; +// hipStreamBeginCaptureToGraph[('hipStream_t', 'stream'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'dependencies'), ('const hipGraphEdgeData*', 'dependencyData'), ('size_t', 'numDependencies'), ('hipStreamCaptureMode', 'mode')] +#define INIT_hipStreamBeginCaptureToGraph_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamBeginCaptureToGraph.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamBeginCaptureToGraph.graph = (hipGraph_t)graph; \ + cb_data.args.hipStreamBeginCaptureToGraph.dependencies = (const hipGraphNode_t*)dependencies; \ + cb_data.args.hipStreamBeginCaptureToGraph.dependencyData = (const hipGraphEdgeData*)dependencyData; \ + cb_data.args.hipStreamBeginCaptureToGraph.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipStreamBeginCaptureToGraph.mode = (hipStreamCaptureMode)mode; \ +}; +// hipStreamCreate[('hipStream_t*', 'stream')] +#define INIT_hipStreamCreate_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamCreate.stream = (hipStream_t*)stream; \ +}; +// hipStreamCreateWithFlags[('hipStream_t*', 'stream'), ('unsigned int', 'flags')] +#define INIT_hipStreamCreateWithFlags_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamCreateWithFlags.stream = (hipStream_t*)stream; \ + cb_data.args.hipStreamCreateWithFlags.flags = (unsigned int)flags; \ +}; +// hipStreamCreateWithPriority[('hipStream_t*', 'stream'), ('unsigned int', 'flags'), ('int', 'priority')] +#define INIT_hipStreamCreateWithPriority_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamCreateWithPriority.stream = (hipStream_t*)stream; \ + cb_data.args.hipStreamCreateWithPriority.flags = (unsigned int)flags; \ + cb_data.args.hipStreamCreateWithPriority.priority = (int)priority; \ +}; +// hipStreamDestroy[('hipStream_t', 'stream')] +#define INIT_hipStreamDestroy_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamDestroy.stream = (hipStream_t)stream; \ +}; +// hipStreamEndCapture[('hipStream_t', 'stream'), ('hipGraph_t*', 'pGraph')] +#define INIT_hipStreamEndCapture_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamEndCapture.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamEndCapture.pGraph = (hipGraph_t*)pGraph; \ +}; +// hipStreamGetCaptureInfo[('hipStream_t', 'stream'), ('hipStreamCaptureStatus*', 'pCaptureStatus'), ('unsigned long long*', 'pId')] +#define INIT_hipStreamGetCaptureInfo_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamGetCaptureInfo.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamGetCaptureInfo.pCaptureStatus = (hipStreamCaptureStatus*)pCaptureStatus; \ + cb_data.args.hipStreamGetCaptureInfo.pId = (unsigned long long*)pId; \ +}; +// hipStreamGetCaptureInfo_v2[('hipStream_t', 'stream'), ('hipStreamCaptureStatus*', 'captureStatus_out'), ('unsigned long long*', 'id_out'), ('hipGraph_t*', 'graph_out'), ('const hipGraphNode_t**', 'dependencies_out'), ('size_t*', 'numDependencies_out')] +#define INIT_hipStreamGetCaptureInfo_v2_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamGetCaptureInfo_v2.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamGetCaptureInfo_v2.captureStatus_out = (hipStreamCaptureStatus*)captureStatus_out; \ + cb_data.args.hipStreamGetCaptureInfo_v2.id_out = (unsigned long long*)id_out; \ + cb_data.args.hipStreamGetCaptureInfo_v2.graph_out = (hipGraph_t*)graph_out; \ + cb_data.args.hipStreamGetCaptureInfo_v2.dependencies_out = (const hipGraphNode_t**)dependencies_out; \ + cb_data.args.hipStreamGetCaptureInfo_v2.numDependencies_out = (size_t*)numDependencies_out; \ +}; +// hipStreamGetDevice[('hipStream_t', 'stream'), ('hipDevice_t*', 'device')] +#define INIT_hipStreamGetDevice_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamGetDevice.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamGetDevice.device = (hipDevice_t*)device; \ +}; +// hipStreamGetFlags[('hipStream_t', 'stream'), ('unsigned int*', 'flags')] +#define INIT_hipStreamGetFlags_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamGetFlags.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamGetFlags.flags = (unsigned int*)flags; \ +}; +// hipStreamGetPriority[('hipStream_t', 'stream'), ('int*', 'priority')] +#define INIT_hipStreamGetPriority_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamGetPriority.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamGetPriority.priority = (int*)priority; \ +}; +// hipStreamIsCapturing[('hipStream_t', 'stream'), ('hipStreamCaptureStatus*', 'pCaptureStatus')] +#define INIT_hipStreamIsCapturing_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamIsCapturing.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamIsCapturing.pCaptureStatus = (hipStreamCaptureStatus*)pCaptureStatus; \ +}; +// hipStreamQuery[('hipStream_t', 'stream')] +#define INIT_hipStreamQuery_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamQuery.stream = (hipStream_t)stream; \ +}; +// hipStreamSynchronize[('hipStream_t', 'stream')] +#define INIT_hipStreamSynchronize_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamSynchronize.stream = (hipStream_t)stream; \ +}; +// hipStreamUpdateCaptureDependencies[('hipStream_t', 'stream'), ('hipGraphNode_t*', 'dependencies'), ('size_t', 'numDependencies'), ('unsigned int', 'flags')] +#define INIT_hipStreamUpdateCaptureDependencies_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamUpdateCaptureDependencies.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamUpdateCaptureDependencies.dependencies = (hipGraphNode_t*)dependencies; \ + cb_data.args.hipStreamUpdateCaptureDependencies.numDependencies = (size_t)numDependencies; \ + cb_data.args.hipStreamUpdateCaptureDependencies.flags = (unsigned int)flags; \ +}; +// hipStreamWaitEvent[('hipStream_t', 'stream'), ('hipEvent_t', 'event'), ('unsigned int', 'flags')] +#define INIT_hipStreamWaitEvent_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamWaitEvent.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamWaitEvent.event = (hipEvent_t)event; \ + cb_data.args.hipStreamWaitEvent.flags = (unsigned int)flags; \ +}; +// hipStreamWaitValue32[('hipStream_t', 'stream'), ('void*', 'ptr'), ('unsigned int', 'value'), ('unsigned int', 'flags'), ('unsigned int', 'mask')] +#define INIT_hipStreamWaitValue32_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamWaitValue32.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamWaitValue32.ptr = (void*)ptr; \ + cb_data.args.hipStreamWaitValue32.value = (unsigned int)value; \ + cb_data.args.hipStreamWaitValue32.flags = (unsigned int)flags; \ + cb_data.args.hipStreamWaitValue32.mask = (unsigned int)mask; \ +}; +// hipStreamWaitValue64[('hipStream_t', 'stream'), ('void*', 'ptr'), ('uint64_t', 'value'), ('unsigned int', 'flags'), ('uint64_t', 'mask')] +#define INIT_hipStreamWaitValue64_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamWaitValue64.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamWaitValue64.ptr = (void*)ptr; \ + cb_data.args.hipStreamWaitValue64.value = (uint64_t)value; \ + cb_data.args.hipStreamWaitValue64.flags = (unsigned int)flags; \ + cb_data.args.hipStreamWaitValue64.mask = (uint64_t)mask; \ +}; +// hipStreamWriteValue32[('hipStream_t', 'stream'), ('void*', 'ptr'), ('unsigned int', 'value'), ('unsigned int', 'flags')] +#define INIT_hipStreamWriteValue32_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamWriteValue32.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamWriteValue32.ptr = (void*)ptr; \ + cb_data.args.hipStreamWriteValue32.value = (unsigned int)value; \ + cb_data.args.hipStreamWriteValue32.flags = (unsigned int)flags; \ +}; +// hipStreamWriteValue64[('hipStream_t', 'stream'), ('void*', 'ptr'), ('uint64_t', 'value'), ('unsigned int', 'flags')] +#define INIT_hipStreamWriteValue64_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipStreamWriteValue64.stream = (hipStream_t)stream; \ + cb_data.args.hipStreamWriteValue64.ptr = (void*)ptr; \ + cb_data.args.hipStreamWriteValue64.value = (uint64_t)value; \ + cb_data.args.hipStreamWriteValue64.flags = (unsigned int)flags; \ +}; +// hipTexRefGetAddress[('hipDeviceptr_t*', 'dev_ptr'), ('const textureReference*', 'texRef')] +#define INIT_hipTexRefGetAddress_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefGetAddress.dev_ptr = (hipDeviceptr_t*)dptr; \ + cb_data.args.hipTexRefGetAddress.texRef = (const textureReference*)texRef; \ +}; +// hipTexRefGetArray[('hipArray_t*', 'pArray'), ('const textureReference*', 'texRef')] +#define INIT_hipTexRefGetArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefGetArray.pArray = (hipArray_t*)pArray; \ + cb_data.args.hipTexRefGetArray.texRef = (const textureReference*)texRef; \ +}; +// hipTexRefGetBorderColor[('float*', 'pBorderColor'), ('const textureReference*', 'texRef')] +#define INIT_hipTexRefGetBorderColor_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefGetBorderColor.pBorderColor = (float*)pBorderColor; \ + cb_data.args.hipTexRefGetBorderColor.texRef = (const textureReference*)texRef; \ +}; +// hipTexRefGetFlags[('unsigned int*', 'pFlags'), ('const textureReference*', 'texRef')] +#define INIT_hipTexRefGetFlags_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefGetFlags.pFlags = (unsigned int*)pFlags; \ + cb_data.args.hipTexRefGetFlags.texRef = (const textureReference*)texRef; \ +}; +// hipTexRefGetFormat[('hipArray_Format*', 'pFormat'), ('int*', 'pNumChannels'), ('const textureReference*', 'texRef')] +#define INIT_hipTexRefGetFormat_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefGetFormat.pFormat = (hipArray_Format*)pFormat; \ + cb_data.args.hipTexRefGetFormat.pNumChannels = (int*)pNumChannels; \ + cb_data.args.hipTexRefGetFormat.texRef = (const textureReference*)texRef; \ +}; +// hipTexRefGetMaxAnisotropy[('int*', 'pmaxAnsio'), ('const textureReference*', 'texRef')] +#define INIT_hipTexRefGetMaxAnisotropy_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefGetMaxAnisotropy.pmaxAnsio = (int*)pmaxAnsio; \ + cb_data.args.hipTexRefGetMaxAnisotropy.texRef = (const textureReference*)texRef; \ +}; +// hipTexRefGetMipMappedArray[('hipMipmappedArray_t*', 'pArray'), ('const textureReference*', 'texRef')] +#define INIT_hipTexRefGetMipMappedArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefGetMipMappedArray.pArray = (hipMipmappedArray_t*)pArray; \ + cb_data.args.hipTexRefGetMipMappedArray.texRef = (const textureReference*)texRef; \ +}; +// hipTexRefGetMipmapLevelBias[('float*', 'pbias'), ('const textureReference*', 'texRef')] +#define INIT_hipTexRefGetMipmapLevelBias_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefGetMipmapLevelBias.pbias = (float*)pbias; \ + cb_data.args.hipTexRefGetMipmapLevelBias.texRef = (const textureReference*)texRef; \ +}; +// hipTexRefGetMipmapLevelClamp[('float*', 'pminMipmapLevelClamp'), ('float*', 'pmaxMipmapLevelClamp'), ('const textureReference*', 'texRef')] +#define INIT_hipTexRefGetMipmapLevelClamp_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefGetMipmapLevelClamp.pminMipmapLevelClamp = (float*)pminMipmapLevelClamp; \ + cb_data.args.hipTexRefGetMipmapLevelClamp.pmaxMipmapLevelClamp = (float*)pmaxMipmapLevelClamp; \ + cb_data.args.hipTexRefGetMipmapLevelClamp.texRef = (const textureReference*)texRef; \ +}; +// hipTexRefSetAddress[('size_t*', 'ByteOffset'), ('textureReference*', 'texRef'), ('hipDeviceptr_t', 'dptr'), ('size_t', 'bytes')] +#define INIT_hipTexRefSetAddress_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefSetAddress.ByteOffset = (size_t*)ByteOffset; \ + cb_data.args.hipTexRefSetAddress.texRef = (textureReference*)texRef; \ + cb_data.args.hipTexRefSetAddress.dptr = (hipDeviceptr_t)dptr; \ + cb_data.args.hipTexRefSetAddress.bytes = (size_t)bytes; \ +}; +// hipTexRefSetAddress2D[('textureReference*', 'texRef'), ('const HIP_ARRAY_DESCRIPTOR*', 'desc'), ('hipDeviceptr_t', 'dptr'), ('size_t', 'Pitch')] +#define INIT_hipTexRefSetAddress2D_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefSetAddress2D.texRef = (textureReference*)texRef; \ + cb_data.args.hipTexRefSetAddress2D.desc = (const HIP_ARRAY_DESCRIPTOR*)desc; \ + cb_data.args.hipTexRefSetAddress2D.dptr = (hipDeviceptr_t)dptr; \ + cb_data.args.hipTexRefSetAddress2D.Pitch = (size_t)Pitch; \ +}; +// hipTexRefSetArray[('textureReference*', 'tex'), ('hipArray_const_t', 'array'), ('unsigned int', 'flags')] +#define INIT_hipTexRefSetArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefSetArray.tex = (textureReference*)texRef; \ + cb_data.args.hipTexRefSetArray.array = (hipArray_const_t)array; \ + cb_data.args.hipTexRefSetArray.flags = (unsigned int)flags; \ +}; +// hipTexRefSetBorderColor[('textureReference*', 'texRef'), ('float*', 'pBorderColor')] +#define INIT_hipTexRefSetBorderColor_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefSetBorderColor.texRef = (textureReference*)texRef; \ + cb_data.args.hipTexRefSetBorderColor.pBorderColor = (float*)pBorderColor; \ +}; +// hipTexRefSetFlags[('textureReference*', 'texRef'), ('unsigned int', 'Flags')] +#define INIT_hipTexRefSetFlags_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefSetFlags.texRef = (textureReference*)texRef; \ + cb_data.args.hipTexRefSetFlags.Flags = (unsigned int)Flags; \ +}; +// hipTexRefSetFormat[('textureReference*', 'texRef'), ('hipArray_Format', 'fmt'), ('int', 'NumPackedComponents')] +#define INIT_hipTexRefSetFormat_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefSetFormat.texRef = (textureReference*)texRef; \ + cb_data.args.hipTexRefSetFormat.fmt = (hipArray_Format)fmt; \ + cb_data.args.hipTexRefSetFormat.NumPackedComponents = (int)NumPackedComponents; \ +}; +// hipTexRefSetMaxAnisotropy[('textureReference*', 'texRef'), ('unsigned int', 'maxAniso')] +#define INIT_hipTexRefSetMaxAnisotropy_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefSetMaxAnisotropy.texRef = (textureReference*)texRef; \ + cb_data.args.hipTexRefSetMaxAnisotropy.maxAniso = (unsigned int)maxAniso; \ +}; +// hipTexRefSetMipmapLevelBias[('textureReference*', 'texRef'), ('float', 'bias')] +#define INIT_hipTexRefSetMipmapLevelBias_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefSetMipmapLevelBias.texRef = (textureReference*)texRef; \ + cb_data.args.hipTexRefSetMipmapLevelBias.bias = (float)bias; \ +}; +// hipTexRefSetMipmapLevelClamp[('textureReference*', 'texRef'), ('float', 'minMipMapLevelClamp'), ('float', 'maxMipMapLevelClamp')] +#define INIT_hipTexRefSetMipmapLevelClamp_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefSetMipmapLevelClamp.texRef = (textureReference*)texRef; \ + cb_data.args.hipTexRefSetMipmapLevelClamp.minMipMapLevelClamp = (float)minMipMapLevelClamp; \ + cb_data.args.hipTexRefSetMipmapLevelClamp.maxMipMapLevelClamp = (float)maxMipMapLevelClamp; \ +}; +// hipTexRefSetMipmappedArray[('textureReference*', 'texRef'), ('hipMipmappedArray*', 'mipmappedArray'), ('unsigned int', 'Flags')] +#define INIT_hipTexRefSetMipmappedArray_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipTexRefSetMipmappedArray.texRef = (textureReference*)texRef; \ + cb_data.args.hipTexRefSetMipmappedArray.mipmappedArray = (hipMipmappedArray*)mipmappedArray; \ + cb_data.args.hipTexRefSetMipmappedArray.Flags = (unsigned int)Flags; \ +}; +// hipThreadExchangeStreamCaptureMode[('hipStreamCaptureMode*', 'mode')] +#define INIT_hipThreadExchangeStreamCaptureMode_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipThreadExchangeStreamCaptureMode.mode = (hipStreamCaptureMode*)mode; \ +}; +// hipUserObjectCreate[('hipUserObject_t*', 'object_out'), ('void*', 'ptr'), ('hipHostFn_t', 'destroy'), ('unsigned int', 'initialRefcount'), ('unsigned int', 'flags')] +#define INIT_hipUserObjectCreate_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipUserObjectCreate.object_out = (hipUserObject_t*)object_out; \ + cb_data.args.hipUserObjectCreate.ptr = (void*)ptr; \ + cb_data.args.hipUserObjectCreate.destroy = (hipHostFn_t)destroy; \ + cb_data.args.hipUserObjectCreate.initialRefcount = (unsigned int)initialRefcount; \ + cb_data.args.hipUserObjectCreate.flags = (unsigned int)flags; \ +}; +// hipUserObjectRelease[('hipUserObject_t', 'object'), ('unsigned int', 'count')] +#define INIT_hipUserObjectRelease_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipUserObjectRelease.object = (hipUserObject_t)object; \ + cb_data.args.hipUserObjectRelease.count = (unsigned int)count; \ +}; +// hipUserObjectRetain[('hipUserObject_t', 'object'), ('unsigned int', 'count')] +#define INIT_hipUserObjectRetain_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipUserObjectRetain.object = (hipUserObject_t)object; \ + cb_data.args.hipUserObjectRetain.count = (unsigned int)count; \ +}; +// hipWaitExternalSemaphoresAsync[('const hipExternalSemaphore_t*', 'extSemArray'), ('const hipExternalSemaphoreWaitParams*', 'paramsArray'), ('unsigned int', 'numExtSems'), ('hipStream_t', 'stream')] +#define INIT_hipWaitExternalSemaphoresAsync_CB_ARGS_DATA(cb_data) { \ + cb_data.args.hipWaitExternalSemaphoresAsync.extSemArray = (const hipExternalSemaphore_t*)extSemArray; \ + cb_data.args.hipWaitExternalSemaphoresAsync.paramsArray = (const hipExternalSemaphoreWaitParams*)paramsArray; \ + cb_data.args.hipWaitExternalSemaphoresAsync.numExtSems = (unsigned int)numExtSems; \ + cb_data.args.hipWaitExternalSemaphoresAsync.stream = (hipStream_t)stream; \ +}; +#define INIT_CB_ARGS_DATA(cb_id, cb_data) INIT_##cb_id##_CB_ARGS_DATA(cb_data) + +// Macros for non-public API primitives +// hipBindTexture() +#define INIT_hipBindTexture_CB_ARGS_DATA(cb_data) {}; +// hipBindTexture2D() +#define INIT_hipBindTexture2D_CB_ARGS_DATA(cb_data) {}; +// hipBindTextureToArray() +#define INIT_hipBindTextureToArray_CB_ARGS_DATA(cb_data) {}; +// hipBindTextureToMipmappedArray() +#define INIT_hipBindTextureToMipmappedArray_CB_ARGS_DATA(cb_data) {}; +// hipCreateTextureObject() +#define INIT_hipCreateTextureObject_CB_ARGS_DATA(cb_data) {}; +// hipDestroyTextureObject() +#define INIT_hipDestroyTextureObject_CB_ARGS_DATA(cb_data) {}; +// hipDeviceGetCount() +#define INIT_hipDeviceGetCount_CB_ARGS_DATA(cb_data) {}; +// hipGetTextureAlignmentOffset() +#define INIT_hipGetTextureAlignmentOffset_CB_ARGS_DATA(cb_data) {}; +// hipGetTextureObjectResourceDesc() +#define INIT_hipGetTextureObjectResourceDesc_CB_ARGS_DATA(cb_data) {}; +// hipGetTextureObjectResourceViewDesc() +#define INIT_hipGetTextureObjectResourceViewDesc_CB_ARGS_DATA(cb_data) {}; +// hipGetTextureObjectTextureDesc() +#define INIT_hipGetTextureObjectTextureDesc_CB_ARGS_DATA(cb_data) {}; +// hipGetTextureReference() +#define INIT_hipGetTextureReference_CB_ARGS_DATA(cb_data) {}; +// hipTexObjectCreate() +#define INIT_hipTexObjectCreate_CB_ARGS_DATA(cb_data) {}; +// hipTexObjectDestroy() +#define INIT_hipTexObjectDestroy_CB_ARGS_DATA(cb_data) {}; +// hipTexObjectGetResourceDesc() +#define INIT_hipTexObjectGetResourceDesc_CB_ARGS_DATA(cb_data) {}; +// hipTexObjectGetResourceViewDesc() +#define INIT_hipTexObjectGetResourceViewDesc_CB_ARGS_DATA(cb_data) {}; +// hipTexObjectGetTextureDesc() +#define INIT_hipTexObjectGetTextureDesc_CB_ARGS_DATA(cb_data) {}; +// hipTexRefGetAddressMode() +#define INIT_hipTexRefGetAddressMode_CB_ARGS_DATA(cb_data) {}; +// hipTexRefGetFilterMode() +#define INIT_hipTexRefGetFilterMode_CB_ARGS_DATA(cb_data) {}; +// hipTexRefGetMipmapFilterMode() +#define INIT_hipTexRefGetMipmapFilterMode_CB_ARGS_DATA(cb_data) {}; +// hipTexRefSetAddressMode() +#define INIT_hipTexRefSetAddressMode_CB_ARGS_DATA(cb_data) {}; +// hipTexRefSetFilterMode() +#define INIT_hipTexRefSetFilterMode_CB_ARGS_DATA(cb_data) {}; +// hipTexRefSetMipmapFilterMode() +#define INIT_hipTexRefSetMipmapFilterMode_CB_ARGS_DATA(cb_data) {}; +// hipUnbindTexture() +#define INIT_hipUnbindTexture_CB_ARGS_DATA(cb_data) {}; + +#define INIT_NONE_CB_ARGS_DATA(cb_data) {}; + +#if HIP_PROF_HIP_API_STRING +// HIP API args filling helper +static inline void hipApiArgsInit(hip_api_id_t id, hip_api_data_t* data) { + switch (id) { +// __hipPopCallConfiguration[('dim3*', 'gridDim'), ('dim3*', 'blockDim'), ('size_t*', 'sharedMem'), ('hipStream_t*', 'stream')] + case HIP_API_ID___hipPopCallConfiguration: + if (data->args.__hipPopCallConfiguration.gridDim) data->args.__hipPopCallConfiguration.gridDim__val = *(data->args.__hipPopCallConfiguration.gridDim); + if (data->args.__hipPopCallConfiguration.blockDim) data->args.__hipPopCallConfiguration.blockDim__val = *(data->args.__hipPopCallConfiguration.blockDim); + if (data->args.__hipPopCallConfiguration.sharedMem) data->args.__hipPopCallConfiguration.sharedMem__val = *(data->args.__hipPopCallConfiguration.sharedMem); + if (data->args.__hipPopCallConfiguration.stream) data->args.__hipPopCallConfiguration.stream__val = *(data->args.__hipPopCallConfiguration.stream); + break; +// __hipPushCallConfiguration[('dim3', 'gridDim'), ('dim3', 'blockDim'), ('size_t', 'sharedMem'), ('hipStream_t', 'stream')] + case HIP_API_ID___hipPushCallConfiguration: + break; +// hipArray3DCreate[('hipArray_t*', 'array'), ('const HIP_ARRAY3D_DESCRIPTOR*', 'pAllocateArray')] + case HIP_API_ID_hipArray3DCreate: + if (data->args.hipArray3DCreate.array) data->args.hipArray3DCreate.array__val = *(data->args.hipArray3DCreate.array); + if (data->args.hipArray3DCreate.pAllocateArray) data->args.hipArray3DCreate.pAllocateArray__val = *(data->args.hipArray3DCreate.pAllocateArray); + break; +// hipArray3DGetDescriptor[('HIP_ARRAY3D_DESCRIPTOR*', 'pArrayDescriptor'), ('hipArray_t', 'array')] + case HIP_API_ID_hipArray3DGetDescriptor: + if (data->args.hipArray3DGetDescriptor.pArrayDescriptor) data->args.hipArray3DGetDescriptor.pArrayDescriptor__val = *(data->args.hipArray3DGetDescriptor.pArrayDescriptor); + break; +// hipArrayCreate[('hipArray_t*', 'pHandle'), ('const HIP_ARRAY_DESCRIPTOR*', 'pAllocateArray')] + case HIP_API_ID_hipArrayCreate: + if (data->args.hipArrayCreate.pHandle) data->args.hipArrayCreate.pHandle__val = *(data->args.hipArrayCreate.pHandle); + if (data->args.hipArrayCreate.pAllocateArray) data->args.hipArrayCreate.pAllocateArray__val = *(data->args.hipArrayCreate.pAllocateArray); + break; +// hipArrayDestroy[('hipArray_t', 'array')] + case HIP_API_ID_hipArrayDestroy: + break; +// hipArrayGetDescriptor[('HIP_ARRAY_DESCRIPTOR*', 'pArrayDescriptor'), ('hipArray_t', 'array')] + case HIP_API_ID_hipArrayGetDescriptor: + if (data->args.hipArrayGetDescriptor.pArrayDescriptor) data->args.hipArrayGetDescriptor.pArrayDescriptor__val = *(data->args.hipArrayGetDescriptor.pArrayDescriptor); + break; +// hipArrayGetInfo[('hipChannelFormatDesc*', 'desc'), ('hipExtent*', 'extent'), ('unsigned int*', 'flags'), ('hipArray_t', 'array')] + case HIP_API_ID_hipArrayGetInfo: + if (data->args.hipArrayGetInfo.desc) data->args.hipArrayGetInfo.desc__val = *(data->args.hipArrayGetInfo.desc); + if (data->args.hipArrayGetInfo.extent) data->args.hipArrayGetInfo.extent__val = *(data->args.hipArrayGetInfo.extent); + if (data->args.hipArrayGetInfo.flags) data->args.hipArrayGetInfo.flags__val = *(data->args.hipArrayGetInfo.flags); + break; +// hipChooseDeviceR0000[('int*', 'device'), ('const hipDeviceProp_tR0000*', 'prop')] + case HIP_API_ID_hipChooseDeviceR0000: + if (data->args.hipChooseDeviceR0000.device) data->args.hipChooseDeviceR0000.device__val = *(data->args.hipChooseDeviceR0000.device); + if (data->args.hipChooseDeviceR0000.prop) data->args.hipChooseDeviceR0000.prop__val = *(data->args.hipChooseDeviceR0000.prop); + break; +// hipChooseDeviceR0600[('int*', 'device'), ('const hipDeviceProp_tR0600*', 'prop')] + case HIP_API_ID_hipChooseDeviceR0600: + if (data->args.hipChooseDeviceR0600.device) data->args.hipChooseDeviceR0600.device__val = *(data->args.hipChooseDeviceR0600.device); + if (data->args.hipChooseDeviceR0600.prop) data->args.hipChooseDeviceR0600.prop__val = *(data->args.hipChooseDeviceR0600.prop); + break; +// hipConfigureCall[('dim3', 'gridDim'), ('dim3', 'blockDim'), ('size_t', 'sharedMem'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipConfigureCall: + break; +// hipCreateSurfaceObject[('hipSurfaceObject_t*', 'pSurfObject'), ('const hipResourceDesc*', 'pResDesc')] + case HIP_API_ID_hipCreateSurfaceObject: + if (data->args.hipCreateSurfaceObject.pSurfObject) data->args.hipCreateSurfaceObject.pSurfObject__val = *(data->args.hipCreateSurfaceObject.pSurfObject); + if (data->args.hipCreateSurfaceObject.pResDesc) data->args.hipCreateSurfaceObject.pResDesc__val = *(data->args.hipCreateSurfaceObject.pResDesc); + break; +// hipCtxCreate[('hipCtx_t*', 'ctx'), ('unsigned int', 'flags'), ('hipDevice_t', 'device')] + case HIP_API_ID_hipCtxCreate: + if (data->args.hipCtxCreate.ctx) data->args.hipCtxCreate.ctx__val = *(data->args.hipCtxCreate.ctx); + break; +// hipCtxDestroy[('hipCtx_t', 'ctx')] + case HIP_API_ID_hipCtxDestroy: + break; +// hipCtxDisablePeerAccess[('hipCtx_t', 'peerCtx')] + case HIP_API_ID_hipCtxDisablePeerAccess: + break; +// hipCtxEnablePeerAccess[('hipCtx_t', 'peerCtx'), ('unsigned int', 'flags')] + case HIP_API_ID_hipCtxEnablePeerAccess: + break; +// hipCtxGetApiVersion[('hipCtx_t', 'ctx'), ('int*', 'apiVersion')] + case HIP_API_ID_hipCtxGetApiVersion: + if (data->args.hipCtxGetApiVersion.apiVersion) data->args.hipCtxGetApiVersion.apiVersion__val = *(data->args.hipCtxGetApiVersion.apiVersion); + break; +// hipCtxGetCacheConfig[('hipFuncCache_t*', 'cacheConfig')] + case HIP_API_ID_hipCtxGetCacheConfig: + if (data->args.hipCtxGetCacheConfig.cacheConfig) data->args.hipCtxGetCacheConfig.cacheConfig__val = *(data->args.hipCtxGetCacheConfig.cacheConfig); + break; +// hipCtxGetCurrent[('hipCtx_t*', 'ctx')] + case HIP_API_ID_hipCtxGetCurrent: + if (data->args.hipCtxGetCurrent.ctx) data->args.hipCtxGetCurrent.ctx__val = *(data->args.hipCtxGetCurrent.ctx); + break; +// hipCtxGetDevice[('hipDevice_t*', 'device')] + case HIP_API_ID_hipCtxGetDevice: + if (data->args.hipCtxGetDevice.device) data->args.hipCtxGetDevice.device__val = *(data->args.hipCtxGetDevice.device); + break; +// hipCtxGetFlags[('unsigned int*', 'flags')] + case HIP_API_ID_hipCtxGetFlags: + if (data->args.hipCtxGetFlags.flags) data->args.hipCtxGetFlags.flags__val = *(data->args.hipCtxGetFlags.flags); + break; +// hipCtxGetSharedMemConfig[('hipSharedMemConfig*', 'pConfig')] + case HIP_API_ID_hipCtxGetSharedMemConfig: + if (data->args.hipCtxGetSharedMemConfig.pConfig) data->args.hipCtxGetSharedMemConfig.pConfig__val = *(data->args.hipCtxGetSharedMemConfig.pConfig); + break; +// hipCtxPopCurrent[('hipCtx_t*', 'ctx')] + case HIP_API_ID_hipCtxPopCurrent: + if (data->args.hipCtxPopCurrent.ctx) data->args.hipCtxPopCurrent.ctx__val = *(data->args.hipCtxPopCurrent.ctx); + break; +// hipCtxPushCurrent[('hipCtx_t', 'ctx')] + case HIP_API_ID_hipCtxPushCurrent: + break; +// hipCtxSetCacheConfig[('hipFuncCache_t', 'cacheConfig')] + case HIP_API_ID_hipCtxSetCacheConfig: + break; +// hipCtxSetCurrent[('hipCtx_t', 'ctx')] + case HIP_API_ID_hipCtxSetCurrent: + break; +// hipCtxSetSharedMemConfig[('hipSharedMemConfig', 'config')] + case HIP_API_ID_hipCtxSetSharedMemConfig: + break; +// hipCtxSynchronize[] + case HIP_API_ID_hipCtxSynchronize: + break; +// hipDestroyExternalMemory[('hipExternalMemory_t', 'extMem')] + case HIP_API_ID_hipDestroyExternalMemory: + break; +// hipDestroyExternalSemaphore[('hipExternalSemaphore_t', 'extSem')] + case HIP_API_ID_hipDestroyExternalSemaphore: + break; +// hipDestroySurfaceObject[('hipSurfaceObject_t', 'surfaceObject')] + case HIP_API_ID_hipDestroySurfaceObject: + break; +// hipDeviceCanAccessPeer[('int*', 'canAccessPeer'), ('int', 'deviceId'), ('int', 'peerDeviceId')] + case HIP_API_ID_hipDeviceCanAccessPeer: + if (data->args.hipDeviceCanAccessPeer.canAccessPeer) data->args.hipDeviceCanAccessPeer.canAccessPeer__val = *(data->args.hipDeviceCanAccessPeer.canAccessPeer); + break; +// hipDeviceComputeCapability[('int*', 'major'), ('int*', 'minor'), ('hipDevice_t', 'device')] + case HIP_API_ID_hipDeviceComputeCapability: + if (data->args.hipDeviceComputeCapability.major) data->args.hipDeviceComputeCapability.major__val = *(data->args.hipDeviceComputeCapability.major); + if (data->args.hipDeviceComputeCapability.minor) data->args.hipDeviceComputeCapability.minor__val = *(data->args.hipDeviceComputeCapability.minor); + break; +// hipDeviceDisablePeerAccess[('int', 'peerDeviceId')] + case HIP_API_ID_hipDeviceDisablePeerAccess: + break; +// hipDeviceEnablePeerAccess[('int', 'peerDeviceId'), ('unsigned int', 'flags')] + case HIP_API_ID_hipDeviceEnablePeerAccess: + break; +// hipDeviceGet[('hipDevice_t*', 'device'), ('int', 'ordinal')] + case HIP_API_ID_hipDeviceGet: + if (data->args.hipDeviceGet.device) data->args.hipDeviceGet.device__val = *(data->args.hipDeviceGet.device); + break; +// hipDeviceGetAttribute[('int*', 'pi'), ('hipDeviceAttribute_t', 'attr'), ('int', 'deviceId')] + case HIP_API_ID_hipDeviceGetAttribute: + if (data->args.hipDeviceGetAttribute.pi) data->args.hipDeviceGetAttribute.pi__val = *(data->args.hipDeviceGetAttribute.pi); + break; +// hipDeviceGetByPCIBusId[('int*', 'device'), ('const char*', 'pciBusId')] + case HIP_API_ID_hipDeviceGetByPCIBusId: + if (data->args.hipDeviceGetByPCIBusId.device) data->args.hipDeviceGetByPCIBusId.device__val = *(data->args.hipDeviceGetByPCIBusId.device); + if (data->args.hipDeviceGetByPCIBusId.pciBusId) data->args.hipDeviceGetByPCIBusId.pciBusId__val = *(data->args.hipDeviceGetByPCIBusId.pciBusId); + break; +// hipDeviceGetCacheConfig[('hipFuncCache_t*', 'cacheConfig')] + case HIP_API_ID_hipDeviceGetCacheConfig: + if (data->args.hipDeviceGetCacheConfig.cacheConfig) data->args.hipDeviceGetCacheConfig.cacheConfig__val = *(data->args.hipDeviceGetCacheConfig.cacheConfig); + break; +// hipDeviceGetDefaultMemPool[('hipMemPool_t*', 'mem_pool'), ('int', 'device')] + case HIP_API_ID_hipDeviceGetDefaultMemPool: + if (data->args.hipDeviceGetDefaultMemPool.mem_pool) data->args.hipDeviceGetDefaultMemPool.mem_pool__val = *(data->args.hipDeviceGetDefaultMemPool.mem_pool); + break; +// hipDeviceGetGraphMemAttribute[('int', 'device'), ('hipGraphMemAttributeType', 'attr'), ('void*', 'value')] + case HIP_API_ID_hipDeviceGetGraphMemAttribute: + break; +// hipDeviceGetLimit[('size_t*', 'pValue'), ('hipLimit_t', 'limit')] + case HIP_API_ID_hipDeviceGetLimit: + if (data->args.hipDeviceGetLimit.pValue) data->args.hipDeviceGetLimit.pValue__val = *(data->args.hipDeviceGetLimit.pValue); + break; +// hipDeviceGetMemPool[('hipMemPool_t*', 'mem_pool'), ('int', 'device')] + case HIP_API_ID_hipDeviceGetMemPool: + if (data->args.hipDeviceGetMemPool.mem_pool) data->args.hipDeviceGetMemPool.mem_pool__val = *(data->args.hipDeviceGetMemPool.mem_pool); + break; +// hipDeviceGetName[('char*', 'name'), ('int', 'len'), ('hipDevice_t', 'device')] + case HIP_API_ID_hipDeviceGetName: + data->args.hipDeviceGetName.name = (data->args.hipDeviceGetName.name) ? strdup(data->args.hipDeviceGetName.name) : NULL; + break; +// hipDeviceGetP2PAttribute[('int*', 'value'), ('hipDeviceP2PAttr', 'attr'), ('int', 'srcDevice'), ('int', 'dstDevice')] + case HIP_API_ID_hipDeviceGetP2PAttribute: + if (data->args.hipDeviceGetP2PAttribute.value) data->args.hipDeviceGetP2PAttribute.value__val = *(data->args.hipDeviceGetP2PAttribute.value); + break; +// hipDeviceGetPCIBusId[('char*', 'pciBusId'), ('int', 'len'), ('int', 'device')] + case HIP_API_ID_hipDeviceGetPCIBusId: + data->args.hipDeviceGetPCIBusId.pciBusId = (data->args.hipDeviceGetPCIBusId.pciBusId) ? strdup(data->args.hipDeviceGetPCIBusId.pciBusId) : NULL; + break; +// hipDeviceGetSharedMemConfig[('hipSharedMemConfig*', 'pConfig')] + case HIP_API_ID_hipDeviceGetSharedMemConfig: + if (data->args.hipDeviceGetSharedMemConfig.pConfig) data->args.hipDeviceGetSharedMemConfig.pConfig__val = *(data->args.hipDeviceGetSharedMemConfig.pConfig); + break; +// hipDeviceGetStreamPriorityRange[('int*', 'leastPriority'), ('int*', 'greatestPriority')] + case HIP_API_ID_hipDeviceGetStreamPriorityRange: + if (data->args.hipDeviceGetStreamPriorityRange.leastPriority) data->args.hipDeviceGetStreamPriorityRange.leastPriority__val = *(data->args.hipDeviceGetStreamPriorityRange.leastPriority); + if (data->args.hipDeviceGetStreamPriorityRange.greatestPriority) data->args.hipDeviceGetStreamPriorityRange.greatestPriority__val = *(data->args.hipDeviceGetStreamPriorityRange.greatestPriority); + break; +// hipDeviceGetUuid[('hipUUID*', 'uuid'), ('hipDevice_t', 'device')] + case HIP_API_ID_hipDeviceGetUuid: + if (data->args.hipDeviceGetUuid.uuid) data->args.hipDeviceGetUuid.uuid__val = *(data->args.hipDeviceGetUuid.uuid); + break; +// hipDeviceGraphMemTrim[('int', 'device')] + case HIP_API_ID_hipDeviceGraphMemTrim: + break; +// hipDevicePrimaryCtxGetState[('hipDevice_t', 'dev'), ('unsigned int*', 'flags'), ('int*', 'active')] + case HIP_API_ID_hipDevicePrimaryCtxGetState: + if (data->args.hipDevicePrimaryCtxGetState.flags) data->args.hipDevicePrimaryCtxGetState.flags__val = *(data->args.hipDevicePrimaryCtxGetState.flags); + if (data->args.hipDevicePrimaryCtxGetState.active) data->args.hipDevicePrimaryCtxGetState.active__val = *(data->args.hipDevicePrimaryCtxGetState.active); + break; +// hipDevicePrimaryCtxRelease[('hipDevice_t', 'dev')] + case HIP_API_ID_hipDevicePrimaryCtxRelease: + break; +// hipDevicePrimaryCtxReset[('hipDevice_t', 'dev')] + case HIP_API_ID_hipDevicePrimaryCtxReset: + break; +// hipDevicePrimaryCtxRetain[('hipCtx_t*', 'pctx'), ('hipDevice_t', 'dev')] + case HIP_API_ID_hipDevicePrimaryCtxRetain: + if (data->args.hipDevicePrimaryCtxRetain.pctx) data->args.hipDevicePrimaryCtxRetain.pctx__val = *(data->args.hipDevicePrimaryCtxRetain.pctx); + break; +// hipDevicePrimaryCtxSetFlags[('hipDevice_t', 'dev'), ('unsigned int', 'flags')] + case HIP_API_ID_hipDevicePrimaryCtxSetFlags: + break; +// hipDeviceReset[] + case HIP_API_ID_hipDeviceReset: + break; +// hipDeviceSetCacheConfig[('hipFuncCache_t', 'cacheConfig')] + case HIP_API_ID_hipDeviceSetCacheConfig: + break; +// hipDeviceSetGraphMemAttribute[('int', 'device'), ('hipGraphMemAttributeType', 'attr'), ('void*', 'value')] + case HIP_API_ID_hipDeviceSetGraphMemAttribute: + break; +// hipDeviceSetLimit[('hipLimit_t', 'limit'), ('size_t', 'value')] + case HIP_API_ID_hipDeviceSetLimit: + break; +// hipDeviceSetMemPool[('int', 'device'), ('hipMemPool_t', 'mem_pool')] + case HIP_API_ID_hipDeviceSetMemPool: + break; +// hipDeviceSetSharedMemConfig[('hipSharedMemConfig', 'config')] + case HIP_API_ID_hipDeviceSetSharedMemConfig: + break; +// hipDeviceSynchronize[] + case HIP_API_ID_hipDeviceSynchronize: + break; +// hipDeviceTotalMem[('size_t*', 'bytes'), ('hipDevice_t', 'device')] + case HIP_API_ID_hipDeviceTotalMem: + if (data->args.hipDeviceTotalMem.bytes) data->args.hipDeviceTotalMem.bytes__val = *(data->args.hipDeviceTotalMem.bytes); + break; +// hipDriverGetVersion[('int*', 'driverVersion')] + case HIP_API_ID_hipDriverGetVersion: + if (data->args.hipDriverGetVersion.driverVersion) data->args.hipDriverGetVersion.driverVersion__val = *(data->args.hipDriverGetVersion.driverVersion); + break; +// hipDrvGraphAddMemcpyNode[('hipGraphNode_t*', 'phGraphNode'), ('hipGraph_t', 'hGraph'), ('const hipGraphNode_t*', 'dependencies'), ('size_t', 'numDependencies'), ('const HIP_MEMCPY3D*', 'copyParams'), ('hipCtx_t', 'ctx')] + case HIP_API_ID_hipDrvGraphAddMemcpyNode: + if (data->args.hipDrvGraphAddMemcpyNode.phGraphNode) data->args.hipDrvGraphAddMemcpyNode.phGraphNode__val = *(data->args.hipDrvGraphAddMemcpyNode.phGraphNode); + if (data->args.hipDrvGraphAddMemcpyNode.dependencies) data->args.hipDrvGraphAddMemcpyNode.dependencies__val = *(data->args.hipDrvGraphAddMemcpyNode.dependencies); + if (data->args.hipDrvGraphAddMemcpyNode.copyParams) data->args.hipDrvGraphAddMemcpyNode.copyParams__val = *(data->args.hipDrvGraphAddMemcpyNode.copyParams); + break; +// hipDrvGraphAddMemsetNode[('hipGraphNode_t*', 'phGraphNode'), ('hipGraph_t', 'hGraph'), ('const hipGraphNode_t*', 'dependencies'), ('size_t', 'numDependencies'), ('const HIP_MEMSET_NODE_PARAMS*', 'memsetParams'), ('hipCtx_t', 'ctx')] + case HIP_API_ID_hipDrvGraphAddMemsetNode: + if (data->args.hipDrvGraphAddMemsetNode.phGraphNode) data->args.hipDrvGraphAddMemsetNode.phGraphNode__val = *(data->args.hipDrvGraphAddMemsetNode.phGraphNode); + if (data->args.hipDrvGraphAddMemsetNode.dependencies) data->args.hipDrvGraphAddMemsetNode.dependencies__val = *(data->args.hipDrvGraphAddMemsetNode.dependencies); + if (data->args.hipDrvGraphAddMemsetNode.memsetParams) data->args.hipDrvGraphAddMemsetNode.memsetParams__val = *(data->args.hipDrvGraphAddMemsetNode.memsetParams); + break; +// hipDrvMemcpy2DUnaligned[('const hip_Memcpy2D*', 'pCopy')] + case HIP_API_ID_hipDrvMemcpy2DUnaligned: + if (data->args.hipDrvMemcpy2DUnaligned.pCopy) data->args.hipDrvMemcpy2DUnaligned.pCopy__val = *(data->args.hipDrvMemcpy2DUnaligned.pCopy); + break; +// hipDrvMemcpy3D[('const HIP_MEMCPY3D*', 'pCopy')] + case HIP_API_ID_hipDrvMemcpy3D: + if (data->args.hipDrvMemcpy3D.pCopy) data->args.hipDrvMemcpy3D.pCopy__val = *(data->args.hipDrvMemcpy3D.pCopy); + break; +// hipDrvMemcpy3DAsync[('const HIP_MEMCPY3D*', 'pCopy'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipDrvMemcpy3DAsync: + if (data->args.hipDrvMemcpy3DAsync.pCopy) data->args.hipDrvMemcpy3DAsync.pCopy__val = *(data->args.hipDrvMemcpy3DAsync.pCopy); + break; +// hipDrvPointerGetAttributes[('unsigned int', 'numAttributes'), ('hipPointer_attribute*', 'attributes'), ('void**', 'data'), ('hipDeviceptr_t', 'ptr')] + case HIP_API_ID_hipDrvPointerGetAttributes: + if (data->args.hipDrvPointerGetAttributes.attributes) data->args.hipDrvPointerGetAttributes.attributes__val = *(data->args.hipDrvPointerGetAttributes.attributes); + if (data->args.hipDrvPointerGetAttributes.data) data->args.hipDrvPointerGetAttributes.data__val = *(data->args.hipDrvPointerGetAttributes.data); + break; +// hipEventCreate[('hipEvent_t*', 'event')] + case HIP_API_ID_hipEventCreate: + if (data->args.hipEventCreate.event) data->args.hipEventCreate.event__val = *(data->args.hipEventCreate.event); + break; +// hipEventCreateWithFlags[('hipEvent_t*', 'event'), ('unsigned int', 'flags')] + case HIP_API_ID_hipEventCreateWithFlags: + if (data->args.hipEventCreateWithFlags.event) data->args.hipEventCreateWithFlags.event__val = *(data->args.hipEventCreateWithFlags.event); + break; +// hipEventDestroy[('hipEvent_t', 'event')] + case HIP_API_ID_hipEventDestroy: + break; +// hipEventElapsedTime[('float*', 'ms'), ('hipEvent_t', 'start'), ('hipEvent_t', 'stop')] + case HIP_API_ID_hipEventElapsedTime: + if (data->args.hipEventElapsedTime.ms) data->args.hipEventElapsedTime.ms__val = *(data->args.hipEventElapsedTime.ms); + break; +// hipEventQuery[('hipEvent_t', 'event')] + case HIP_API_ID_hipEventQuery: + break; +// hipEventRecord[('hipEvent_t', 'event'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipEventRecord: + break; +// hipEventSynchronize[('hipEvent_t', 'event')] + case HIP_API_ID_hipEventSynchronize: + break; +// hipExtGetLastError[] + case HIP_API_ID_hipExtGetLastError: + break; +// hipExtGetLinkTypeAndHopCount[('int', 'device1'), ('int', 'device2'), ('unsigned int*', 'linktype'), ('unsigned int*', 'hopcount')] + case HIP_API_ID_hipExtGetLinkTypeAndHopCount: + if (data->args.hipExtGetLinkTypeAndHopCount.linktype) data->args.hipExtGetLinkTypeAndHopCount.linktype__val = *(data->args.hipExtGetLinkTypeAndHopCount.linktype); + if (data->args.hipExtGetLinkTypeAndHopCount.hopcount) data->args.hipExtGetLinkTypeAndHopCount.hopcount__val = *(data->args.hipExtGetLinkTypeAndHopCount.hopcount); + break; +// hipExtLaunchKernel[('const void*', 'function_address'), ('dim3', 'numBlocks'), ('dim3', 'dimBlocks'), ('void**', 'args'), ('size_t', 'sharedMemBytes'), ('hipStream_t', 'stream'), ('hipEvent_t', 'startEvent'), ('hipEvent_t', 'stopEvent'), ('int', 'flags')] + case HIP_API_ID_hipExtLaunchKernel: + if (data->args.hipExtLaunchKernel.args) data->args.hipExtLaunchKernel.args__val = *(data->args.hipExtLaunchKernel.args); + break; +// hipExtLaunchMultiKernelMultiDevice[('hipLaunchParams*', 'launchParamsList'), ('int', 'numDevices'), ('unsigned int', 'flags')] + case HIP_API_ID_hipExtLaunchMultiKernelMultiDevice: + if (data->args.hipExtLaunchMultiKernelMultiDevice.launchParamsList) data->args.hipExtLaunchMultiKernelMultiDevice.launchParamsList__val = *(data->args.hipExtLaunchMultiKernelMultiDevice.launchParamsList); + break; +// hipExtMallocWithFlags[('void**', 'ptr'), ('size_t', 'sizeBytes'), ('unsigned int', 'flags')] + case HIP_API_ID_hipExtMallocWithFlags: + if (data->args.hipExtMallocWithFlags.ptr) data->args.hipExtMallocWithFlags.ptr__val = *(data->args.hipExtMallocWithFlags.ptr); + break; +// hipExtModuleLaunchKernel[('hipFunction_t', 'f'), ('unsigned int', 'globalWorkSizeX'), ('unsigned int', 'globalWorkSizeY'), ('unsigned int', 'globalWorkSizeZ'), ('unsigned int', 'localWorkSizeX'), ('unsigned int', 'localWorkSizeY'), ('unsigned int', 'localWorkSizeZ'), ('size_t', 'sharedMemBytes'), ('hipStream_t', 'hStream'), ('void**', 'kernelParams'), ('void**', 'extra'), ('hipEvent_t', 'startEvent'), ('hipEvent_t', 'stopEvent'), ('unsigned int', 'flags')] + case HIP_API_ID_hipExtModuleLaunchKernel: + if (data->args.hipExtModuleLaunchKernel.kernelParams) data->args.hipExtModuleLaunchKernel.kernelParams__val = *(data->args.hipExtModuleLaunchKernel.kernelParams); + if (data->args.hipExtModuleLaunchKernel.extra) data->args.hipExtModuleLaunchKernel.extra__val = *(data->args.hipExtModuleLaunchKernel.extra); + break; +// hipExtStreamCreateWithCUMask[('hipStream_t*', 'stream'), ('unsigned int', 'cuMaskSize'), ('const unsigned int*', 'cuMask')] + case HIP_API_ID_hipExtStreamCreateWithCUMask: + if (data->args.hipExtStreamCreateWithCUMask.stream) data->args.hipExtStreamCreateWithCUMask.stream__val = *(data->args.hipExtStreamCreateWithCUMask.stream); + if (data->args.hipExtStreamCreateWithCUMask.cuMask) data->args.hipExtStreamCreateWithCUMask.cuMask__val = *(data->args.hipExtStreamCreateWithCUMask.cuMask); + break; +// hipExtStreamGetCUMask[('hipStream_t', 'stream'), ('unsigned int', 'cuMaskSize'), ('unsigned int*', 'cuMask')] + case HIP_API_ID_hipExtStreamGetCUMask: + if (data->args.hipExtStreamGetCUMask.cuMask) data->args.hipExtStreamGetCUMask.cuMask__val = *(data->args.hipExtStreamGetCUMask.cuMask); + break; +// hipExternalMemoryGetMappedBuffer[('void**', 'devPtr'), ('hipExternalMemory_t', 'extMem'), ('const hipExternalMemoryBufferDesc*', 'bufferDesc')] + case HIP_API_ID_hipExternalMemoryGetMappedBuffer: + if (data->args.hipExternalMemoryGetMappedBuffer.devPtr) data->args.hipExternalMemoryGetMappedBuffer.devPtr__val = *(data->args.hipExternalMemoryGetMappedBuffer.devPtr); + if (data->args.hipExternalMemoryGetMappedBuffer.bufferDesc) data->args.hipExternalMemoryGetMappedBuffer.bufferDesc__val = *(data->args.hipExternalMemoryGetMappedBuffer.bufferDesc); + break; +// hipExternalMemoryGetMappedMipmappedArray[('hipMipmappedArray_t*', 'mipmap'), ('hipExternalMemory_t', 'extMem'), ('const hipExternalMemoryMipmappedArrayDesc*', 'mipmapDesc')] + case HIP_API_ID_hipExternalMemoryGetMappedMipmappedArray: + if (data->args.hipExternalMemoryGetMappedMipmappedArray.mipmap) data->args.hipExternalMemoryGetMappedMipmappedArray.mipmap__val = *(data->args.hipExternalMemoryGetMappedMipmappedArray.mipmap); + if (data->args.hipExternalMemoryGetMappedMipmappedArray.mipmapDesc) data->args.hipExternalMemoryGetMappedMipmappedArray.mipmapDesc__val = *(data->args.hipExternalMemoryGetMappedMipmappedArray.mipmapDesc); + break; +// hipFree[('void*', 'ptr')] + case HIP_API_ID_hipFree: + break; +// hipFreeArray[('hipArray_t', 'array')] + case HIP_API_ID_hipFreeArray: + break; +// hipFreeAsync[('void*', 'dev_ptr'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipFreeAsync: + break; +// hipFreeHost[('void*', 'ptr')] + case HIP_API_ID_hipFreeHost: + break; +// hipFreeMipmappedArray[('hipMipmappedArray_t', 'mipmappedArray')] + case HIP_API_ID_hipFreeMipmappedArray: + break; +// hipFuncGetAttribute[('int*', 'value'), ('hipFunction_attribute', 'attrib'), ('hipFunction_t', 'hfunc')] + case HIP_API_ID_hipFuncGetAttribute: + if (data->args.hipFuncGetAttribute.value) data->args.hipFuncGetAttribute.value__val = *(data->args.hipFuncGetAttribute.value); + break; +// hipFuncGetAttributes[('hipFuncAttributes*', 'attr'), ('const void*', 'func')] + case HIP_API_ID_hipFuncGetAttributes: + if (data->args.hipFuncGetAttributes.attr) data->args.hipFuncGetAttributes.attr__val = *(data->args.hipFuncGetAttributes.attr); + break; +// hipFuncSetAttribute[('const void*', 'func'), ('hipFuncAttribute', 'attr'), ('int', 'value')] + case HIP_API_ID_hipFuncSetAttribute: + break; +// hipFuncSetCacheConfig[('const void*', 'func'), ('hipFuncCache_t', 'config')] + case HIP_API_ID_hipFuncSetCacheConfig: + break; +// hipFuncSetSharedMemConfig[('const void*', 'func'), ('hipSharedMemConfig', 'config')] + case HIP_API_ID_hipFuncSetSharedMemConfig: + break; +// hipGLGetDevices[('unsigned int*', 'pHipDeviceCount'), ('int*', 'pHipDevices'), ('unsigned int', 'hipDeviceCount'), ('hipGLDeviceList', 'deviceList')] + case HIP_API_ID_hipGLGetDevices: + if (data->args.hipGLGetDevices.pHipDeviceCount) data->args.hipGLGetDevices.pHipDeviceCount__val = *(data->args.hipGLGetDevices.pHipDeviceCount); + if (data->args.hipGLGetDevices.pHipDevices) data->args.hipGLGetDevices.pHipDevices__val = *(data->args.hipGLGetDevices.pHipDevices); + break; +// hipGetChannelDesc[('hipChannelFormatDesc*', 'desc'), ('hipArray_const_t', 'array')] + case HIP_API_ID_hipGetChannelDesc: + if (data->args.hipGetChannelDesc.desc) data->args.hipGetChannelDesc.desc__val = *(data->args.hipGetChannelDesc.desc); + break; +// hipGetDevice[('int*', 'deviceId')] + case HIP_API_ID_hipGetDevice: + if (data->args.hipGetDevice.deviceId) data->args.hipGetDevice.deviceId__val = *(data->args.hipGetDevice.deviceId); + break; +// hipGetDeviceCount[('int*', 'count')] + case HIP_API_ID_hipGetDeviceCount: + if (data->args.hipGetDeviceCount.count) data->args.hipGetDeviceCount.count__val = *(data->args.hipGetDeviceCount.count); + break; +// hipGetDeviceFlags[('unsigned int*', 'flags')] + case HIP_API_ID_hipGetDeviceFlags: + if (data->args.hipGetDeviceFlags.flags) data->args.hipGetDeviceFlags.flags__val = *(data->args.hipGetDeviceFlags.flags); + break; +// hipGetDevicePropertiesR0000[('hipDeviceProp_tR0000*', 'prop'), ('int', 'device')] + case HIP_API_ID_hipGetDevicePropertiesR0000: + if (data->args.hipGetDevicePropertiesR0000.prop) data->args.hipGetDevicePropertiesR0000.prop__val = *(data->args.hipGetDevicePropertiesR0000.prop); + break; +// hipGetDevicePropertiesR0600[('hipDeviceProp_tR0600*', 'prop'), ('int', 'deviceId')] + case HIP_API_ID_hipGetDevicePropertiesR0600: + if (data->args.hipGetDevicePropertiesR0600.prop) data->args.hipGetDevicePropertiesR0600.prop__val = *(data->args.hipGetDevicePropertiesR0600.prop); + break; +// hipGetErrorString[] + case HIP_API_ID_hipGetErrorString: + break; +// hipGetFuncBySymbol[('hipFunction_t*', 'functionPtr'), ('const void*', 'symbolPtr')] + case HIP_API_ID_hipGetFuncBySymbol: + if (data->args.hipGetFuncBySymbol.functionPtr) data->args.hipGetFuncBySymbol.functionPtr__val = *(data->args.hipGetFuncBySymbol.functionPtr); + break; +// hipGetLastError[] + case HIP_API_ID_hipGetLastError: + break; +// hipGetMipmappedArrayLevel[('hipArray_t*', 'levelArray'), ('hipMipmappedArray_const_t', 'mipmappedArray'), ('unsigned int', 'level')] + case HIP_API_ID_hipGetMipmappedArrayLevel: + if (data->args.hipGetMipmappedArrayLevel.levelArray) data->args.hipGetMipmappedArrayLevel.levelArray__val = *(data->args.hipGetMipmappedArrayLevel.levelArray); + break; +// hipGetProcAddress[('const char*', 'symbol'), ('void**', 'pfn'), ('int', 'hipVersion'), ('uint64_t', 'flags'), ('hipDriverProcAddressQueryResult*', 'symbolStatus')] + case HIP_API_ID_hipGetProcAddress: + if (data->args.hipGetProcAddress.symbol) data->args.hipGetProcAddress.symbol__val = *(data->args.hipGetProcAddress.symbol); + if (data->args.hipGetProcAddress.pfn) data->args.hipGetProcAddress.pfn__val = *(data->args.hipGetProcAddress.pfn); + if (data->args.hipGetProcAddress.symbolStatus) data->args.hipGetProcAddress.symbolStatus__val = *(data->args.hipGetProcAddress.symbolStatus); + break; +// hipGetSymbolAddress[('void**', 'devPtr'), ('const void*', 'symbol')] + case HIP_API_ID_hipGetSymbolAddress: + if (data->args.hipGetSymbolAddress.devPtr) data->args.hipGetSymbolAddress.devPtr__val = *(data->args.hipGetSymbolAddress.devPtr); + break; +// hipGetSymbolSize[('size_t*', 'size'), ('const void*', 'symbol')] + case HIP_API_ID_hipGetSymbolSize: + if (data->args.hipGetSymbolSize.size) data->args.hipGetSymbolSize.size__val = *(data->args.hipGetSymbolSize.size); + break; +// hipGraphAddChildGraphNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('hipGraph_t', 'childGraph')] + case HIP_API_ID_hipGraphAddChildGraphNode: + if (data->args.hipGraphAddChildGraphNode.pGraphNode) data->args.hipGraphAddChildGraphNode.pGraphNode__val = *(data->args.hipGraphAddChildGraphNode.pGraphNode); + if (data->args.hipGraphAddChildGraphNode.pDependencies) data->args.hipGraphAddChildGraphNode.pDependencies__val = *(data->args.hipGraphAddChildGraphNode.pDependencies); + break; +// hipGraphAddDependencies[('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'from'), ('const hipGraphNode_t*', 'to'), ('size_t', 'numDependencies')] + case HIP_API_ID_hipGraphAddDependencies: + if (data->args.hipGraphAddDependencies.from) data->args.hipGraphAddDependencies.from__val = *(data->args.hipGraphAddDependencies.from); + if (data->args.hipGraphAddDependencies.to) data->args.hipGraphAddDependencies.to__val = *(data->args.hipGraphAddDependencies.to); + break; +// hipGraphAddEmptyNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies')] + case HIP_API_ID_hipGraphAddEmptyNode: + if (data->args.hipGraphAddEmptyNode.pGraphNode) data->args.hipGraphAddEmptyNode.pGraphNode__val = *(data->args.hipGraphAddEmptyNode.pGraphNode); + if (data->args.hipGraphAddEmptyNode.pDependencies) data->args.hipGraphAddEmptyNode.pDependencies__val = *(data->args.hipGraphAddEmptyNode.pDependencies); + break; +// hipGraphAddEventRecordNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('hipEvent_t', 'event')] + case HIP_API_ID_hipGraphAddEventRecordNode: + if (data->args.hipGraphAddEventRecordNode.pGraphNode) data->args.hipGraphAddEventRecordNode.pGraphNode__val = *(data->args.hipGraphAddEventRecordNode.pGraphNode); + if (data->args.hipGraphAddEventRecordNode.pDependencies) data->args.hipGraphAddEventRecordNode.pDependencies__val = *(data->args.hipGraphAddEventRecordNode.pDependencies); + break; +// hipGraphAddEventWaitNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('hipEvent_t', 'event')] + case HIP_API_ID_hipGraphAddEventWaitNode: + if (data->args.hipGraphAddEventWaitNode.pGraphNode) data->args.hipGraphAddEventWaitNode.pGraphNode__val = *(data->args.hipGraphAddEventWaitNode.pGraphNode); + if (data->args.hipGraphAddEventWaitNode.pDependencies) data->args.hipGraphAddEventWaitNode.pDependencies__val = *(data->args.hipGraphAddEventWaitNode.pDependencies); + break; +// hipGraphAddExternalSemaphoresSignalNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('const hipExternalSemaphoreSignalNodeParams*', 'nodeParams')] + case HIP_API_ID_hipGraphAddExternalSemaphoresSignalNode: + if (data->args.hipGraphAddExternalSemaphoresSignalNode.pGraphNode) data->args.hipGraphAddExternalSemaphoresSignalNode.pGraphNode__val = *(data->args.hipGraphAddExternalSemaphoresSignalNode.pGraphNode); + if (data->args.hipGraphAddExternalSemaphoresSignalNode.pDependencies) data->args.hipGraphAddExternalSemaphoresSignalNode.pDependencies__val = *(data->args.hipGraphAddExternalSemaphoresSignalNode.pDependencies); + if (data->args.hipGraphAddExternalSemaphoresSignalNode.nodeParams) data->args.hipGraphAddExternalSemaphoresSignalNode.nodeParams__val = *(data->args.hipGraphAddExternalSemaphoresSignalNode.nodeParams); + break; +// hipGraphAddExternalSemaphoresWaitNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('const hipExternalSemaphoreWaitNodeParams*', 'nodeParams')] + case HIP_API_ID_hipGraphAddExternalSemaphoresWaitNode: + if (data->args.hipGraphAddExternalSemaphoresWaitNode.pGraphNode) data->args.hipGraphAddExternalSemaphoresWaitNode.pGraphNode__val = *(data->args.hipGraphAddExternalSemaphoresWaitNode.pGraphNode); + if (data->args.hipGraphAddExternalSemaphoresWaitNode.pDependencies) data->args.hipGraphAddExternalSemaphoresWaitNode.pDependencies__val = *(data->args.hipGraphAddExternalSemaphoresWaitNode.pDependencies); + if (data->args.hipGraphAddExternalSemaphoresWaitNode.nodeParams) data->args.hipGraphAddExternalSemaphoresWaitNode.nodeParams__val = *(data->args.hipGraphAddExternalSemaphoresWaitNode.nodeParams); + break; +// hipGraphAddHostNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('const hipHostNodeParams*', 'pNodeParams')] + case HIP_API_ID_hipGraphAddHostNode: + if (data->args.hipGraphAddHostNode.pGraphNode) data->args.hipGraphAddHostNode.pGraphNode__val = *(data->args.hipGraphAddHostNode.pGraphNode); + if (data->args.hipGraphAddHostNode.pDependencies) data->args.hipGraphAddHostNode.pDependencies__val = *(data->args.hipGraphAddHostNode.pDependencies); + if (data->args.hipGraphAddHostNode.pNodeParams) data->args.hipGraphAddHostNode.pNodeParams__val = *(data->args.hipGraphAddHostNode.pNodeParams); + break; +// hipGraphAddKernelNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('const hipKernelNodeParams*', 'pNodeParams')] + case HIP_API_ID_hipGraphAddKernelNode: + if (data->args.hipGraphAddKernelNode.pGraphNode) data->args.hipGraphAddKernelNode.pGraphNode__val = *(data->args.hipGraphAddKernelNode.pGraphNode); + if (data->args.hipGraphAddKernelNode.pDependencies) data->args.hipGraphAddKernelNode.pDependencies__val = *(data->args.hipGraphAddKernelNode.pDependencies); + if (data->args.hipGraphAddKernelNode.pNodeParams) data->args.hipGraphAddKernelNode.pNodeParams__val = *(data->args.hipGraphAddKernelNode.pNodeParams); + break; +// hipGraphAddMemAllocNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('hipMemAllocNodeParams*', 'pNodeParams')] + case HIP_API_ID_hipGraphAddMemAllocNode: + if (data->args.hipGraphAddMemAllocNode.pGraphNode) data->args.hipGraphAddMemAllocNode.pGraphNode__val = *(data->args.hipGraphAddMemAllocNode.pGraphNode); + if (data->args.hipGraphAddMemAllocNode.pDependencies) data->args.hipGraphAddMemAllocNode.pDependencies__val = *(data->args.hipGraphAddMemAllocNode.pDependencies); + if (data->args.hipGraphAddMemAllocNode.pNodeParams) data->args.hipGraphAddMemAllocNode.pNodeParams__val = *(data->args.hipGraphAddMemAllocNode.pNodeParams); + break; +// hipGraphAddMemFreeNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('void*', 'dev_ptr')] + case HIP_API_ID_hipGraphAddMemFreeNode: + if (data->args.hipGraphAddMemFreeNode.pGraphNode) data->args.hipGraphAddMemFreeNode.pGraphNode__val = *(data->args.hipGraphAddMemFreeNode.pGraphNode); + if (data->args.hipGraphAddMemFreeNode.pDependencies) data->args.hipGraphAddMemFreeNode.pDependencies__val = *(data->args.hipGraphAddMemFreeNode.pDependencies); + break; +// hipGraphAddMemcpyNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('const hipMemcpy3DParms*', 'pCopyParams')] + case HIP_API_ID_hipGraphAddMemcpyNode: + if (data->args.hipGraphAddMemcpyNode.pGraphNode) data->args.hipGraphAddMemcpyNode.pGraphNode__val = *(data->args.hipGraphAddMemcpyNode.pGraphNode); + if (data->args.hipGraphAddMemcpyNode.pDependencies) data->args.hipGraphAddMemcpyNode.pDependencies__val = *(data->args.hipGraphAddMemcpyNode.pDependencies); + if (data->args.hipGraphAddMemcpyNode.pCopyParams) data->args.hipGraphAddMemcpyNode.pCopyParams__val = *(data->args.hipGraphAddMemcpyNode.pCopyParams); + break; +// hipGraphAddMemcpyNode1D[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('void*', 'dst'), ('const void*', 'src'), ('size_t', 'count'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipGraphAddMemcpyNode1D: + if (data->args.hipGraphAddMemcpyNode1D.pGraphNode) data->args.hipGraphAddMemcpyNode1D.pGraphNode__val = *(data->args.hipGraphAddMemcpyNode1D.pGraphNode); + if (data->args.hipGraphAddMemcpyNode1D.pDependencies) data->args.hipGraphAddMemcpyNode1D.pDependencies__val = *(data->args.hipGraphAddMemcpyNode1D.pDependencies); + break; +// hipGraphAddMemcpyNodeFromSymbol[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('void*', 'dst'), ('const void*', 'symbol'), ('size_t', 'count'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipGraphAddMemcpyNodeFromSymbol: + if (data->args.hipGraphAddMemcpyNodeFromSymbol.pGraphNode) data->args.hipGraphAddMemcpyNodeFromSymbol.pGraphNode__val = *(data->args.hipGraphAddMemcpyNodeFromSymbol.pGraphNode); + if (data->args.hipGraphAddMemcpyNodeFromSymbol.pDependencies) data->args.hipGraphAddMemcpyNodeFromSymbol.pDependencies__val = *(data->args.hipGraphAddMemcpyNodeFromSymbol.pDependencies); + break; +// hipGraphAddMemcpyNodeToSymbol[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('const void*', 'symbol'), ('const void*', 'src'), ('size_t', 'count'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipGraphAddMemcpyNodeToSymbol: + if (data->args.hipGraphAddMemcpyNodeToSymbol.pGraphNode) data->args.hipGraphAddMemcpyNodeToSymbol.pGraphNode__val = *(data->args.hipGraphAddMemcpyNodeToSymbol.pGraphNode); + if (data->args.hipGraphAddMemcpyNodeToSymbol.pDependencies) data->args.hipGraphAddMemcpyNodeToSymbol.pDependencies__val = *(data->args.hipGraphAddMemcpyNodeToSymbol.pDependencies); + break; +// hipGraphAddMemsetNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('const hipMemsetParams*', 'pMemsetParams')] + case HIP_API_ID_hipGraphAddMemsetNode: + if (data->args.hipGraphAddMemsetNode.pGraphNode) data->args.hipGraphAddMemsetNode.pGraphNode__val = *(data->args.hipGraphAddMemsetNode.pGraphNode); + if (data->args.hipGraphAddMemsetNode.pDependencies) data->args.hipGraphAddMemsetNode.pDependencies__val = *(data->args.hipGraphAddMemsetNode.pDependencies); + if (data->args.hipGraphAddMemsetNode.pMemsetParams) data->args.hipGraphAddMemsetNode.pMemsetParams__val = *(data->args.hipGraphAddMemsetNode.pMemsetParams); + break; +// hipGraphAddNode[('hipGraphNode_t*', 'pGraphNode'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'pDependencies'), ('size_t', 'numDependencies'), ('hipGraphNodeParams*', 'nodeParams')] + case HIP_API_ID_hipGraphAddNode: + if (data->args.hipGraphAddNode.pGraphNode) data->args.hipGraphAddNode.pGraphNode__val = *(data->args.hipGraphAddNode.pGraphNode); + if (data->args.hipGraphAddNode.pDependencies) data->args.hipGraphAddNode.pDependencies__val = *(data->args.hipGraphAddNode.pDependencies); + if (data->args.hipGraphAddNode.nodeParams) data->args.hipGraphAddNode.nodeParams__val = *(data->args.hipGraphAddNode.nodeParams); + break; +// hipGraphChildGraphNodeGetGraph[('hipGraphNode_t', 'node'), ('hipGraph_t*', 'pGraph')] + case HIP_API_ID_hipGraphChildGraphNodeGetGraph: + if (data->args.hipGraphChildGraphNodeGetGraph.pGraph) data->args.hipGraphChildGraphNodeGetGraph.pGraph__val = *(data->args.hipGraphChildGraphNodeGetGraph.pGraph); + break; +// hipGraphClone[('hipGraph_t*', 'pGraphClone'), ('hipGraph_t', 'originalGraph')] + case HIP_API_ID_hipGraphClone: + if (data->args.hipGraphClone.pGraphClone) data->args.hipGraphClone.pGraphClone__val = *(data->args.hipGraphClone.pGraphClone); + break; +// hipGraphCreate[('hipGraph_t*', 'pGraph'), ('unsigned int', 'flags')] + case HIP_API_ID_hipGraphCreate: + if (data->args.hipGraphCreate.pGraph) data->args.hipGraphCreate.pGraph__val = *(data->args.hipGraphCreate.pGraph); + break; +// hipGraphDebugDotPrint[('hipGraph_t', 'graph'), ('const char*', 'path'), ('unsigned int', 'flags')] + case HIP_API_ID_hipGraphDebugDotPrint: + if (data->args.hipGraphDebugDotPrint.path) data->args.hipGraphDebugDotPrint.path__val = *(data->args.hipGraphDebugDotPrint.path); + break; +// hipGraphDestroy[('hipGraph_t', 'graph')] + case HIP_API_ID_hipGraphDestroy: + break; +// hipGraphDestroyNode[('hipGraphNode_t', 'node')] + case HIP_API_ID_hipGraphDestroyNode: + break; +// hipGraphEventRecordNodeGetEvent[('hipGraphNode_t', 'node'), ('hipEvent_t*', 'event_out')] + case HIP_API_ID_hipGraphEventRecordNodeGetEvent: + if (data->args.hipGraphEventRecordNodeGetEvent.event_out) data->args.hipGraphEventRecordNodeGetEvent.event_out__val = *(data->args.hipGraphEventRecordNodeGetEvent.event_out); + break; +// hipGraphEventRecordNodeSetEvent[('hipGraphNode_t', 'node'), ('hipEvent_t', 'event')] + case HIP_API_ID_hipGraphEventRecordNodeSetEvent: + break; +// hipGraphEventWaitNodeGetEvent[('hipGraphNode_t', 'node'), ('hipEvent_t*', 'event_out')] + case HIP_API_ID_hipGraphEventWaitNodeGetEvent: + if (data->args.hipGraphEventWaitNodeGetEvent.event_out) data->args.hipGraphEventWaitNodeGetEvent.event_out__val = *(data->args.hipGraphEventWaitNodeGetEvent.event_out); + break; +// hipGraphEventWaitNodeSetEvent[('hipGraphNode_t', 'node'), ('hipEvent_t', 'event')] + case HIP_API_ID_hipGraphEventWaitNodeSetEvent: + break; +// hipGraphExecChildGraphNodeSetParams[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('hipGraph_t', 'childGraph')] + case HIP_API_ID_hipGraphExecChildGraphNodeSetParams: + break; +// hipGraphExecDestroy[('hipGraphExec_t', 'graphExec')] + case HIP_API_ID_hipGraphExecDestroy: + break; +// hipGraphExecEventRecordNodeSetEvent[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'hNode'), ('hipEvent_t', 'event')] + case HIP_API_ID_hipGraphExecEventRecordNodeSetEvent: + break; +// hipGraphExecEventWaitNodeSetEvent[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'hNode'), ('hipEvent_t', 'event')] + case HIP_API_ID_hipGraphExecEventWaitNodeSetEvent: + break; +// hipGraphExecExternalSemaphoresSignalNodeSetParams[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'hNode'), ('const hipExternalSemaphoreSignalNodeParams*', 'nodeParams')] + case HIP_API_ID_hipGraphExecExternalSemaphoresSignalNodeSetParams: + if (data->args.hipGraphExecExternalSemaphoresSignalNodeSetParams.nodeParams) data->args.hipGraphExecExternalSemaphoresSignalNodeSetParams.nodeParams__val = *(data->args.hipGraphExecExternalSemaphoresSignalNodeSetParams.nodeParams); + break; +// hipGraphExecExternalSemaphoresWaitNodeSetParams[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'hNode'), ('const hipExternalSemaphoreWaitNodeParams*', 'nodeParams')] + case HIP_API_ID_hipGraphExecExternalSemaphoresWaitNodeSetParams: + if (data->args.hipGraphExecExternalSemaphoresWaitNodeSetParams.nodeParams) data->args.hipGraphExecExternalSemaphoresWaitNodeSetParams.nodeParams__val = *(data->args.hipGraphExecExternalSemaphoresWaitNodeSetParams.nodeParams); + break; +// hipGraphExecHostNodeSetParams[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('const hipHostNodeParams*', 'pNodeParams')] + case HIP_API_ID_hipGraphExecHostNodeSetParams: + if (data->args.hipGraphExecHostNodeSetParams.pNodeParams) data->args.hipGraphExecHostNodeSetParams.pNodeParams__val = *(data->args.hipGraphExecHostNodeSetParams.pNodeParams); + break; +// hipGraphExecKernelNodeSetParams[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('const hipKernelNodeParams*', 'pNodeParams')] + case HIP_API_ID_hipGraphExecKernelNodeSetParams: + if (data->args.hipGraphExecKernelNodeSetParams.pNodeParams) data->args.hipGraphExecKernelNodeSetParams.pNodeParams__val = *(data->args.hipGraphExecKernelNodeSetParams.pNodeParams); + break; +// hipGraphExecMemcpyNodeSetParams[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('hipMemcpy3DParms*', 'pNodeParams')] + case HIP_API_ID_hipGraphExecMemcpyNodeSetParams: + if (data->args.hipGraphExecMemcpyNodeSetParams.pNodeParams) data->args.hipGraphExecMemcpyNodeSetParams.pNodeParams__val = *(data->args.hipGraphExecMemcpyNodeSetParams.pNodeParams); + break; +// hipGraphExecMemcpyNodeSetParams1D[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('void*', 'dst'), ('const void*', 'src'), ('size_t', 'count'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipGraphExecMemcpyNodeSetParams1D: + break; +// hipGraphExecMemcpyNodeSetParamsFromSymbol[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('void*', 'dst'), ('const void*', 'symbol'), ('size_t', 'count'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipGraphExecMemcpyNodeSetParamsFromSymbol: + break; +// hipGraphExecMemcpyNodeSetParamsToSymbol[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('const void*', 'symbol'), ('const void*', 'src'), ('size_t', 'count'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipGraphExecMemcpyNodeSetParamsToSymbol: + break; +// hipGraphExecMemsetNodeSetParams[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'node'), ('const hipMemsetParams*', 'pNodeParams')] + case HIP_API_ID_hipGraphExecMemsetNodeSetParams: + if (data->args.hipGraphExecMemsetNodeSetParams.pNodeParams) data->args.hipGraphExecMemsetNodeSetParams.pNodeParams__val = *(data->args.hipGraphExecMemsetNodeSetParams.pNodeParams); + break; +// hipGraphExecUpdate[('hipGraphExec_t', 'hGraphExec'), ('hipGraph_t', 'hGraph'), ('hipGraphNode_t*', 'hErrorNode_out'), ('hipGraphExecUpdateResult*', 'updateResult_out')] + case HIP_API_ID_hipGraphExecUpdate: + if (data->args.hipGraphExecUpdate.hErrorNode_out) data->args.hipGraphExecUpdate.hErrorNode_out__val = *(data->args.hipGraphExecUpdate.hErrorNode_out); + if (data->args.hipGraphExecUpdate.updateResult_out) data->args.hipGraphExecUpdate.updateResult_out__val = *(data->args.hipGraphExecUpdate.updateResult_out); + break; +// hipGraphExternalSemaphoresSignalNodeGetParams[('hipGraphNode_t', 'hNode'), ('hipExternalSemaphoreSignalNodeParams*', 'params_out')] + case HIP_API_ID_hipGraphExternalSemaphoresSignalNodeGetParams: + if (data->args.hipGraphExternalSemaphoresSignalNodeGetParams.params_out) data->args.hipGraphExternalSemaphoresSignalNodeGetParams.params_out__val = *(data->args.hipGraphExternalSemaphoresSignalNodeGetParams.params_out); + break; +// hipGraphExternalSemaphoresSignalNodeSetParams[('hipGraphNode_t', 'hNode'), ('const hipExternalSemaphoreSignalNodeParams*', 'nodeParams')] + case HIP_API_ID_hipGraphExternalSemaphoresSignalNodeSetParams: + if (data->args.hipGraphExternalSemaphoresSignalNodeSetParams.nodeParams) data->args.hipGraphExternalSemaphoresSignalNodeSetParams.nodeParams__val = *(data->args.hipGraphExternalSemaphoresSignalNodeSetParams.nodeParams); + break; +// hipGraphExternalSemaphoresWaitNodeGetParams[('hipGraphNode_t', 'hNode'), ('hipExternalSemaphoreWaitNodeParams*', 'params_out')] + case HIP_API_ID_hipGraphExternalSemaphoresWaitNodeGetParams: + if (data->args.hipGraphExternalSemaphoresWaitNodeGetParams.params_out) data->args.hipGraphExternalSemaphoresWaitNodeGetParams.params_out__val = *(data->args.hipGraphExternalSemaphoresWaitNodeGetParams.params_out); + break; +// hipGraphExternalSemaphoresWaitNodeSetParams[('hipGraphNode_t', 'hNode'), ('const hipExternalSemaphoreWaitNodeParams*', 'nodeParams')] + case HIP_API_ID_hipGraphExternalSemaphoresWaitNodeSetParams: + if (data->args.hipGraphExternalSemaphoresWaitNodeSetParams.nodeParams) data->args.hipGraphExternalSemaphoresWaitNodeSetParams.nodeParams__val = *(data->args.hipGraphExternalSemaphoresWaitNodeSetParams.nodeParams); + break; +// hipGraphGetEdges[('hipGraph_t', 'graph'), ('hipGraphNode_t*', 'from'), ('hipGraphNode_t*', 'to'), ('size_t*', 'numEdges')] + case HIP_API_ID_hipGraphGetEdges: + if (data->args.hipGraphGetEdges.from) data->args.hipGraphGetEdges.from__val = *(data->args.hipGraphGetEdges.from); + if (data->args.hipGraphGetEdges.to) data->args.hipGraphGetEdges.to__val = *(data->args.hipGraphGetEdges.to); + if (data->args.hipGraphGetEdges.numEdges) data->args.hipGraphGetEdges.numEdges__val = *(data->args.hipGraphGetEdges.numEdges); + break; +// hipGraphGetNodes[('hipGraph_t', 'graph'), ('hipGraphNode_t*', 'nodes'), ('size_t*', 'numNodes')] + case HIP_API_ID_hipGraphGetNodes: + if (data->args.hipGraphGetNodes.nodes) data->args.hipGraphGetNodes.nodes__val = *(data->args.hipGraphGetNodes.nodes); + if (data->args.hipGraphGetNodes.numNodes) data->args.hipGraphGetNodes.numNodes__val = *(data->args.hipGraphGetNodes.numNodes); + break; +// hipGraphGetRootNodes[('hipGraph_t', 'graph'), ('hipGraphNode_t*', 'pRootNodes'), ('size_t*', 'pNumRootNodes')] + case HIP_API_ID_hipGraphGetRootNodes: + if (data->args.hipGraphGetRootNodes.pRootNodes) data->args.hipGraphGetRootNodes.pRootNodes__val = *(data->args.hipGraphGetRootNodes.pRootNodes); + if (data->args.hipGraphGetRootNodes.pNumRootNodes) data->args.hipGraphGetRootNodes.pNumRootNodes__val = *(data->args.hipGraphGetRootNodes.pNumRootNodes); + break; +// hipGraphHostNodeGetParams[('hipGraphNode_t', 'node'), ('hipHostNodeParams*', 'pNodeParams')] + case HIP_API_ID_hipGraphHostNodeGetParams: + if (data->args.hipGraphHostNodeGetParams.pNodeParams) data->args.hipGraphHostNodeGetParams.pNodeParams__val = *(data->args.hipGraphHostNodeGetParams.pNodeParams); + break; +// hipGraphHostNodeSetParams[('hipGraphNode_t', 'node'), ('const hipHostNodeParams*', 'pNodeParams')] + case HIP_API_ID_hipGraphHostNodeSetParams: + if (data->args.hipGraphHostNodeSetParams.pNodeParams) data->args.hipGraphHostNodeSetParams.pNodeParams__val = *(data->args.hipGraphHostNodeSetParams.pNodeParams); + break; +// hipGraphInstantiate[('hipGraphExec_t*', 'pGraphExec'), ('hipGraph_t', 'graph'), ('hipGraphNode_t*', 'pErrorNode'), ('char*', 'pLogBuffer'), ('size_t', 'bufferSize')] + case HIP_API_ID_hipGraphInstantiate: + if (data->args.hipGraphInstantiate.pGraphExec) data->args.hipGraphInstantiate.pGraphExec__val = *(data->args.hipGraphInstantiate.pGraphExec); + if (data->args.hipGraphInstantiate.pErrorNode) data->args.hipGraphInstantiate.pErrorNode__val = *(data->args.hipGraphInstantiate.pErrorNode); + data->args.hipGraphInstantiate.pLogBuffer = (data->args.hipGraphInstantiate.pLogBuffer) ? strdup(data->args.hipGraphInstantiate.pLogBuffer) : NULL; + break; +// hipGraphInstantiateWithFlags[('hipGraphExec_t*', 'pGraphExec'), ('hipGraph_t', 'graph'), ('unsigned long long', 'flags')] + case HIP_API_ID_hipGraphInstantiateWithFlags: + if (data->args.hipGraphInstantiateWithFlags.pGraphExec) data->args.hipGraphInstantiateWithFlags.pGraphExec__val = *(data->args.hipGraphInstantiateWithFlags.pGraphExec); + break; +// hipGraphInstantiateWithParams[('hipGraphExec_t*', 'pGraphExec'), ('hipGraph_t', 'graph'), ('hipGraphInstantiateParams*', 'instantiateParams')] + case HIP_API_ID_hipGraphInstantiateWithParams: + if (data->args.hipGraphInstantiateWithParams.pGraphExec) data->args.hipGraphInstantiateWithParams.pGraphExec__val = *(data->args.hipGraphInstantiateWithParams.pGraphExec); + if (data->args.hipGraphInstantiateWithParams.instantiateParams) data->args.hipGraphInstantiateWithParams.instantiateParams__val = *(data->args.hipGraphInstantiateWithParams.instantiateParams); + break; +// hipGraphKernelNodeCopyAttributes[('hipGraphNode_t', 'hSrc'), ('hipGraphNode_t', 'hDst')] + case HIP_API_ID_hipGraphKernelNodeCopyAttributes: + break; +// hipGraphKernelNodeGetAttribute[('hipGraphNode_t', 'hNode'), ('hipLaunchAttributeID', 'attr'), ('hipLaunchAttributeValue*', 'value')] + case HIP_API_ID_hipGraphKernelNodeGetAttribute: + if (data->args.hipGraphKernelNodeGetAttribute.value) data->args.hipGraphKernelNodeGetAttribute.value__val = *(data->args.hipGraphKernelNodeGetAttribute.value); + break; +// hipGraphKernelNodeGetParams[('hipGraphNode_t', 'node'), ('hipKernelNodeParams*', 'pNodeParams')] + case HIP_API_ID_hipGraphKernelNodeGetParams: + if (data->args.hipGraphKernelNodeGetParams.pNodeParams) data->args.hipGraphKernelNodeGetParams.pNodeParams__val = *(data->args.hipGraphKernelNodeGetParams.pNodeParams); + break; +// hipGraphKernelNodeSetAttribute[('hipGraphNode_t', 'hNode'), ('hipLaunchAttributeID', 'attr'), ('const hipLaunchAttributeValue*', 'value')] + case HIP_API_ID_hipGraphKernelNodeSetAttribute: + if (data->args.hipGraphKernelNodeSetAttribute.value) data->args.hipGraphKernelNodeSetAttribute.value__val = *(data->args.hipGraphKernelNodeSetAttribute.value); + break; +// hipGraphKernelNodeSetParams[('hipGraphNode_t', 'node'), ('const hipKernelNodeParams*', 'pNodeParams')] + case HIP_API_ID_hipGraphKernelNodeSetParams: + if (data->args.hipGraphKernelNodeSetParams.pNodeParams) data->args.hipGraphKernelNodeSetParams.pNodeParams__val = *(data->args.hipGraphKernelNodeSetParams.pNodeParams); + break; +// hipGraphLaunch[('hipGraphExec_t', 'graphExec'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipGraphLaunch: + break; +// hipGraphMemAllocNodeGetParams[('hipGraphNode_t', 'node'), ('hipMemAllocNodeParams*', 'pNodeParams')] + case HIP_API_ID_hipGraphMemAllocNodeGetParams: + if (data->args.hipGraphMemAllocNodeGetParams.pNodeParams) data->args.hipGraphMemAllocNodeGetParams.pNodeParams__val = *(data->args.hipGraphMemAllocNodeGetParams.pNodeParams); + break; +// hipGraphMemFreeNodeGetParams[('hipGraphNode_t', 'node'), ('void*', 'dev_ptr')] + case HIP_API_ID_hipGraphMemFreeNodeGetParams: + break; +// hipGraphMemcpyNodeGetParams[('hipGraphNode_t', 'node'), ('hipMemcpy3DParms*', 'pNodeParams')] + case HIP_API_ID_hipGraphMemcpyNodeGetParams: + if (data->args.hipGraphMemcpyNodeGetParams.pNodeParams) data->args.hipGraphMemcpyNodeGetParams.pNodeParams__val = *(data->args.hipGraphMemcpyNodeGetParams.pNodeParams); + break; +// hipGraphMemcpyNodeSetParams[('hipGraphNode_t', 'node'), ('const hipMemcpy3DParms*', 'pNodeParams')] + case HIP_API_ID_hipGraphMemcpyNodeSetParams: + if (data->args.hipGraphMemcpyNodeSetParams.pNodeParams) data->args.hipGraphMemcpyNodeSetParams.pNodeParams__val = *(data->args.hipGraphMemcpyNodeSetParams.pNodeParams); + break; +// hipGraphMemcpyNodeSetParams1D[('hipGraphNode_t', 'node'), ('void*', 'dst'), ('const void*', 'src'), ('size_t', 'count'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipGraphMemcpyNodeSetParams1D: + break; +// hipGraphMemcpyNodeSetParamsFromSymbol[('hipGraphNode_t', 'node'), ('void*', 'dst'), ('const void*', 'symbol'), ('size_t', 'count'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipGraphMemcpyNodeSetParamsFromSymbol: + break; +// hipGraphMemcpyNodeSetParamsToSymbol[('hipGraphNode_t', 'node'), ('const void*', 'symbol'), ('const void*', 'src'), ('size_t', 'count'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipGraphMemcpyNodeSetParamsToSymbol: + break; +// hipGraphMemsetNodeGetParams[('hipGraphNode_t', 'node'), ('hipMemsetParams*', 'pNodeParams')] + case HIP_API_ID_hipGraphMemsetNodeGetParams: + if (data->args.hipGraphMemsetNodeGetParams.pNodeParams) data->args.hipGraphMemsetNodeGetParams.pNodeParams__val = *(data->args.hipGraphMemsetNodeGetParams.pNodeParams); + break; +// hipGraphMemsetNodeSetParams[('hipGraphNode_t', 'node'), ('const hipMemsetParams*', 'pNodeParams')] + case HIP_API_ID_hipGraphMemsetNodeSetParams: + if (data->args.hipGraphMemsetNodeSetParams.pNodeParams) data->args.hipGraphMemsetNodeSetParams.pNodeParams__val = *(data->args.hipGraphMemsetNodeSetParams.pNodeParams); + break; +// hipGraphNodeFindInClone[('hipGraphNode_t*', 'pNode'), ('hipGraphNode_t', 'originalNode'), ('hipGraph_t', 'clonedGraph')] + case HIP_API_ID_hipGraphNodeFindInClone: + if (data->args.hipGraphNodeFindInClone.pNode) data->args.hipGraphNodeFindInClone.pNode__val = *(data->args.hipGraphNodeFindInClone.pNode); + break; +// hipGraphNodeGetDependencies[('hipGraphNode_t', 'node'), ('hipGraphNode_t*', 'pDependencies'), ('size_t*', 'pNumDependencies')] + case HIP_API_ID_hipGraphNodeGetDependencies: + if (data->args.hipGraphNodeGetDependencies.pDependencies) data->args.hipGraphNodeGetDependencies.pDependencies__val = *(data->args.hipGraphNodeGetDependencies.pDependencies); + if (data->args.hipGraphNodeGetDependencies.pNumDependencies) data->args.hipGraphNodeGetDependencies.pNumDependencies__val = *(data->args.hipGraphNodeGetDependencies.pNumDependencies); + break; +// hipGraphNodeGetDependentNodes[('hipGraphNode_t', 'node'), ('hipGraphNode_t*', 'pDependentNodes'), ('size_t*', 'pNumDependentNodes')] + case HIP_API_ID_hipGraphNodeGetDependentNodes: + if (data->args.hipGraphNodeGetDependentNodes.pDependentNodes) data->args.hipGraphNodeGetDependentNodes.pDependentNodes__val = *(data->args.hipGraphNodeGetDependentNodes.pDependentNodes); + if (data->args.hipGraphNodeGetDependentNodes.pNumDependentNodes) data->args.hipGraphNodeGetDependentNodes.pNumDependentNodes__val = *(data->args.hipGraphNodeGetDependentNodes.pNumDependentNodes); + break; +// hipGraphNodeGetEnabled[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'hNode'), ('unsigned int*', 'isEnabled')] + case HIP_API_ID_hipGraphNodeGetEnabled: + if (data->args.hipGraphNodeGetEnabled.isEnabled) data->args.hipGraphNodeGetEnabled.isEnabled__val = *(data->args.hipGraphNodeGetEnabled.isEnabled); + break; +// hipGraphNodeGetType[('hipGraphNode_t', 'node'), ('hipGraphNodeType*', 'pType')] + case HIP_API_ID_hipGraphNodeGetType: + if (data->args.hipGraphNodeGetType.pType) data->args.hipGraphNodeGetType.pType__val = *(data->args.hipGraphNodeGetType.pType); + break; +// hipGraphNodeSetEnabled[('hipGraphExec_t', 'hGraphExec'), ('hipGraphNode_t', 'hNode'), ('unsigned int', 'isEnabled')] + case HIP_API_ID_hipGraphNodeSetEnabled: + break; +// hipGraphReleaseUserObject[('hipGraph_t', 'graph'), ('hipUserObject_t', 'object'), ('unsigned int', 'count')] + case HIP_API_ID_hipGraphReleaseUserObject: + break; +// hipGraphRemoveDependencies[('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'from'), ('const hipGraphNode_t*', 'to'), ('size_t', 'numDependencies')] + case HIP_API_ID_hipGraphRemoveDependencies: + if (data->args.hipGraphRemoveDependencies.from) data->args.hipGraphRemoveDependencies.from__val = *(data->args.hipGraphRemoveDependencies.from); + if (data->args.hipGraphRemoveDependencies.to) data->args.hipGraphRemoveDependencies.to__val = *(data->args.hipGraphRemoveDependencies.to); + break; +// hipGraphRetainUserObject[('hipGraph_t', 'graph'), ('hipUserObject_t', 'object'), ('unsigned int', 'count'), ('unsigned int', 'flags')] + case HIP_API_ID_hipGraphRetainUserObject: + break; +// hipGraphUpload[('hipGraphExec_t', 'graphExec'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipGraphUpload: + break; +// hipGraphicsGLRegisterBuffer[('hipGraphicsResource**', 'resource'), ('GLuint', 'buffer'), ('unsigned int', 'flags')] + case HIP_API_ID_hipGraphicsGLRegisterBuffer: + if (data->args.hipGraphicsGLRegisterBuffer.resource) data->args.hipGraphicsGLRegisterBuffer.resource__val = *(data->args.hipGraphicsGLRegisterBuffer.resource); + break; +// hipGraphicsGLRegisterImage[('hipGraphicsResource**', 'resource'), ('GLuint', 'image'), ('GLenum', 'target'), ('unsigned int', 'flags')] + case HIP_API_ID_hipGraphicsGLRegisterImage: + if (data->args.hipGraphicsGLRegisterImage.resource) data->args.hipGraphicsGLRegisterImage.resource__val = *(data->args.hipGraphicsGLRegisterImage.resource); + break; +// hipGraphicsMapResources[('int', 'count'), ('hipGraphicsResource_t*', 'resources'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipGraphicsMapResources: + if (data->args.hipGraphicsMapResources.resources) data->args.hipGraphicsMapResources.resources__val = *(data->args.hipGraphicsMapResources.resources); + break; +// hipGraphicsResourceGetMappedPointer[('void**', 'devPtr'), ('size_t*', 'size'), ('hipGraphicsResource_t', 'resource')] + case HIP_API_ID_hipGraphicsResourceGetMappedPointer: + if (data->args.hipGraphicsResourceGetMappedPointer.devPtr) data->args.hipGraphicsResourceGetMappedPointer.devPtr__val = *(data->args.hipGraphicsResourceGetMappedPointer.devPtr); + if (data->args.hipGraphicsResourceGetMappedPointer.size) data->args.hipGraphicsResourceGetMappedPointer.size__val = *(data->args.hipGraphicsResourceGetMappedPointer.size); + break; +// hipGraphicsSubResourceGetMappedArray[('hipArray_t*', 'array'), ('hipGraphicsResource_t', 'resource'), ('unsigned int', 'arrayIndex'), ('unsigned int', 'mipLevel')] + case HIP_API_ID_hipGraphicsSubResourceGetMappedArray: + if (data->args.hipGraphicsSubResourceGetMappedArray.array) data->args.hipGraphicsSubResourceGetMappedArray.array__val = *(data->args.hipGraphicsSubResourceGetMappedArray.array); + break; +// hipGraphicsUnmapResources[('int', 'count'), ('hipGraphicsResource_t*', 'resources'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipGraphicsUnmapResources: + if (data->args.hipGraphicsUnmapResources.resources) data->args.hipGraphicsUnmapResources.resources__val = *(data->args.hipGraphicsUnmapResources.resources); + break; +// hipGraphicsUnregisterResource[('hipGraphicsResource_t', 'resource')] + case HIP_API_ID_hipGraphicsUnregisterResource: + break; +// hipHccModuleLaunchKernel[('hipFunction_t', 'f'), ('unsigned int', 'globalWorkSizeX'), ('unsigned int', 'globalWorkSizeY'), ('unsigned int', 'globalWorkSizeZ'), ('unsigned int', 'blockDimX'), ('unsigned int', 'blockDimY'), ('unsigned int', 'blockDimZ'), ('size_t', 'sharedMemBytes'), ('hipStream_t', 'hStream'), ('void**', 'kernelParams'), ('void**', 'extra'), ('hipEvent_t', 'startEvent'), ('hipEvent_t', 'stopEvent')] + case HIP_API_ID_hipHccModuleLaunchKernel: + if (data->args.hipHccModuleLaunchKernel.kernelParams) data->args.hipHccModuleLaunchKernel.kernelParams__val = *(data->args.hipHccModuleLaunchKernel.kernelParams); + if (data->args.hipHccModuleLaunchKernel.extra) data->args.hipHccModuleLaunchKernel.extra__val = *(data->args.hipHccModuleLaunchKernel.extra); + break; +// hipHostAlloc[('void**', 'ptr'), ('size_t', 'size'), ('unsigned int', 'flags')] + case HIP_API_ID_hipHostAlloc: + if (data->args.hipHostAlloc.ptr) data->args.hipHostAlloc.ptr__val = *(data->args.hipHostAlloc.ptr); + break; +// hipHostFree[('void*', 'ptr')] + case HIP_API_ID_hipHostFree: + break; +// hipHostGetDevicePointer[('void**', 'devPtr'), ('void*', 'hstPtr'), ('unsigned int', 'flags')] + case HIP_API_ID_hipHostGetDevicePointer: + if (data->args.hipHostGetDevicePointer.devPtr) data->args.hipHostGetDevicePointer.devPtr__val = *(data->args.hipHostGetDevicePointer.devPtr); + break; +// hipHostGetFlags[('unsigned int*', 'flagsPtr'), ('void*', 'hostPtr')] + case HIP_API_ID_hipHostGetFlags: + if (data->args.hipHostGetFlags.flagsPtr) data->args.hipHostGetFlags.flagsPtr__val = *(data->args.hipHostGetFlags.flagsPtr); + break; +// hipHostMalloc[('void**', 'ptr'), ('size_t', 'size'), ('unsigned int', 'flags')] + case HIP_API_ID_hipHostMalloc: + if (data->args.hipHostMalloc.ptr) data->args.hipHostMalloc.ptr__val = *(data->args.hipHostMalloc.ptr); + break; +// hipHostRegister[('void*', 'hostPtr'), ('size_t', 'sizeBytes'), ('unsigned int', 'flags')] + case HIP_API_ID_hipHostRegister: + break; +// hipHostUnregister[('void*', 'hostPtr')] + case HIP_API_ID_hipHostUnregister: + break; +// hipImportExternalMemory[('hipExternalMemory_t*', 'extMem_out'), ('const hipExternalMemoryHandleDesc*', 'memHandleDesc')] + case HIP_API_ID_hipImportExternalMemory: + if (data->args.hipImportExternalMemory.extMem_out) data->args.hipImportExternalMemory.extMem_out__val = *(data->args.hipImportExternalMemory.extMem_out); + if (data->args.hipImportExternalMemory.memHandleDesc) data->args.hipImportExternalMemory.memHandleDesc__val = *(data->args.hipImportExternalMemory.memHandleDesc); + break; +// hipImportExternalSemaphore[('hipExternalSemaphore_t*', 'extSem_out'), ('const hipExternalSemaphoreHandleDesc*', 'semHandleDesc')] + case HIP_API_ID_hipImportExternalSemaphore: + if (data->args.hipImportExternalSemaphore.extSem_out) data->args.hipImportExternalSemaphore.extSem_out__val = *(data->args.hipImportExternalSemaphore.extSem_out); + if (data->args.hipImportExternalSemaphore.semHandleDesc) data->args.hipImportExternalSemaphore.semHandleDesc__val = *(data->args.hipImportExternalSemaphore.semHandleDesc); + break; +// hipInit[('unsigned int', 'flags')] + case HIP_API_ID_hipInit: + break; +// hipIpcCloseMemHandle[('void*', 'devPtr')] + case HIP_API_ID_hipIpcCloseMemHandle: + break; +// hipIpcGetEventHandle[('hipIpcEventHandle_t*', 'handle'), ('hipEvent_t', 'event')] + case HIP_API_ID_hipIpcGetEventHandle: + if (data->args.hipIpcGetEventHandle.handle) data->args.hipIpcGetEventHandle.handle__val = *(data->args.hipIpcGetEventHandle.handle); + break; +// hipIpcGetMemHandle[('hipIpcMemHandle_t*', 'handle'), ('void*', 'devPtr')] + case HIP_API_ID_hipIpcGetMemHandle: + if (data->args.hipIpcGetMemHandle.handle) data->args.hipIpcGetMemHandle.handle__val = *(data->args.hipIpcGetMemHandle.handle); + break; +// hipIpcOpenEventHandle[('hipEvent_t*', 'event'), ('hipIpcEventHandle_t', 'handle')] + case HIP_API_ID_hipIpcOpenEventHandle: + if (data->args.hipIpcOpenEventHandle.event) data->args.hipIpcOpenEventHandle.event__val = *(data->args.hipIpcOpenEventHandle.event); + break; +// hipIpcOpenMemHandle[('void**', 'devPtr'), ('hipIpcMemHandle_t', 'handle'), ('unsigned int', 'flags')] + case HIP_API_ID_hipIpcOpenMemHandle: + if (data->args.hipIpcOpenMemHandle.devPtr) data->args.hipIpcOpenMemHandle.devPtr__val = *(data->args.hipIpcOpenMemHandle.devPtr); + break; +// hipLaunchByPtr[('const void*', 'hostFunction')] + case HIP_API_ID_hipLaunchByPtr: + break; +// hipLaunchCooperativeKernel[('const void*', 'f'), ('dim3', 'gridDim'), ('dim3', 'blockDimX'), ('void**', 'kernelParams'), ('unsigned int', 'sharedMemBytes'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipLaunchCooperativeKernel: + if (data->args.hipLaunchCooperativeKernel.kernelParams) data->args.hipLaunchCooperativeKernel.kernelParams__val = *(data->args.hipLaunchCooperativeKernel.kernelParams); + break; +// hipLaunchCooperativeKernelMultiDevice[('hipLaunchParams*', 'launchParamsList'), ('int', 'numDevices'), ('unsigned int', 'flags')] + case HIP_API_ID_hipLaunchCooperativeKernelMultiDevice: + if (data->args.hipLaunchCooperativeKernelMultiDevice.launchParamsList) data->args.hipLaunchCooperativeKernelMultiDevice.launchParamsList__val = *(data->args.hipLaunchCooperativeKernelMultiDevice.launchParamsList); + break; +// hipLaunchHostFunc[('hipStream_t', 'stream'), ('hipHostFn_t', 'fn'), ('void*', 'userData')] + case HIP_API_ID_hipLaunchHostFunc: + break; +// hipLaunchKernel[('const void*', 'function_address'), ('dim3', 'numBlocks'), ('dim3', 'dimBlocks'), ('void**', 'args'), ('size_t', 'sharedMemBytes'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipLaunchKernel: + if (data->args.hipLaunchKernel.args) data->args.hipLaunchKernel.args__val = *(data->args.hipLaunchKernel.args); + break; +// hipMalloc[('void**', 'ptr'), ('size_t', 'size')] + case HIP_API_ID_hipMalloc: + if (data->args.hipMalloc.ptr) data->args.hipMalloc.ptr__val = *(data->args.hipMalloc.ptr); + break; +// hipMalloc3D[('hipPitchedPtr*', 'pitchedDevPtr'), ('hipExtent', 'extent')] + case HIP_API_ID_hipMalloc3D: + if (data->args.hipMalloc3D.pitchedDevPtr) data->args.hipMalloc3D.pitchedDevPtr__val = *(data->args.hipMalloc3D.pitchedDevPtr); + break; +// hipMalloc3DArray[('hipArray_t*', 'array'), ('const hipChannelFormatDesc*', 'desc'), ('hipExtent', 'extent'), ('unsigned int', 'flags')] + case HIP_API_ID_hipMalloc3DArray: + if (data->args.hipMalloc3DArray.array) data->args.hipMalloc3DArray.array__val = *(data->args.hipMalloc3DArray.array); + if (data->args.hipMalloc3DArray.desc) data->args.hipMalloc3DArray.desc__val = *(data->args.hipMalloc3DArray.desc); + break; +// hipMallocArray[('hipArray_t*', 'array'), ('const hipChannelFormatDesc*', 'desc'), ('size_t', 'width'), ('size_t', 'height'), ('unsigned int', 'flags')] + case HIP_API_ID_hipMallocArray: + if (data->args.hipMallocArray.array) data->args.hipMallocArray.array__val = *(data->args.hipMallocArray.array); + if (data->args.hipMallocArray.desc) data->args.hipMallocArray.desc__val = *(data->args.hipMallocArray.desc); + break; +// hipMallocAsync[('void**', 'dev_ptr'), ('size_t', 'size'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMallocAsync: + if (data->args.hipMallocAsync.dev_ptr) data->args.hipMallocAsync.dev_ptr__val = *(data->args.hipMallocAsync.dev_ptr); + break; +// hipMallocFromPoolAsync[('void**', 'dev_ptr'), ('size_t', 'size'), ('hipMemPool_t', 'mem_pool'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMallocFromPoolAsync: + if (data->args.hipMallocFromPoolAsync.dev_ptr) data->args.hipMallocFromPoolAsync.dev_ptr__val = *(data->args.hipMallocFromPoolAsync.dev_ptr); + break; +// hipMallocHost[('void**', 'ptr'), ('size_t', 'size')] + case HIP_API_ID_hipMallocHost: + if (data->args.hipMallocHost.ptr) data->args.hipMallocHost.ptr__val = *(data->args.hipMallocHost.ptr); + break; +// hipMallocManaged[('void**', 'dev_ptr'), ('size_t', 'size'), ('unsigned int', 'flags')] + case HIP_API_ID_hipMallocManaged: + if (data->args.hipMallocManaged.dev_ptr) data->args.hipMallocManaged.dev_ptr__val = *(data->args.hipMallocManaged.dev_ptr); + break; +// hipMallocMipmappedArray[('hipMipmappedArray_t*', 'mipmappedArray'), ('const hipChannelFormatDesc*', 'desc'), ('hipExtent', 'extent'), ('unsigned int', 'numLevels'), ('unsigned int', 'flags')] + case HIP_API_ID_hipMallocMipmappedArray: + if (data->args.hipMallocMipmappedArray.mipmappedArray) data->args.hipMallocMipmappedArray.mipmappedArray__val = *(data->args.hipMallocMipmappedArray.mipmappedArray); + if (data->args.hipMallocMipmappedArray.desc) data->args.hipMallocMipmappedArray.desc__val = *(data->args.hipMallocMipmappedArray.desc); + break; +// hipMallocPitch[('void**', 'ptr'), ('size_t*', 'pitch'), ('size_t', 'width'), ('size_t', 'height')] + case HIP_API_ID_hipMallocPitch: + if (data->args.hipMallocPitch.ptr) data->args.hipMallocPitch.ptr__val = *(data->args.hipMallocPitch.ptr); + if (data->args.hipMallocPitch.pitch) data->args.hipMallocPitch.pitch__val = *(data->args.hipMallocPitch.pitch); + break; +// hipMemAddressFree[('void*', 'devPtr'), ('size_t', 'size')] + case HIP_API_ID_hipMemAddressFree: + break; +// hipMemAddressReserve[('void**', 'ptr'), ('size_t', 'size'), ('size_t', 'alignment'), ('void*', 'addr'), ('unsigned long long', 'flags')] + case HIP_API_ID_hipMemAddressReserve: + if (data->args.hipMemAddressReserve.ptr) data->args.hipMemAddressReserve.ptr__val = *(data->args.hipMemAddressReserve.ptr); + break; +// hipMemAdvise[('const void*', 'dev_ptr'), ('size_t', 'count'), ('hipMemoryAdvise', 'advice'), ('int', 'device')] + case HIP_API_ID_hipMemAdvise: + break; +// hipMemAllocHost[('void**', 'ptr'), ('size_t', 'size')] + case HIP_API_ID_hipMemAllocHost: + if (data->args.hipMemAllocHost.ptr) data->args.hipMemAllocHost.ptr__val = *(data->args.hipMemAllocHost.ptr); + break; +// hipMemAllocPitch[('hipDeviceptr_t*', 'dptr'), ('size_t*', 'pitch'), ('size_t', 'widthInBytes'), ('size_t', 'height'), ('unsigned int', 'elementSizeBytes')] + case HIP_API_ID_hipMemAllocPitch: + if (data->args.hipMemAllocPitch.dptr) data->args.hipMemAllocPitch.dptr__val = *(data->args.hipMemAllocPitch.dptr); + if (data->args.hipMemAllocPitch.pitch) data->args.hipMemAllocPitch.pitch__val = *(data->args.hipMemAllocPitch.pitch); + break; +// hipMemCreate[('hipMemGenericAllocationHandle_t*', 'handle'), ('size_t', 'size'), ('const hipMemAllocationProp*', 'prop'), ('unsigned long long', 'flags')] + case HIP_API_ID_hipMemCreate: + if (data->args.hipMemCreate.handle) data->args.hipMemCreate.handle__val = *(data->args.hipMemCreate.handle); + if (data->args.hipMemCreate.prop) data->args.hipMemCreate.prop__val = *(data->args.hipMemCreate.prop); + break; +// hipMemExportToShareableHandle[('void*', 'shareableHandle'), ('hipMemGenericAllocationHandle_t', 'handle'), ('hipMemAllocationHandleType', 'handleType'), ('unsigned long long', 'flags')] + case HIP_API_ID_hipMemExportToShareableHandle: + break; +// hipMemGetAccess[('unsigned long long*', 'flags'), ('const hipMemLocation*', 'location'), ('void*', 'ptr')] + case HIP_API_ID_hipMemGetAccess: + if (data->args.hipMemGetAccess.flags) data->args.hipMemGetAccess.flags__val = *(data->args.hipMemGetAccess.flags); + if (data->args.hipMemGetAccess.location) data->args.hipMemGetAccess.location__val = *(data->args.hipMemGetAccess.location); + break; +// hipMemGetAddressRange[('hipDeviceptr_t*', 'pbase'), ('size_t*', 'psize'), ('hipDeviceptr_t', 'dptr')] + case HIP_API_ID_hipMemGetAddressRange: + if (data->args.hipMemGetAddressRange.pbase) data->args.hipMemGetAddressRange.pbase__val = *(data->args.hipMemGetAddressRange.pbase); + if (data->args.hipMemGetAddressRange.psize) data->args.hipMemGetAddressRange.psize__val = *(data->args.hipMemGetAddressRange.psize); + break; +// hipMemGetAllocationGranularity[('size_t*', 'granularity'), ('const hipMemAllocationProp*', 'prop'), ('hipMemAllocationGranularity_flags', 'option')] + case HIP_API_ID_hipMemGetAllocationGranularity: + if (data->args.hipMemGetAllocationGranularity.granularity) data->args.hipMemGetAllocationGranularity.granularity__val = *(data->args.hipMemGetAllocationGranularity.granularity); + if (data->args.hipMemGetAllocationGranularity.prop) data->args.hipMemGetAllocationGranularity.prop__val = *(data->args.hipMemGetAllocationGranularity.prop); + break; +// hipMemGetAllocationPropertiesFromHandle[('hipMemAllocationProp*', 'prop'), ('hipMemGenericAllocationHandle_t', 'handle')] + case HIP_API_ID_hipMemGetAllocationPropertiesFromHandle: + if (data->args.hipMemGetAllocationPropertiesFromHandle.prop) data->args.hipMemGetAllocationPropertiesFromHandle.prop__val = *(data->args.hipMemGetAllocationPropertiesFromHandle.prop); + break; +// hipMemGetInfo[('size_t*', 'free'), ('size_t*', 'total')] + case HIP_API_ID_hipMemGetInfo: + if (data->args.hipMemGetInfo.free) data->args.hipMemGetInfo.free__val = *(data->args.hipMemGetInfo.free); + if (data->args.hipMemGetInfo.total) data->args.hipMemGetInfo.total__val = *(data->args.hipMemGetInfo.total); + break; +// hipMemImportFromShareableHandle[('hipMemGenericAllocationHandle_t*', 'handle'), ('void*', 'osHandle'), ('hipMemAllocationHandleType', 'shHandleType')] + case HIP_API_ID_hipMemImportFromShareableHandle: + if (data->args.hipMemImportFromShareableHandle.handle) data->args.hipMemImportFromShareableHandle.handle__val = *(data->args.hipMemImportFromShareableHandle.handle); + break; +// hipMemMap[('void*', 'ptr'), ('size_t', 'size'), ('size_t', 'offset'), ('hipMemGenericAllocationHandle_t', 'handle'), ('unsigned long long', 'flags')] + case HIP_API_ID_hipMemMap: + break; +// hipMemMapArrayAsync[('hipArrayMapInfo*', 'mapInfoList'), ('unsigned int', 'count'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemMapArrayAsync: + if (data->args.hipMemMapArrayAsync.mapInfoList) data->args.hipMemMapArrayAsync.mapInfoList__val = *(data->args.hipMemMapArrayAsync.mapInfoList); + break; +// hipMemPoolCreate[('hipMemPool_t*', 'mem_pool'), ('const hipMemPoolProps*', 'pool_props')] + case HIP_API_ID_hipMemPoolCreate: + if (data->args.hipMemPoolCreate.mem_pool) data->args.hipMemPoolCreate.mem_pool__val = *(data->args.hipMemPoolCreate.mem_pool); + if (data->args.hipMemPoolCreate.pool_props) data->args.hipMemPoolCreate.pool_props__val = *(data->args.hipMemPoolCreate.pool_props); + break; +// hipMemPoolDestroy[('hipMemPool_t', 'mem_pool')] + case HIP_API_ID_hipMemPoolDestroy: + break; +// hipMemPoolExportPointer[('hipMemPoolPtrExportData*', 'export_data'), ('void*', 'dev_ptr')] + case HIP_API_ID_hipMemPoolExportPointer: + if (data->args.hipMemPoolExportPointer.export_data) data->args.hipMemPoolExportPointer.export_data__val = *(data->args.hipMemPoolExportPointer.export_data); + break; +// hipMemPoolExportToShareableHandle[('void*', 'shared_handle'), ('hipMemPool_t', 'mem_pool'), ('hipMemAllocationHandleType', 'handle_type'), ('unsigned int', 'flags')] + case HIP_API_ID_hipMemPoolExportToShareableHandle: + break; +// hipMemPoolGetAccess[('hipMemAccessFlags*', 'flags'), ('hipMemPool_t', 'mem_pool'), ('hipMemLocation*', 'location')] + case HIP_API_ID_hipMemPoolGetAccess: + if (data->args.hipMemPoolGetAccess.flags) data->args.hipMemPoolGetAccess.flags__val = *(data->args.hipMemPoolGetAccess.flags); + if (data->args.hipMemPoolGetAccess.location) data->args.hipMemPoolGetAccess.location__val = *(data->args.hipMemPoolGetAccess.location); + break; +// hipMemPoolGetAttribute[('hipMemPool_t', 'mem_pool'), ('hipMemPoolAttr', 'attr'), ('void*', 'value')] + case HIP_API_ID_hipMemPoolGetAttribute: + break; +// hipMemPoolImportFromShareableHandle[('hipMemPool_t*', 'mem_pool'), ('void*', 'shared_handle'), ('hipMemAllocationHandleType', 'handle_type'), ('unsigned int', 'flags')] + case HIP_API_ID_hipMemPoolImportFromShareableHandle: + if (data->args.hipMemPoolImportFromShareableHandle.mem_pool) data->args.hipMemPoolImportFromShareableHandle.mem_pool__val = *(data->args.hipMemPoolImportFromShareableHandle.mem_pool); + break; +// hipMemPoolImportPointer[('void**', 'dev_ptr'), ('hipMemPool_t', 'mem_pool'), ('hipMemPoolPtrExportData*', 'export_data')] + case HIP_API_ID_hipMemPoolImportPointer: + if (data->args.hipMemPoolImportPointer.dev_ptr) data->args.hipMemPoolImportPointer.dev_ptr__val = *(data->args.hipMemPoolImportPointer.dev_ptr); + if (data->args.hipMemPoolImportPointer.export_data) data->args.hipMemPoolImportPointer.export_data__val = *(data->args.hipMemPoolImportPointer.export_data); + break; +// hipMemPoolSetAccess[('hipMemPool_t', 'mem_pool'), ('const hipMemAccessDesc*', 'desc_list'), ('size_t', 'count')] + case HIP_API_ID_hipMemPoolSetAccess: + if (data->args.hipMemPoolSetAccess.desc_list) data->args.hipMemPoolSetAccess.desc_list__val = *(data->args.hipMemPoolSetAccess.desc_list); + break; +// hipMemPoolSetAttribute[('hipMemPool_t', 'mem_pool'), ('hipMemPoolAttr', 'attr'), ('void*', 'value')] + case HIP_API_ID_hipMemPoolSetAttribute: + break; +// hipMemPoolTrimTo[('hipMemPool_t', 'mem_pool'), ('size_t', 'min_bytes_to_hold')] + case HIP_API_ID_hipMemPoolTrimTo: + break; +// hipMemPrefetchAsync[('const void*', 'dev_ptr'), ('size_t', 'count'), ('int', 'device'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemPrefetchAsync: + break; +// hipMemPtrGetInfo[('void*', 'ptr'), ('size_t*', 'size')] + case HIP_API_ID_hipMemPtrGetInfo: + if (data->args.hipMemPtrGetInfo.size) data->args.hipMemPtrGetInfo.size__val = *(data->args.hipMemPtrGetInfo.size); + break; +// hipMemRangeGetAttribute[('void*', 'data'), ('size_t', 'data_size'), ('hipMemRangeAttribute', 'attribute'), ('const void*', 'dev_ptr'), ('size_t', 'count')] + case HIP_API_ID_hipMemRangeGetAttribute: + break; +// hipMemRangeGetAttributes[('void**', 'data'), ('size_t*', 'data_sizes'), ('hipMemRangeAttribute*', 'attributes'), ('size_t', 'num_attributes'), ('const void*', 'dev_ptr'), ('size_t', 'count')] + case HIP_API_ID_hipMemRangeGetAttributes: + if (data->args.hipMemRangeGetAttributes.data) data->args.hipMemRangeGetAttributes.data__val = *(data->args.hipMemRangeGetAttributes.data); + if (data->args.hipMemRangeGetAttributes.data_sizes) data->args.hipMemRangeGetAttributes.data_sizes__val = *(data->args.hipMemRangeGetAttributes.data_sizes); + if (data->args.hipMemRangeGetAttributes.attributes) data->args.hipMemRangeGetAttributes.attributes__val = *(data->args.hipMemRangeGetAttributes.attributes); + break; +// hipMemRelease[('hipMemGenericAllocationHandle_t', 'handle')] + case HIP_API_ID_hipMemRelease: + break; +// hipMemRetainAllocationHandle[('hipMemGenericAllocationHandle_t*', 'handle'), ('void*', 'addr')] + case HIP_API_ID_hipMemRetainAllocationHandle: + if (data->args.hipMemRetainAllocationHandle.handle) data->args.hipMemRetainAllocationHandle.handle__val = *(data->args.hipMemRetainAllocationHandle.handle); + break; +// hipMemSetAccess[('void*', 'ptr'), ('size_t', 'size'), ('const hipMemAccessDesc*', 'desc'), ('size_t', 'count')] + case HIP_API_ID_hipMemSetAccess: + if (data->args.hipMemSetAccess.desc) data->args.hipMemSetAccess.desc__val = *(data->args.hipMemSetAccess.desc); + break; +// hipMemUnmap[('void*', 'ptr'), ('size_t', 'size')] + case HIP_API_ID_hipMemUnmap: + break; +// hipMemcpy[('void*', 'dst'), ('const void*', 'src'), ('size_t', 'sizeBytes'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipMemcpy: + break; +// hipMemcpy2D[('void*', 'dst'), ('size_t', 'dpitch'), ('const void*', 'src'), ('size_t', 'spitch'), ('size_t', 'width'), ('size_t', 'height'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipMemcpy2D: + break; +// hipMemcpy2DArrayToArray[('hipArray_t', 'dst'), ('size_t', 'wOffsetDst'), ('size_t', 'hOffsetDst'), ('hipArray_const_t', 'src'), ('size_t', 'wOffsetSrc'), ('size_t', 'hOffsetSrc'), ('size_t', 'width'), ('size_t', 'height'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipMemcpy2DArrayToArray: + break; +// hipMemcpy2DAsync[('void*', 'dst'), ('size_t', 'dpitch'), ('const void*', 'src'), ('size_t', 'spitch'), ('size_t', 'width'), ('size_t', 'height'), ('hipMemcpyKind', 'kind'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemcpy2DAsync: + break; +// hipMemcpy2DFromArray[('void*', 'dst'), ('size_t', 'dpitch'), ('hipArray_const_t', 'src'), ('size_t', 'wOffset'), ('size_t', 'hOffset'), ('size_t', 'width'), ('size_t', 'height'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipMemcpy2DFromArray: + break; +// hipMemcpy2DFromArrayAsync[('void*', 'dst'), ('size_t', 'dpitch'), ('hipArray_const_t', 'src'), ('size_t', 'wOffset'), ('size_t', 'hOffset'), ('size_t', 'width'), ('size_t', 'height'), ('hipMemcpyKind', 'kind'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemcpy2DFromArrayAsync: + break; +// hipMemcpy2DToArray[('hipArray_t', 'dst'), ('size_t', 'wOffset'), ('size_t', 'hOffset'), ('const void*', 'src'), ('size_t', 'spitch'), ('size_t', 'width'), ('size_t', 'height'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipMemcpy2DToArray: + break; +// hipMemcpy2DToArrayAsync[('hipArray_t', 'dst'), ('size_t', 'wOffset'), ('size_t', 'hOffset'), ('const void*', 'src'), ('size_t', 'spitch'), ('size_t', 'width'), ('size_t', 'height'), ('hipMemcpyKind', 'kind'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemcpy2DToArrayAsync: + break; +// hipMemcpy3D[('const hipMemcpy3DParms*', 'p')] + case HIP_API_ID_hipMemcpy3D: + if (data->args.hipMemcpy3D.p) data->args.hipMemcpy3D.p__val = *(data->args.hipMemcpy3D.p); + break; +// hipMemcpy3DAsync[('const hipMemcpy3DParms*', 'p'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemcpy3DAsync: + if (data->args.hipMemcpy3DAsync.p) data->args.hipMemcpy3DAsync.p__val = *(data->args.hipMemcpy3DAsync.p); + break; +// hipMemcpyAsync[('void*', 'dst'), ('const void*', 'src'), ('size_t', 'sizeBytes'), ('hipMemcpyKind', 'kind'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemcpyAsync: + break; +// hipMemcpyAtoA[('hipArray_t', 'dstArray'), ('size_t', 'dstOffset'), ('hipArray_t', 'srcArray'), ('size_t', 'srcOffset'), ('size_t', 'ByteCount')] + case HIP_API_ID_hipMemcpyAtoA: + break; +// hipMemcpyAtoD[('hipDeviceptr_t', 'dstDevice'), ('hipArray_t', 'srcArray'), ('size_t', 'srcOffset'), ('size_t', 'ByteCount')] + case HIP_API_ID_hipMemcpyAtoD: + break; +// hipMemcpyAtoH[('void*', 'dst'), ('hipArray_t', 'srcArray'), ('size_t', 'srcOffset'), ('size_t', 'count')] + case HIP_API_ID_hipMemcpyAtoH: + break; +// hipMemcpyAtoHAsync[('void*', 'dstHost'), ('hipArray_t', 'srcArray'), ('size_t', 'srcOffset'), ('size_t', 'ByteCount'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemcpyAtoHAsync: + break; +// hipMemcpyDtoA[('hipArray_t', 'dstArray'), ('size_t', 'dstOffset'), ('hipDeviceptr_t', 'srcDevice'), ('size_t', 'ByteCount')] + case HIP_API_ID_hipMemcpyDtoA: + break; +// hipMemcpyDtoD[('hipDeviceptr_t', 'dst'), ('hipDeviceptr_t', 'src'), ('size_t', 'sizeBytes')] + case HIP_API_ID_hipMemcpyDtoD: + break; +// hipMemcpyDtoDAsync[('hipDeviceptr_t', 'dst'), ('hipDeviceptr_t', 'src'), ('size_t', 'sizeBytes'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemcpyDtoDAsync: + break; +// hipMemcpyDtoH[('void*', 'dst'), ('hipDeviceptr_t', 'src'), ('size_t', 'sizeBytes')] + case HIP_API_ID_hipMemcpyDtoH: + break; +// hipMemcpyDtoHAsync[('void*', 'dst'), ('hipDeviceptr_t', 'src'), ('size_t', 'sizeBytes'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemcpyDtoHAsync: + break; +// hipMemcpyFromArray[('void*', 'dst'), ('hipArray_const_t', 'srcArray'), ('size_t', 'wOffset'), ('size_t', 'hOffset'), ('size_t', 'count'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipMemcpyFromArray: + break; +// hipMemcpyFromSymbol[('void*', 'dst'), ('const void*', 'symbol'), ('size_t', 'sizeBytes'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipMemcpyFromSymbol: + break; +// hipMemcpyFromSymbolAsync[('void*', 'dst'), ('const void*', 'symbol'), ('size_t', 'sizeBytes'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemcpyFromSymbolAsync: + break; +// hipMemcpyHtoA[('hipArray_t', 'dstArray'), ('size_t', 'dstOffset'), ('const void*', 'srcHost'), ('size_t', 'count')] + case HIP_API_ID_hipMemcpyHtoA: + break; +// hipMemcpyHtoAAsync[('hipArray_t', 'dstArray'), ('size_t', 'dstOffset'), ('const void*', 'srcHost'), ('size_t', 'ByteCount'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemcpyHtoAAsync: + break; +// hipMemcpyHtoD[('hipDeviceptr_t', 'dst'), ('void*', 'src'), ('size_t', 'sizeBytes')] + case HIP_API_ID_hipMemcpyHtoD: + break; +// hipMemcpyHtoDAsync[('hipDeviceptr_t', 'dst'), ('void*', 'src'), ('size_t', 'sizeBytes'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemcpyHtoDAsync: + break; +// hipMemcpyParam2D[('const hip_Memcpy2D*', 'pCopy')] + case HIP_API_ID_hipMemcpyParam2D: + if (data->args.hipMemcpyParam2D.pCopy) data->args.hipMemcpyParam2D.pCopy__val = *(data->args.hipMemcpyParam2D.pCopy); + break; +// hipMemcpyParam2DAsync[('const hip_Memcpy2D*', 'pCopy'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemcpyParam2DAsync: + if (data->args.hipMemcpyParam2DAsync.pCopy) data->args.hipMemcpyParam2DAsync.pCopy__val = *(data->args.hipMemcpyParam2DAsync.pCopy); + break; +// hipMemcpyPeer[('void*', 'dst'), ('int', 'dstDeviceId'), ('const void*', 'src'), ('int', 'srcDeviceId'), ('size_t', 'sizeBytes')] + case HIP_API_ID_hipMemcpyPeer: + break; +// hipMemcpyPeerAsync[('void*', 'dst'), ('int', 'dstDeviceId'), ('const void*', 'src'), ('int', 'srcDevice'), ('size_t', 'sizeBytes'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemcpyPeerAsync: + break; +// hipMemcpyToArray[('hipArray_t', 'dst'), ('size_t', 'wOffset'), ('size_t', 'hOffset'), ('const void*', 'src'), ('size_t', 'count'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipMemcpyToArray: + break; +// hipMemcpyToSymbol[('const void*', 'symbol'), ('const void*', 'src'), ('size_t', 'sizeBytes'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind')] + case HIP_API_ID_hipMemcpyToSymbol: + break; +// hipMemcpyToSymbolAsync[('const void*', 'symbol'), ('const void*', 'src'), ('size_t', 'sizeBytes'), ('size_t', 'offset'), ('hipMemcpyKind', 'kind'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemcpyToSymbolAsync: + break; +// hipMemcpyWithStream[('void*', 'dst'), ('const void*', 'src'), ('size_t', 'sizeBytes'), ('hipMemcpyKind', 'kind'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemcpyWithStream: + break; +// hipMemset[('void*', 'dst'), ('int', 'value'), ('size_t', 'sizeBytes')] + case HIP_API_ID_hipMemset: + break; +// hipMemset2D[('void*', 'dst'), ('size_t', 'pitch'), ('int', 'value'), ('size_t', 'width'), ('size_t', 'height')] + case HIP_API_ID_hipMemset2D: + break; +// hipMemset2DAsync[('void*', 'dst'), ('size_t', 'pitch'), ('int', 'value'), ('size_t', 'width'), ('size_t', 'height'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemset2DAsync: + break; +// hipMemset3D[('hipPitchedPtr', 'pitchedDevPtr'), ('int', 'value'), ('hipExtent', 'extent')] + case HIP_API_ID_hipMemset3D: + break; +// hipMemset3DAsync[('hipPitchedPtr', 'pitchedDevPtr'), ('int', 'value'), ('hipExtent', 'extent'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemset3DAsync: + break; +// hipMemsetAsync[('void*', 'dst'), ('int', 'value'), ('size_t', 'sizeBytes'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemsetAsync: + break; +// hipMemsetD16[('hipDeviceptr_t', 'dest'), ('unsigned short', 'value'), ('size_t', 'count')] + case HIP_API_ID_hipMemsetD16: + break; +// hipMemsetD16Async[('hipDeviceptr_t', 'dest'), ('unsigned short', 'value'), ('size_t', 'count'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemsetD16Async: + break; +// hipMemsetD32[('hipDeviceptr_t', 'dest'), ('int', 'value'), ('size_t', 'count')] + case HIP_API_ID_hipMemsetD32: + break; +// hipMemsetD32Async[('hipDeviceptr_t', 'dst'), ('int', 'value'), ('size_t', 'count'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemsetD32Async: + break; +// hipMemsetD8[('hipDeviceptr_t', 'dest'), ('unsigned char', 'value'), ('size_t', 'count')] + case HIP_API_ID_hipMemsetD8: + break; +// hipMemsetD8Async[('hipDeviceptr_t', 'dest'), ('unsigned char', 'value'), ('size_t', 'count'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipMemsetD8Async: + break; +// hipMipmappedArrayCreate[('hipMipmappedArray_t*', 'pHandle'), ('HIP_ARRAY3D_DESCRIPTOR*', 'pMipmappedArrayDesc'), ('unsigned int', 'numMipmapLevels')] + case HIP_API_ID_hipMipmappedArrayCreate: + if (data->args.hipMipmappedArrayCreate.pHandle) data->args.hipMipmappedArrayCreate.pHandle__val = *(data->args.hipMipmappedArrayCreate.pHandle); + if (data->args.hipMipmappedArrayCreate.pMipmappedArrayDesc) data->args.hipMipmappedArrayCreate.pMipmappedArrayDesc__val = *(data->args.hipMipmappedArrayCreate.pMipmappedArrayDesc); + break; +// hipMipmappedArrayDestroy[('hipMipmappedArray_t', 'hMipmappedArray')] + case HIP_API_ID_hipMipmappedArrayDestroy: + break; +// hipMipmappedArrayGetLevel[('hipArray_t*', 'pLevelArray'), ('hipMipmappedArray_t', 'hMipMappedArray'), ('unsigned int', 'level')] + case HIP_API_ID_hipMipmappedArrayGetLevel: + if (data->args.hipMipmappedArrayGetLevel.pLevelArray) data->args.hipMipmappedArrayGetLevel.pLevelArray__val = *(data->args.hipMipmappedArrayGetLevel.pLevelArray); + break; +// hipModuleGetFunction[('hipFunction_t*', 'function'), ('hipModule_t', 'module'), ('const char*', 'kname')] + case HIP_API_ID_hipModuleGetFunction: + if (data->args.hipModuleGetFunction.function) data->args.hipModuleGetFunction.function__val = *(data->args.hipModuleGetFunction.function); + if (data->args.hipModuleGetFunction.kname) data->args.hipModuleGetFunction.kname__val = *(data->args.hipModuleGetFunction.kname); + break; +// hipModuleGetGlobal[('hipDeviceptr_t*', 'dptr'), ('size_t*', 'bytes'), ('hipModule_t', 'hmod'), ('const char*', 'name')] + case HIP_API_ID_hipModuleGetGlobal: + if (data->args.hipModuleGetGlobal.dptr) data->args.hipModuleGetGlobal.dptr__val = *(data->args.hipModuleGetGlobal.dptr); + if (data->args.hipModuleGetGlobal.bytes) data->args.hipModuleGetGlobal.bytes__val = *(data->args.hipModuleGetGlobal.bytes); + if (data->args.hipModuleGetGlobal.name) data->args.hipModuleGetGlobal.name__val = *(data->args.hipModuleGetGlobal.name); + break; +// hipModuleGetTexRef[('textureReference**', 'texRef'), ('hipModule_t', 'hmod'), ('const char*', 'name')] + case HIP_API_ID_hipModuleGetTexRef: + if (data->args.hipModuleGetTexRef.texRef) data->args.hipModuleGetTexRef.texRef__val = *(data->args.hipModuleGetTexRef.texRef); + if (data->args.hipModuleGetTexRef.name) data->args.hipModuleGetTexRef.name__val = *(data->args.hipModuleGetTexRef.name); + break; +// 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')] + case HIP_API_ID_hipModuleLaunchCooperativeKernel: + if (data->args.hipModuleLaunchCooperativeKernel.kernelParams) data->args.hipModuleLaunchCooperativeKernel.kernelParams__val = *(data->args.hipModuleLaunchCooperativeKernel.kernelParams); + break; +// hipModuleLaunchCooperativeKernelMultiDevice[('hipFunctionLaunchParams*', 'launchParamsList'), ('unsigned int', 'numDevices'), ('unsigned int', 'flags')] + case HIP_API_ID_hipModuleLaunchCooperativeKernelMultiDevice: + if (data->args.hipModuleLaunchCooperativeKernelMultiDevice.launchParamsList) data->args.hipModuleLaunchCooperativeKernelMultiDevice.launchParamsList__val = *(data->args.hipModuleLaunchCooperativeKernelMultiDevice.launchParamsList); + break; +// 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')] + case HIP_API_ID_hipModuleLaunchKernel: + if (data->args.hipModuleLaunchKernel.kernelParams) data->args.hipModuleLaunchKernel.kernelParams__val = *(data->args.hipModuleLaunchKernel.kernelParams); + if (data->args.hipModuleLaunchKernel.extra) data->args.hipModuleLaunchKernel.extra__val = *(data->args.hipModuleLaunchKernel.extra); + break; +// hipModuleLoad[('hipModule_t*', 'module'), ('const char*', 'fname')] + case HIP_API_ID_hipModuleLoad: + if (data->args.hipModuleLoad.module) data->args.hipModuleLoad.module__val = *(data->args.hipModuleLoad.module); + if (data->args.hipModuleLoad.fname) data->args.hipModuleLoad.fname__val = *(data->args.hipModuleLoad.fname); + break; +// hipModuleLoadData[('hipModule_t*', 'module'), ('const void*', 'image')] + case HIP_API_ID_hipModuleLoadData: + if (data->args.hipModuleLoadData.module) data->args.hipModuleLoadData.module__val = *(data->args.hipModuleLoadData.module); + break; +// hipModuleLoadDataEx[('hipModule_t*', 'module'), ('const void*', 'image'), ('unsigned int', 'numOptions'), ('hipJitOption*', 'options'), ('void**', 'optionsValues')] + case HIP_API_ID_hipModuleLoadDataEx: + if (data->args.hipModuleLoadDataEx.module) data->args.hipModuleLoadDataEx.module__val = *(data->args.hipModuleLoadDataEx.module); + if (data->args.hipModuleLoadDataEx.options) data->args.hipModuleLoadDataEx.options__val = *(data->args.hipModuleLoadDataEx.options); + if (data->args.hipModuleLoadDataEx.optionsValues) data->args.hipModuleLoadDataEx.optionsValues__val = *(data->args.hipModuleLoadDataEx.optionsValues); + break; +// hipModuleOccupancyMaxActiveBlocksPerMultiprocessor[('int*', 'numBlocks'), ('hipFunction_t', 'f'), ('int', 'blockSize'), ('size_t', 'dynSharedMemPerBlk')] + case HIP_API_ID_hipModuleOccupancyMaxActiveBlocksPerMultiprocessor: + if (data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessor.numBlocks) data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessor.numBlocks__val = *(data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessor.numBlocks); + break; +// hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags[('int*', 'numBlocks'), ('hipFunction_t', 'f'), ('int', 'blockSize'), ('size_t', 'dynSharedMemPerBlk'), ('unsigned int', 'flags')] + case HIP_API_ID_hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags: + if (data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.numBlocks) data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.numBlocks__val = *(data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.numBlocks); + break; +// hipModuleOccupancyMaxPotentialBlockSize[('int*', 'gridSize'), ('int*', 'blockSize'), ('hipFunction_t', 'f'), ('size_t', 'dynSharedMemPerBlk'), ('int', 'blockSizeLimit')] + case HIP_API_ID_hipModuleOccupancyMaxPotentialBlockSize: + if (data->args.hipModuleOccupancyMaxPotentialBlockSize.gridSize) data->args.hipModuleOccupancyMaxPotentialBlockSize.gridSize__val = *(data->args.hipModuleOccupancyMaxPotentialBlockSize.gridSize); + if (data->args.hipModuleOccupancyMaxPotentialBlockSize.blockSize) data->args.hipModuleOccupancyMaxPotentialBlockSize.blockSize__val = *(data->args.hipModuleOccupancyMaxPotentialBlockSize.blockSize); + break; +// hipModuleOccupancyMaxPotentialBlockSizeWithFlags[('int*', 'gridSize'), ('int*', 'blockSize'), ('hipFunction_t', 'f'), ('size_t', 'dynSharedMemPerBlk'), ('int', 'blockSizeLimit'), ('unsigned int', 'flags')] + case HIP_API_ID_hipModuleOccupancyMaxPotentialBlockSizeWithFlags: + if (data->args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.gridSize) data->args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.gridSize__val = *(data->args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.gridSize); + if (data->args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.blockSize) data->args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.blockSize__val = *(data->args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.blockSize); + break; +// hipModuleUnload[('hipModule_t', 'module')] + case HIP_API_ID_hipModuleUnload: + break; +// hipOccupancyMaxActiveBlocksPerMultiprocessor[('int*', 'numBlocks'), ('const void*', 'f'), ('int', 'blockSize'), ('size_t', 'dynamicSMemSize')] + case HIP_API_ID_hipOccupancyMaxActiveBlocksPerMultiprocessor: + if (data->args.hipOccupancyMaxActiveBlocksPerMultiprocessor.numBlocks) data->args.hipOccupancyMaxActiveBlocksPerMultiprocessor.numBlocks__val = *(data->args.hipOccupancyMaxActiveBlocksPerMultiprocessor.numBlocks); + break; +// hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags[('int*', 'numBlocks'), ('const void*', 'f'), ('int', 'blockSize'), ('size_t', 'dynamicSMemSize'), ('unsigned int', 'flags')] + case HIP_API_ID_hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags: + if (data->args.hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.numBlocks) data->args.hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.numBlocks__val = *(data->args.hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.numBlocks); + break; +// hipOccupancyMaxPotentialBlockSize[('int*', 'gridSize'), ('int*', 'blockSize'), ('const void*', 'f'), ('size_t', 'dynSharedMemPerBlk'), ('int', 'blockSizeLimit')] + case HIP_API_ID_hipOccupancyMaxPotentialBlockSize: + if (data->args.hipOccupancyMaxPotentialBlockSize.gridSize) data->args.hipOccupancyMaxPotentialBlockSize.gridSize__val = *(data->args.hipOccupancyMaxPotentialBlockSize.gridSize); + if (data->args.hipOccupancyMaxPotentialBlockSize.blockSize) data->args.hipOccupancyMaxPotentialBlockSize.blockSize__val = *(data->args.hipOccupancyMaxPotentialBlockSize.blockSize); + break; +// hipPeekAtLastError[] + case HIP_API_ID_hipPeekAtLastError: + break; +// hipPointerGetAttribute[('void*', 'data'), ('hipPointer_attribute', 'attribute'), ('hipDeviceptr_t', 'ptr')] + case HIP_API_ID_hipPointerGetAttribute: + break; +// hipPointerGetAttributes[('hipPointerAttribute_t*', 'attributes'), ('const void*', 'ptr')] + case HIP_API_ID_hipPointerGetAttributes: + if (data->args.hipPointerGetAttributes.attributes) data->args.hipPointerGetAttributes.attributes__val = *(data->args.hipPointerGetAttributes.attributes); + break; +// hipPointerSetAttribute[('const void*', 'value'), ('hipPointer_attribute', 'attribute'), ('hipDeviceptr_t', 'ptr')] + case HIP_API_ID_hipPointerSetAttribute: + break; +// hipProfilerStart[] + case HIP_API_ID_hipProfilerStart: + break; +// hipProfilerStop[] + case HIP_API_ID_hipProfilerStop: + break; +// hipRuntimeGetVersion[('int*', 'runtimeVersion')] + case HIP_API_ID_hipRuntimeGetVersion: + if (data->args.hipRuntimeGetVersion.runtimeVersion) data->args.hipRuntimeGetVersion.runtimeVersion__val = *(data->args.hipRuntimeGetVersion.runtimeVersion); + break; +// hipSetDevice[('int', 'deviceId')] + case HIP_API_ID_hipSetDevice: + break; +// hipSetDeviceFlags[('unsigned int', 'flags')] + case HIP_API_ID_hipSetDeviceFlags: + break; +// hipSetValidDevices[('int*', 'device_arr'), ('int', 'len')] + case HIP_API_ID_hipSetValidDevices: + if (data->args.hipSetValidDevices.device_arr) data->args.hipSetValidDevices.device_arr__val = *(data->args.hipSetValidDevices.device_arr); + break; +// hipSetupArgument[('const void*', 'arg'), ('size_t', 'size'), ('size_t', 'offset')] + case HIP_API_ID_hipSetupArgument: + break; +// hipSignalExternalSemaphoresAsync[('const hipExternalSemaphore_t*', 'extSemArray'), ('const hipExternalSemaphoreSignalParams*', 'paramsArray'), ('unsigned int', 'numExtSems'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipSignalExternalSemaphoresAsync: + if (data->args.hipSignalExternalSemaphoresAsync.extSemArray) data->args.hipSignalExternalSemaphoresAsync.extSemArray__val = *(data->args.hipSignalExternalSemaphoresAsync.extSemArray); + if (data->args.hipSignalExternalSemaphoresAsync.paramsArray) data->args.hipSignalExternalSemaphoresAsync.paramsArray__val = *(data->args.hipSignalExternalSemaphoresAsync.paramsArray); + break; +// hipStreamAddCallback[('hipStream_t', 'stream'), ('hipStreamCallback_t', 'callback'), ('void*', 'userData'), ('unsigned int', 'flags')] + case HIP_API_ID_hipStreamAddCallback: + break; +// hipStreamAttachMemAsync[('hipStream_t', 'stream'), ('void*', 'dev_ptr'), ('size_t', 'length'), ('unsigned int', 'flags')] + case HIP_API_ID_hipStreamAttachMemAsync: + break; +// hipStreamBeginCapture[('hipStream_t', 'stream'), ('hipStreamCaptureMode', 'mode')] + case HIP_API_ID_hipStreamBeginCapture: + break; +// hipStreamBeginCaptureToGraph[('hipStream_t', 'stream'), ('hipGraph_t', 'graph'), ('const hipGraphNode_t*', 'dependencies'), ('const hipGraphEdgeData*', 'dependencyData'), ('size_t', 'numDependencies'), ('hipStreamCaptureMode', 'mode')] + case HIP_API_ID_hipStreamBeginCaptureToGraph: + if (data->args.hipStreamBeginCaptureToGraph.dependencies) data->args.hipStreamBeginCaptureToGraph.dependencies__val = *(data->args.hipStreamBeginCaptureToGraph.dependencies); + if (data->args.hipStreamBeginCaptureToGraph.dependencyData) data->args.hipStreamBeginCaptureToGraph.dependencyData__val = *(data->args.hipStreamBeginCaptureToGraph.dependencyData); + break; +// hipStreamCreate[('hipStream_t*', 'stream')] + case HIP_API_ID_hipStreamCreate: + if (data->args.hipStreamCreate.stream) data->args.hipStreamCreate.stream__val = *(data->args.hipStreamCreate.stream); + break; +// hipStreamCreateWithFlags[('hipStream_t*', 'stream'), ('unsigned int', 'flags')] + case HIP_API_ID_hipStreamCreateWithFlags: + if (data->args.hipStreamCreateWithFlags.stream) data->args.hipStreamCreateWithFlags.stream__val = *(data->args.hipStreamCreateWithFlags.stream); + break; +// hipStreamCreateWithPriority[('hipStream_t*', 'stream'), ('unsigned int', 'flags'), ('int', 'priority')] + case HIP_API_ID_hipStreamCreateWithPriority: + if (data->args.hipStreamCreateWithPriority.stream) data->args.hipStreamCreateWithPriority.stream__val = *(data->args.hipStreamCreateWithPriority.stream); + break; +// hipStreamDestroy[('hipStream_t', 'stream')] + case HIP_API_ID_hipStreamDestroy: + break; +// hipStreamEndCapture[('hipStream_t', 'stream'), ('hipGraph_t*', 'pGraph')] + case HIP_API_ID_hipStreamEndCapture: + if (data->args.hipStreamEndCapture.pGraph) data->args.hipStreamEndCapture.pGraph__val = *(data->args.hipStreamEndCapture.pGraph); + break; +// hipStreamGetCaptureInfo[('hipStream_t', 'stream'), ('hipStreamCaptureStatus*', 'pCaptureStatus'), ('unsigned long long*', 'pId')] + case HIP_API_ID_hipStreamGetCaptureInfo: + if (data->args.hipStreamGetCaptureInfo.pCaptureStatus) data->args.hipStreamGetCaptureInfo.pCaptureStatus__val = *(data->args.hipStreamGetCaptureInfo.pCaptureStatus); + if (data->args.hipStreamGetCaptureInfo.pId) data->args.hipStreamGetCaptureInfo.pId__val = *(data->args.hipStreamGetCaptureInfo.pId); + break; +// hipStreamGetCaptureInfo_v2[('hipStream_t', 'stream'), ('hipStreamCaptureStatus*', 'captureStatus_out'), ('unsigned long long*', 'id_out'), ('hipGraph_t*', 'graph_out'), ('const hipGraphNode_t**', 'dependencies_out'), ('size_t*', 'numDependencies_out')] + case HIP_API_ID_hipStreamGetCaptureInfo_v2: + if (data->args.hipStreamGetCaptureInfo_v2.captureStatus_out) data->args.hipStreamGetCaptureInfo_v2.captureStatus_out__val = *(data->args.hipStreamGetCaptureInfo_v2.captureStatus_out); + if (data->args.hipStreamGetCaptureInfo_v2.id_out) data->args.hipStreamGetCaptureInfo_v2.id_out__val = *(data->args.hipStreamGetCaptureInfo_v2.id_out); + if (data->args.hipStreamGetCaptureInfo_v2.graph_out) data->args.hipStreamGetCaptureInfo_v2.graph_out__val = *(data->args.hipStreamGetCaptureInfo_v2.graph_out); + if (data->args.hipStreamGetCaptureInfo_v2.dependencies_out) data->args.hipStreamGetCaptureInfo_v2.dependencies_out__val = *(data->args.hipStreamGetCaptureInfo_v2.dependencies_out); + if (data->args.hipStreamGetCaptureInfo_v2.numDependencies_out) data->args.hipStreamGetCaptureInfo_v2.numDependencies_out__val = *(data->args.hipStreamGetCaptureInfo_v2.numDependencies_out); + break; +// hipStreamGetDevice[('hipStream_t', 'stream'), ('hipDevice_t*', 'device')] + case HIP_API_ID_hipStreamGetDevice: + if (data->args.hipStreamGetDevice.device) data->args.hipStreamGetDevice.device__val = *(data->args.hipStreamGetDevice.device); + break; +// hipStreamGetFlags[('hipStream_t', 'stream'), ('unsigned int*', 'flags')] + case HIP_API_ID_hipStreamGetFlags: + if (data->args.hipStreamGetFlags.flags) data->args.hipStreamGetFlags.flags__val = *(data->args.hipStreamGetFlags.flags); + break; +// hipStreamGetPriority[('hipStream_t', 'stream'), ('int*', 'priority')] + case HIP_API_ID_hipStreamGetPriority: + if (data->args.hipStreamGetPriority.priority) data->args.hipStreamGetPriority.priority__val = *(data->args.hipStreamGetPriority.priority); + break; +// hipStreamIsCapturing[('hipStream_t', 'stream'), ('hipStreamCaptureStatus*', 'pCaptureStatus')] + case HIP_API_ID_hipStreamIsCapturing: + if (data->args.hipStreamIsCapturing.pCaptureStatus) data->args.hipStreamIsCapturing.pCaptureStatus__val = *(data->args.hipStreamIsCapturing.pCaptureStatus); + break; +// hipStreamQuery[('hipStream_t', 'stream')] + case HIP_API_ID_hipStreamQuery: + break; +// hipStreamSynchronize[('hipStream_t', 'stream')] + case HIP_API_ID_hipStreamSynchronize: + break; +// hipStreamUpdateCaptureDependencies[('hipStream_t', 'stream'), ('hipGraphNode_t*', 'dependencies'), ('size_t', 'numDependencies'), ('unsigned int', 'flags')] + case HIP_API_ID_hipStreamUpdateCaptureDependencies: + if (data->args.hipStreamUpdateCaptureDependencies.dependencies) data->args.hipStreamUpdateCaptureDependencies.dependencies__val = *(data->args.hipStreamUpdateCaptureDependencies.dependencies); + break; +// hipStreamWaitEvent[('hipStream_t', 'stream'), ('hipEvent_t', 'event'), ('unsigned int', 'flags')] + case HIP_API_ID_hipStreamWaitEvent: + break; +// hipStreamWaitValue32[('hipStream_t', 'stream'), ('void*', 'ptr'), ('unsigned int', 'value'), ('unsigned int', 'flags'), ('unsigned int', 'mask')] + case HIP_API_ID_hipStreamWaitValue32: + break; +// hipStreamWaitValue64[('hipStream_t', 'stream'), ('void*', 'ptr'), ('uint64_t', 'value'), ('unsigned int', 'flags'), ('uint64_t', 'mask')] + case HIP_API_ID_hipStreamWaitValue64: + break; +// hipStreamWriteValue32[('hipStream_t', 'stream'), ('void*', 'ptr'), ('unsigned int', 'value'), ('unsigned int', 'flags')] + case HIP_API_ID_hipStreamWriteValue32: + break; +// hipStreamWriteValue64[('hipStream_t', 'stream'), ('void*', 'ptr'), ('uint64_t', 'value'), ('unsigned int', 'flags')] + case HIP_API_ID_hipStreamWriteValue64: + break; +// hipTexRefGetAddress[('hipDeviceptr_t*', 'dev_ptr'), ('const textureReference*', 'texRef')] + case HIP_API_ID_hipTexRefGetAddress: + if (data->args.hipTexRefGetAddress.dev_ptr) data->args.hipTexRefGetAddress.dev_ptr__val = *(data->args.hipTexRefGetAddress.dev_ptr); + if (data->args.hipTexRefGetAddress.texRef) data->args.hipTexRefGetAddress.texRef__val = *(data->args.hipTexRefGetAddress.texRef); + break; +// hipTexRefGetArray[('hipArray_t*', 'pArray'), ('const textureReference*', 'texRef')] + case HIP_API_ID_hipTexRefGetArray: + if (data->args.hipTexRefGetArray.pArray) data->args.hipTexRefGetArray.pArray__val = *(data->args.hipTexRefGetArray.pArray); + if (data->args.hipTexRefGetArray.texRef) data->args.hipTexRefGetArray.texRef__val = *(data->args.hipTexRefGetArray.texRef); + break; +// hipTexRefGetBorderColor[('float*', 'pBorderColor'), ('const textureReference*', 'texRef')] + case HIP_API_ID_hipTexRefGetBorderColor: + if (data->args.hipTexRefGetBorderColor.pBorderColor) data->args.hipTexRefGetBorderColor.pBorderColor__val = *(data->args.hipTexRefGetBorderColor.pBorderColor); + if (data->args.hipTexRefGetBorderColor.texRef) data->args.hipTexRefGetBorderColor.texRef__val = *(data->args.hipTexRefGetBorderColor.texRef); + break; +// hipTexRefGetFlags[('unsigned int*', 'pFlags'), ('const textureReference*', 'texRef')] + case HIP_API_ID_hipTexRefGetFlags: + if (data->args.hipTexRefGetFlags.pFlags) data->args.hipTexRefGetFlags.pFlags__val = *(data->args.hipTexRefGetFlags.pFlags); + if (data->args.hipTexRefGetFlags.texRef) data->args.hipTexRefGetFlags.texRef__val = *(data->args.hipTexRefGetFlags.texRef); + break; +// hipTexRefGetFormat[('hipArray_Format*', 'pFormat'), ('int*', 'pNumChannels'), ('const textureReference*', 'texRef')] + case HIP_API_ID_hipTexRefGetFormat: + if (data->args.hipTexRefGetFormat.pFormat) data->args.hipTexRefGetFormat.pFormat__val = *(data->args.hipTexRefGetFormat.pFormat); + if (data->args.hipTexRefGetFormat.pNumChannels) data->args.hipTexRefGetFormat.pNumChannels__val = *(data->args.hipTexRefGetFormat.pNumChannels); + if (data->args.hipTexRefGetFormat.texRef) data->args.hipTexRefGetFormat.texRef__val = *(data->args.hipTexRefGetFormat.texRef); + break; +// hipTexRefGetMaxAnisotropy[('int*', 'pmaxAnsio'), ('const textureReference*', 'texRef')] + case HIP_API_ID_hipTexRefGetMaxAnisotropy: + if (data->args.hipTexRefGetMaxAnisotropy.pmaxAnsio) data->args.hipTexRefGetMaxAnisotropy.pmaxAnsio__val = *(data->args.hipTexRefGetMaxAnisotropy.pmaxAnsio); + if (data->args.hipTexRefGetMaxAnisotropy.texRef) data->args.hipTexRefGetMaxAnisotropy.texRef__val = *(data->args.hipTexRefGetMaxAnisotropy.texRef); + break; +// hipTexRefGetMipMappedArray[('hipMipmappedArray_t*', 'pArray'), ('const textureReference*', 'texRef')] + case HIP_API_ID_hipTexRefGetMipMappedArray: + if (data->args.hipTexRefGetMipMappedArray.pArray) data->args.hipTexRefGetMipMappedArray.pArray__val = *(data->args.hipTexRefGetMipMappedArray.pArray); + if (data->args.hipTexRefGetMipMappedArray.texRef) data->args.hipTexRefGetMipMappedArray.texRef__val = *(data->args.hipTexRefGetMipMappedArray.texRef); + break; +// hipTexRefGetMipmapLevelBias[('float*', 'pbias'), ('const textureReference*', 'texRef')] + case HIP_API_ID_hipTexRefGetMipmapLevelBias: + if (data->args.hipTexRefGetMipmapLevelBias.pbias) data->args.hipTexRefGetMipmapLevelBias.pbias__val = *(data->args.hipTexRefGetMipmapLevelBias.pbias); + if (data->args.hipTexRefGetMipmapLevelBias.texRef) data->args.hipTexRefGetMipmapLevelBias.texRef__val = *(data->args.hipTexRefGetMipmapLevelBias.texRef); + break; +// hipTexRefGetMipmapLevelClamp[('float*', 'pminMipmapLevelClamp'), ('float*', 'pmaxMipmapLevelClamp'), ('const textureReference*', 'texRef')] + case HIP_API_ID_hipTexRefGetMipmapLevelClamp: + if (data->args.hipTexRefGetMipmapLevelClamp.pminMipmapLevelClamp) data->args.hipTexRefGetMipmapLevelClamp.pminMipmapLevelClamp__val = *(data->args.hipTexRefGetMipmapLevelClamp.pminMipmapLevelClamp); + if (data->args.hipTexRefGetMipmapLevelClamp.pmaxMipmapLevelClamp) data->args.hipTexRefGetMipmapLevelClamp.pmaxMipmapLevelClamp__val = *(data->args.hipTexRefGetMipmapLevelClamp.pmaxMipmapLevelClamp); + if (data->args.hipTexRefGetMipmapLevelClamp.texRef) data->args.hipTexRefGetMipmapLevelClamp.texRef__val = *(data->args.hipTexRefGetMipmapLevelClamp.texRef); + break; +// hipTexRefSetAddress[('size_t*', 'ByteOffset'), ('textureReference*', 'texRef'), ('hipDeviceptr_t', 'dptr'), ('size_t', 'bytes')] + case HIP_API_ID_hipTexRefSetAddress: + if (data->args.hipTexRefSetAddress.ByteOffset) data->args.hipTexRefSetAddress.ByteOffset__val = *(data->args.hipTexRefSetAddress.ByteOffset); + if (data->args.hipTexRefSetAddress.texRef) data->args.hipTexRefSetAddress.texRef__val = *(data->args.hipTexRefSetAddress.texRef); + break; +// hipTexRefSetAddress2D[('textureReference*', 'texRef'), ('const HIP_ARRAY_DESCRIPTOR*', 'desc'), ('hipDeviceptr_t', 'dptr'), ('size_t', 'Pitch')] + case HIP_API_ID_hipTexRefSetAddress2D: + if (data->args.hipTexRefSetAddress2D.texRef) data->args.hipTexRefSetAddress2D.texRef__val = *(data->args.hipTexRefSetAddress2D.texRef); + if (data->args.hipTexRefSetAddress2D.desc) data->args.hipTexRefSetAddress2D.desc__val = *(data->args.hipTexRefSetAddress2D.desc); + break; +// hipTexRefSetArray[('textureReference*', 'tex'), ('hipArray_const_t', 'array'), ('unsigned int', 'flags')] + case HIP_API_ID_hipTexRefSetArray: + if (data->args.hipTexRefSetArray.tex) data->args.hipTexRefSetArray.tex__val = *(data->args.hipTexRefSetArray.tex); + break; +// hipTexRefSetBorderColor[('textureReference*', 'texRef'), ('float*', 'pBorderColor')] + case HIP_API_ID_hipTexRefSetBorderColor: + if (data->args.hipTexRefSetBorderColor.texRef) data->args.hipTexRefSetBorderColor.texRef__val = *(data->args.hipTexRefSetBorderColor.texRef); + if (data->args.hipTexRefSetBorderColor.pBorderColor) data->args.hipTexRefSetBorderColor.pBorderColor__val = *(data->args.hipTexRefSetBorderColor.pBorderColor); + break; +// hipTexRefSetFlags[('textureReference*', 'texRef'), ('unsigned int', 'Flags')] + case HIP_API_ID_hipTexRefSetFlags: + if (data->args.hipTexRefSetFlags.texRef) data->args.hipTexRefSetFlags.texRef__val = *(data->args.hipTexRefSetFlags.texRef); + break; +// hipTexRefSetFormat[('textureReference*', 'texRef'), ('hipArray_Format', 'fmt'), ('int', 'NumPackedComponents')] + case HIP_API_ID_hipTexRefSetFormat: + if (data->args.hipTexRefSetFormat.texRef) data->args.hipTexRefSetFormat.texRef__val = *(data->args.hipTexRefSetFormat.texRef); + break; +// hipTexRefSetMaxAnisotropy[('textureReference*', 'texRef'), ('unsigned int', 'maxAniso')] + case HIP_API_ID_hipTexRefSetMaxAnisotropy: + if (data->args.hipTexRefSetMaxAnisotropy.texRef) data->args.hipTexRefSetMaxAnisotropy.texRef__val = *(data->args.hipTexRefSetMaxAnisotropy.texRef); + break; +// hipTexRefSetMipmapLevelBias[('textureReference*', 'texRef'), ('float', 'bias')] + case HIP_API_ID_hipTexRefSetMipmapLevelBias: + if (data->args.hipTexRefSetMipmapLevelBias.texRef) data->args.hipTexRefSetMipmapLevelBias.texRef__val = *(data->args.hipTexRefSetMipmapLevelBias.texRef); + break; +// hipTexRefSetMipmapLevelClamp[('textureReference*', 'texRef'), ('float', 'minMipMapLevelClamp'), ('float', 'maxMipMapLevelClamp')] + case HIP_API_ID_hipTexRefSetMipmapLevelClamp: + if (data->args.hipTexRefSetMipmapLevelClamp.texRef) data->args.hipTexRefSetMipmapLevelClamp.texRef__val = *(data->args.hipTexRefSetMipmapLevelClamp.texRef); + break; +// hipTexRefSetMipmappedArray[('textureReference*', 'texRef'), ('hipMipmappedArray*', 'mipmappedArray'), ('unsigned int', 'Flags')] + case HIP_API_ID_hipTexRefSetMipmappedArray: + if (data->args.hipTexRefSetMipmappedArray.texRef) data->args.hipTexRefSetMipmappedArray.texRef__val = *(data->args.hipTexRefSetMipmappedArray.texRef); + if (data->args.hipTexRefSetMipmappedArray.mipmappedArray) data->args.hipTexRefSetMipmappedArray.mipmappedArray__val = *(data->args.hipTexRefSetMipmappedArray.mipmappedArray); + break; +// hipThreadExchangeStreamCaptureMode[('hipStreamCaptureMode*', 'mode')] + case HIP_API_ID_hipThreadExchangeStreamCaptureMode: + if (data->args.hipThreadExchangeStreamCaptureMode.mode) data->args.hipThreadExchangeStreamCaptureMode.mode__val = *(data->args.hipThreadExchangeStreamCaptureMode.mode); + break; +// hipUserObjectCreate[('hipUserObject_t*', 'object_out'), ('void*', 'ptr'), ('hipHostFn_t', 'destroy'), ('unsigned int', 'initialRefcount'), ('unsigned int', 'flags')] + case HIP_API_ID_hipUserObjectCreate: + if (data->args.hipUserObjectCreate.object_out) data->args.hipUserObjectCreate.object_out__val = *(data->args.hipUserObjectCreate.object_out); + break; +// hipUserObjectRelease[('hipUserObject_t', 'object'), ('unsigned int', 'count')] + case HIP_API_ID_hipUserObjectRelease: + break; +// hipUserObjectRetain[('hipUserObject_t', 'object'), ('unsigned int', 'count')] + case HIP_API_ID_hipUserObjectRetain: + break; +// hipWaitExternalSemaphoresAsync[('const hipExternalSemaphore_t*', 'extSemArray'), ('const hipExternalSemaphoreWaitParams*', 'paramsArray'), ('unsigned int', 'numExtSems'), ('hipStream_t', 'stream')] + case HIP_API_ID_hipWaitExternalSemaphoresAsync: + if (data->args.hipWaitExternalSemaphoresAsync.extSemArray) data->args.hipWaitExternalSemaphoresAsync.extSemArray__val = *(data->args.hipWaitExternalSemaphoresAsync.extSemArray); + if (data->args.hipWaitExternalSemaphoresAsync.paramsArray) data->args.hipWaitExternalSemaphoresAsync.paramsArray__val = *(data->args.hipWaitExternalSemaphoresAsync.paramsArray); + break; + default: break; + }; +} + +#include +#include +// HIP API string method, method name and parameters +static inline const char* hipApiString(hip_api_id_t id, const hip_api_data_t* data) { + std::ostringstream oss; + switch (id) { + case HIP_API_ID___hipPopCallConfiguration: + oss << "__hipPopCallConfiguration("; + if (data->args.__hipPopCallConfiguration.gridDim == NULL) oss << "gridDim=NULL"; + else { oss << "gridDim="; roctracer::hip_support::detail::operator<<(oss, data->args.__hipPopCallConfiguration.gridDim__val); } + if (data->args.__hipPopCallConfiguration.blockDim == NULL) oss << ", blockDim=NULL"; + else { oss << ", blockDim="; roctracer::hip_support::detail::operator<<(oss, data->args.__hipPopCallConfiguration.blockDim__val); } + if (data->args.__hipPopCallConfiguration.sharedMem == NULL) oss << ", sharedMem=NULL"; + else { oss << ", sharedMem="; roctracer::hip_support::detail::operator<<(oss, data->args.__hipPopCallConfiguration.sharedMem__val); } + if (data->args.__hipPopCallConfiguration.stream == NULL) oss << ", stream=NULL"; + else { oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.__hipPopCallConfiguration.stream__val); } + oss << ")"; + break; + case HIP_API_ID___hipPushCallConfiguration: + oss << "__hipPushCallConfiguration("; + oss << "gridDim="; roctracer::hip_support::detail::operator<<(oss, data->args.__hipPushCallConfiguration.gridDim); + oss << ", blockDim="; roctracer::hip_support::detail::operator<<(oss, data->args.__hipPushCallConfiguration.blockDim); + oss << ", sharedMem="; roctracer::hip_support::detail::operator<<(oss, data->args.__hipPushCallConfiguration.sharedMem); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.__hipPushCallConfiguration.stream); + oss << ")"; + break; + case HIP_API_ID_hipArray3DCreate: + oss << "hipArray3DCreate("; + if (data->args.hipArray3DCreate.array == NULL) oss << "array=NULL"; + else { oss << "array="; roctracer::hip_support::detail::operator<<(oss, data->args.hipArray3DCreate.array__val); } + if (data->args.hipArray3DCreate.pAllocateArray == NULL) oss << ", pAllocateArray=NULL"; + else { oss << ", pAllocateArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipArray3DCreate.pAllocateArray__val); } + oss << ")"; + break; + case HIP_API_ID_hipArray3DGetDescriptor: + oss << "hipArray3DGetDescriptor("; + if (data->args.hipArray3DGetDescriptor.pArrayDescriptor == NULL) oss << "pArrayDescriptor=NULL"; + else { oss << "pArrayDescriptor="; roctracer::hip_support::detail::operator<<(oss, data->args.hipArray3DGetDescriptor.pArrayDescriptor__val); } + oss << ", array="; roctracer::hip_support::detail::operator<<(oss, data->args.hipArray3DGetDescriptor.array); + oss << ")"; + break; + case HIP_API_ID_hipArrayCreate: + oss << "hipArrayCreate("; + if (data->args.hipArrayCreate.pHandle == NULL) oss << "pHandle=NULL"; + else { oss << "pHandle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipArrayCreate.pHandle__val); } + if (data->args.hipArrayCreate.pAllocateArray == NULL) oss << ", pAllocateArray=NULL"; + else { oss << ", pAllocateArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipArrayCreate.pAllocateArray__val); } + oss << ")"; + break; + case HIP_API_ID_hipArrayDestroy: + oss << "hipArrayDestroy("; + oss << "array="; roctracer::hip_support::detail::operator<<(oss, data->args.hipArrayDestroy.array); + oss << ")"; + break; + case HIP_API_ID_hipArrayGetDescriptor: + oss << "hipArrayGetDescriptor("; + if (data->args.hipArrayGetDescriptor.pArrayDescriptor == NULL) oss << "pArrayDescriptor=NULL"; + else { oss << "pArrayDescriptor="; roctracer::hip_support::detail::operator<<(oss, data->args.hipArrayGetDescriptor.pArrayDescriptor__val); } + oss << ", array="; roctracer::hip_support::detail::operator<<(oss, data->args.hipArrayGetDescriptor.array); + oss << ")"; + break; + case HIP_API_ID_hipArrayGetInfo: + oss << "hipArrayGetInfo("; + if (data->args.hipArrayGetInfo.desc == NULL) oss << "desc=NULL"; + else { oss << "desc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipArrayGetInfo.desc__val); } + if (data->args.hipArrayGetInfo.extent == NULL) oss << ", extent=NULL"; + else { oss << ", extent="; roctracer::hip_support::detail::operator<<(oss, data->args.hipArrayGetInfo.extent__val); } + if (data->args.hipArrayGetInfo.flags == NULL) oss << ", flags=NULL"; + else { oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipArrayGetInfo.flags__val); } + oss << ", array="; roctracer::hip_support::detail::operator<<(oss, data->args.hipArrayGetInfo.array); + oss << ")"; + break; + case HIP_API_ID_hipChooseDeviceR0000: + oss << "hipChooseDeviceR0000("; + if (data->args.hipChooseDeviceR0000.device == NULL) oss << "device=NULL"; + else { oss << "device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipChooseDeviceR0000.device__val); } + if (data->args.hipChooseDeviceR0000.prop == NULL) oss << ", prop=NULL"; + else { oss << ", prop="; roctracer::hip_support::detail::operator<<(oss, data->args.hipChooseDeviceR0000.prop__val); } + oss << ")"; + break; + case HIP_API_ID_hipChooseDeviceR0600: + oss << "hipChooseDeviceR0600("; + if (data->args.hipChooseDeviceR0600.device == NULL) oss << "device=NULL"; + else { oss << "device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipChooseDeviceR0600.device__val); } + if (data->args.hipChooseDeviceR0600.prop == NULL) oss << ", prop=NULL"; + else { oss << ", prop="; roctracer::hip_support::detail::operator<<(oss, data->args.hipChooseDeviceR0600.prop__val); } + oss << ")"; + break; + case HIP_API_ID_hipConfigureCall: + oss << "hipConfigureCall("; + oss << "gridDim="; roctracer::hip_support::detail::operator<<(oss, data->args.hipConfigureCall.gridDim); + oss << ", blockDim="; roctracer::hip_support::detail::operator<<(oss, data->args.hipConfigureCall.blockDim); + oss << ", sharedMem="; roctracer::hip_support::detail::operator<<(oss, data->args.hipConfigureCall.sharedMem); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipConfigureCall.stream); + oss << ")"; + break; + case HIP_API_ID_hipCreateSurfaceObject: + oss << "hipCreateSurfaceObject("; + if (data->args.hipCreateSurfaceObject.pSurfObject == NULL) oss << "pSurfObject=NULL"; + else { oss << "pSurfObject="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCreateSurfaceObject.pSurfObject__val); } + if (data->args.hipCreateSurfaceObject.pResDesc == NULL) oss << ", pResDesc=NULL"; + else { oss << ", pResDesc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCreateSurfaceObject.pResDesc__val); } + oss << ")"; + break; + case HIP_API_ID_hipCtxCreate: + oss << "hipCtxCreate("; + if (data->args.hipCtxCreate.ctx == NULL) oss << "ctx=NULL"; + else { oss << "ctx="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxCreate.ctx__val); } + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxCreate.flags); + oss << ", device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxCreate.device); + oss << ")"; + break; + case HIP_API_ID_hipCtxDestroy: + oss << "hipCtxDestroy("; + oss << "ctx="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxDestroy.ctx); + oss << ")"; + break; + case HIP_API_ID_hipCtxDisablePeerAccess: + oss << "hipCtxDisablePeerAccess("; + oss << "peerCtx="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxDisablePeerAccess.peerCtx); + oss << ")"; + break; + case HIP_API_ID_hipCtxEnablePeerAccess: + oss << "hipCtxEnablePeerAccess("; + oss << "peerCtx="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxEnablePeerAccess.peerCtx); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxEnablePeerAccess.flags); + oss << ")"; + break; + case HIP_API_ID_hipCtxGetApiVersion: + oss << "hipCtxGetApiVersion("; + oss << "ctx="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxGetApiVersion.ctx); + if (data->args.hipCtxGetApiVersion.apiVersion == NULL) oss << ", apiVersion=NULL"; + else { oss << ", apiVersion="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxGetApiVersion.apiVersion__val); } + oss << ")"; + break; + case HIP_API_ID_hipCtxGetCacheConfig: + oss << "hipCtxGetCacheConfig("; + if (data->args.hipCtxGetCacheConfig.cacheConfig == NULL) oss << "cacheConfig=NULL"; + else { oss << "cacheConfig="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxGetCacheConfig.cacheConfig__val); } + oss << ")"; + break; + case HIP_API_ID_hipCtxGetCurrent: + oss << "hipCtxGetCurrent("; + if (data->args.hipCtxGetCurrent.ctx == NULL) oss << "ctx=NULL"; + else { oss << "ctx="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxGetCurrent.ctx__val); } + oss << ")"; + break; + case HIP_API_ID_hipCtxGetDevice: + oss << "hipCtxGetDevice("; + if (data->args.hipCtxGetDevice.device == NULL) oss << "device=NULL"; + else { oss << "device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxGetDevice.device__val); } + oss << ")"; + break; + case HIP_API_ID_hipCtxGetFlags: + oss << "hipCtxGetFlags("; + if (data->args.hipCtxGetFlags.flags == NULL) oss << "flags=NULL"; + else { oss << "flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxGetFlags.flags__val); } + oss << ")"; + break; + case HIP_API_ID_hipCtxGetSharedMemConfig: + oss << "hipCtxGetSharedMemConfig("; + if (data->args.hipCtxGetSharedMemConfig.pConfig == NULL) oss << "pConfig=NULL"; + else { oss << "pConfig="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxGetSharedMemConfig.pConfig__val); } + oss << ")"; + break; + case HIP_API_ID_hipCtxPopCurrent: + oss << "hipCtxPopCurrent("; + if (data->args.hipCtxPopCurrent.ctx == NULL) oss << "ctx=NULL"; + else { oss << "ctx="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxPopCurrent.ctx__val); } + oss << ")"; + break; + case HIP_API_ID_hipCtxPushCurrent: + oss << "hipCtxPushCurrent("; + oss << "ctx="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxPushCurrent.ctx); + oss << ")"; + break; + case HIP_API_ID_hipCtxSetCacheConfig: + oss << "hipCtxSetCacheConfig("; + oss << "cacheConfig="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxSetCacheConfig.cacheConfig); + oss << ")"; + break; + case HIP_API_ID_hipCtxSetCurrent: + oss << "hipCtxSetCurrent("; + oss << "ctx="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxSetCurrent.ctx); + oss << ")"; + break; + case HIP_API_ID_hipCtxSetSharedMemConfig: + oss << "hipCtxSetSharedMemConfig("; + oss << "config="; roctracer::hip_support::detail::operator<<(oss, data->args.hipCtxSetSharedMemConfig.config); + oss << ")"; + break; + case HIP_API_ID_hipCtxSynchronize: + oss << "hipCtxSynchronize("; + oss << ")"; + break; + case HIP_API_ID_hipDestroyExternalMemory: + oss << "hipDestroyExternalMemory("; + oss << "extMem="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDestroyExternalMemory.extMem); + oss << ")"; + break; + case HIP_API_ID_hipDestroyExternalSemaphore: + oss << "hipDestroyExternalSemaphore("; + oss << "extSem="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDestroyExternalSemaphore.extSem); + oss << ")"; + break; + case HIP_API_ID_hipDestroySurfaceObject: + oss << "hipDestroySurfaceObject("; + oss << "surfaceObject="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDestroySurfaceObject.surfaceObject); + oss << ")"; + break; + case HIP_API_ID_hipDeviceCanAccessPeer: + oss << "hipDeviceCanAccessPeer("; + if (data->args.hipDeviceCanAccessPeer.canAccessPeer == NULL) oss << "canAccessPeer=NULL"; + else { oss << "canAccessPeer="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceCanAccessPeer.canAccessPeer__val); } + oss << ", deviceId="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceCanAccessPeer.deviceId); + oss << ", peerDeviceId="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceCanAccessPeer.peerDeviceId); + oss << ")"; + break; + case HIP_API_ID_hipDeviceComputeCapability: + oss << "hipDeviceComputeCapability("; + if (data->args.hipDeviceComputeCapability.major == NULL) oss << "major=NULL"; + else { oss << "major="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceComputeCapability.major__val); } + if (data->args.hipDeviceComputeCapability.minor == NULL) oss << ", minor=NULL"; + else { oss << ", minor="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceComputeCapability.minor__val); } + oss << ", device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceComputeCapability.device); + oss << ")"; + break; + case HIP_API_ID_hipDeviceDisablePeerAccess: + oss << "hipDeviceDisablePeerAccess("; + oss << "peerDeviceId="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceDisablePeerAccess.peerDeviceId); + oss << ")"; + break; + case HIP_API_ID_hipDeviceEnablePeerAccess: + oss << "hipDeviceEnablePeerAccess("; + oss << "peerDeviceId="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceEnablePeerAccess.peerDeviceId); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceEnablePeerAccess.flags); + oss << ")"; + break; + case HIP_API_ID_hipDeviceGet: + oss << "hipDeviceGet("; + if (data->args.hipDeviceGet.device == NULL) oss << "device=NULL"; + else { oss << "device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGet.device__val); } + oss << ", ordinal="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGet.ordinal); + oss << ")"; + break; + case HIP_API_ID_hipDeviceGetAttribute: + oss << "hipDeviceGetAttribute("; + if (data->args.hipDeviceGetAttribute.pi == NULL) oss << "pi=NULL"; + else { oss << "pi="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetAttribute.pi__val); } + oss << ", attr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetAttribute.attr); + oss << ", deviceId="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetAttribute.deviceId); + oss << ")"; + break; + case HIP_API_ID_hipDeviceGetByPCIBusId: + oss << "hipDeviceGetByPCIBusId("; + if (data->args.hipDeviceGetByPCIBusId.device == NULL) oss << "device=NULL"; + else { oss << "device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetByPCIBusId.device__val); } + if (data->args.hipDeviceGetByPCIBusId.pciBusId == NULL) oss << ", pciBusId=NULL"; + else { oss << ", pciBusId="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetByPCIBusId.pciBusId__val); } + oss << ")"; + break; + case HIP_API_ID_hipDeviceGetCacheConfig: + oss << "hipDeviceGetCacheConfig("; + if (data->args.hipDeviceGetCacheConfig.cacheConfig == NULL) oss << "cacheConfig=NULL"; + else { oss << "cacheConfig="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetCacheConfig.cacheConfig__val); } + oss << ")"; + break; + case HIP_API_ID_hipDeviceGetDefaultMemPool: + oss << "hipDeviceGetDefaultMemPool("; + if (data->args.hipDeviceGetDefaultMemPool.mem_pool == NULL) oss << "mem_pool=NULL"; + else { oss << "mem_pool="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetDefaultMemPool.mem_pool__val); } + oss << ", device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetDefaultMemPool.device); + oss << ")"; + break; + case HIP_API_ID_hipDeviceGetGraphMemAttribute: + oss << "hipDeviceGetGraphMemAttribute("; + oss << "device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetGraphMemAttribute.device); + oss << ", attr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetGraphMemAttribute.attr); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetGraphMemAttribute.value); + oss << ")"; + break; + case HIP_API_ID_hipDeviceGetLimit: + oss << "hipDeviceGetLimit("; + if (data->args.hipDeviceGetLimit.pValue == NULL) oss << "pValue=NULL"; + else { oss << "pValue="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetLimit.pValue__val); } + oss << ", limit="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetLimit.limit); + oss << ")"; + break; + case HIP_API_ID_hipDeviceGetMemPool: + oss << "hipDeviceGetMemPool("; + if (data->args.hipDeviceGetMemPool.mem_pool == NULL) oss << "mem_pool=NULL"; + else { oss << "mem_pool="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetMemPool.mem_pool__val); } + oss << ", device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetMemPool.device); + oss << ")"; + break; + case HIP_API_ID_hipDeviceGetName: + oss << "hipDeviceGetName("; + if (data->args.hipDeviceGetName.name == NULL) oss << "name=NULL"; + else { oss << "name="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetName.name__val); } + oss << ", len="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetName.len); + oss << ", device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetName.device); + oss << ")"; + break; + case HIP_API_ID_hipDeviceGetP2PAttribute: + oss << "hipDeviceGetP2PAttribute("; + if (data->args.hipDeviceGetP2PAttribute.value == NULL) oss << "value=NULL"; + else { oss << "value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetP2PAttribute.value__val); } + oss << ", attr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetP2PAttribute.attr); + oss << ", srcDevice="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetP2PAttribute.srcDevice); + oss << ", dstDevice="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetP2PAttribute.dstDevice); + oss << ")"; + break; + case HIP_API_ID_hipDeviceGetPCIBusId: + oss << "hipDeviceGetPCIBusId("; + if (data->args.hipDeviceGetPCIBusId.pciBusId == NULL) oss << "pciBusId=NULL"; + else { oss << "pciBusId="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetPCIBusId.pciBusId__val); } + oss << ", len="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetPCIBusId.len); + oss << ", device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetPCIBusId.device); + oss << ")"; + break; + case HIP_API_ID_hipDeviceGetSharedMemConfig: + oss << "hipDeviceGetSharedMemConfig("; + if (data->args.hipDeviceGetSharedMemConfig.pConfig == NULL) oss << "pConfig=NULL"; + else { oss << "pConfig="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetSharedMemConfig.pConfig__val); } + oss << ")"; + break; + case HIP_API_ID_hipDeviceGetStreamPriorityRange: + oss << "hipDeviceGetStreamPriorityRange("; + if (data->args.hipDeviceGetStreamPriorityRange.leastPriority == NULL) oss << "leastPriority=NULL"; + else { oss << "leastPriority="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetStreamPriorityRange.leastPriority__val); } + if (data->args.hipDeviceGetStreamPriorityRange.greatestPriority == NULL) oss << ", greatestPriority=NULL"; + else { oss << ", greatestPriority="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetStreamPriorityRange.greatestPriority__val); } + oss << ")"; + break; + case HIP_API_ID_hipDeviceGetUuid: + oss << "hipDeviceGetUuid("; + if (data->args.hipDeviceGetUuid.uuid == NULL) oss << "uuid=NULL"; + else { oss << "uuid="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetUuid.uuid__val); } + oss << ", device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGetUuid.device); + oss << ")"; + break; + case HIP_API_ID_hipDeviceGraphMemTrim: + oss << "hipDeviceGraphMemTrim("; + oss << "device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceGraphMemTrim.device); + oss << ")"; + break; + case HIP_API_ID_hipDevicePrimaryCtxGetState: + oss << "hipDevicePrimaryCtxGetState("; + oss << "dev="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDevicePrimaryCtxGetState.dev); + if (data->args.hipDevicePrimaryCtxGetState.flags == NULL) oss << ", flags=NULL"; + else { oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDevicePrimaryCtxGetState.flags__val); } + if (data->args.hipDevicePrimaryCtxGetState.active == NULL) oss << ", active=NULL"; + else { oss << ", active="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDevicePrimaryCtxGetState.active__val); } + oss << ")"; + break; + case HIP_API_ID_hipDevicePrimaryCtxRelease: + oss << "hipDevicePrimaryCtxRelease("; + oss << "dev="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDevicePrimaryCtxRelease.dev); + oss << ")"; + break; + case HIP_API_ID_hipDevicePrimaryCtxReset: + oss << "hipDevicePrimaryCtxReset("; + oss << "dev="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDevicePrimaryCtxReset.dev); + oss << ")"; + break; + case HIP_API_ID_hipDevicePrimaryCtxRetain: + oss << "hipDevicePrimaryCtxRetain("; + if (data->args.hipDevicePrimaryCtxRetain.pctx == NULL) oss << "pctx=NULL"; + else { oss << "pctx="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDevicePrimaryCtxRetain.pctx__val); } + oss << ", dev="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDevicePrimaryCtxRetain.dev); + oss << ")"; + break; + case HIP_API_ID_hipDevicePrimaryCtxSetFlags: + oss << "hipDevicePrimaryCtxSetFlags("; + oss << "dev="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDevicePrimaryCtxSetFlags.dev); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDevicePrimaryCtxSetFlags.flags); + oss << ")"; + break; + case HIP_API_ID_hipDeviceReset: + oss << "hipDeviceReset("; + oss << ")"; + break; + case HIP_API_ID_hipDeviceSetCacheConfig: + oss << "hipDeviceSetCacheConfig("; + oss << "cacheConfig="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceSetCacheConfig.cacheConfig); + oss << ")"; + break; + case HIP_API_ID_hipDeviceSetGraphMemAttribute: + oss << "hipDeviceSetGraphMemAttribute("; + oss << "device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceSetGraphMemAttribute.device); + oss << ", attr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceSetGraphMemAttribute.attr); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceSetGraphMemAttribute.value); + oss << ")"; + break; + case HIP_API_ID_hipDeviceSetLimit: + oss << "hipDeviceSetLimit("; + oss << "limit="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceSetLimit.limit); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceSetLimit.value); + oss << ")"; + break; + case HIP_API_ID_hipDeviceSetMemPool: + oss << "hipDeviceSetMemPool("; + oss << "device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceSetMemPool.device); + oss << ", mem_pool="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceSetMemPool.mem_pool); + oss << ")"; + break; + case HIP_API_ID_hipDeviceSetSharedMemConfig: + oss << "hipDeviceSetSharedMemConfig("; + oss << "config="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceSetSharedMemConfig.config); + oss << ")"; + break; + case HIP_API_ID_hipDeviceSynchronize: + oss << "hipDeviceSynchronize("; + oss << ")"; + break; + case HIP_API_ID_hipDeviceTotalMem: + oss << "hipDeviceTotalMem("; + if (data->args.hipDeviceTotalMem.bytes == NULL) oss << "bytes=NULL"; + else { oss << "bytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceTotalMem.bytes__val); } + oss << ", device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDeviceTotalMem.device); + oss << ")"; + break; + case HIP_API_ID_hipDriverGetVersion: + oss << "hipDriverGetVersion("; + if (data->args.hipDriverGetVersion.driverVersion == NULL) oss << "driverVersion=NULL"; + else { oss << "driverVersion="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDriverGetVersion.driverVersion__val); } + oss << ")"; + break; + case HIP_API_ID_hipDrvGraphAddMemcpyNode: + oss << "hipDrvGraphAddMemcpyNode("; + if (data->args.hipDrvGraphAddMemcpyNode.phGraphNode == NULL) oss << "phGraphNode=NULL"; + else { oss << "phGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvGraphAddMemcpyNode.phGraphNode__val); } + oss << ", hGraph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvGraphAddMemcpyNode.hGraph); + if (data->args.hipDrvGraphAddMemcpyNode.dependencies == NULL) oss << ", dependencies=NULL"; + else { oss << ", dependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvGraphAddMemcpyNode.dependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvGraphAddMemcpyNode.numDependencies); + if (data->args.hipDrvGraphAddMemcpyNode.copyParams == NULL) oss << ", copyParams=NULL"; + else { oss << ", copyParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvGraphAddMemcpyNode.copyParams__val); } + oss << ", ctx="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvGraphAddMemcpyNode.ctx); + oss << ")"; + break; + case HIP_API_ID_hipDrvGraphAddMemsetNode: + oss << "hipDrvGraphAddMemsetNode("; + if (data->args.hipDrvGraphAddMemsetNode.phGraphNode == NULL) oss << "phGraphNode=NULL"; + else { oss << "phGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvGraphAddMemsetNode.phGraphNode__val); } + oss << ", hGraph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvGraphAddMemsetNode.hGraph); + if (data->args.hipDrvGraphAddMemsetNode.dependencies == NULL) oss << ", dependencies=NULL"; + else { oss << ", dependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvGraphAddMemsetNode.dependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvGraphAddMemsetNode.numDependencies); + if (data->args.hipDrvGraphAddMemsetNode.memsetParams == NULL) oss << ", memsetParams=NULL"; + else { oss << ", memsetParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvGraphAddMemsetNode.memsetParams__val); } + oss << ", ctx="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvGraphAddMemsetNode.ctx); + oss << ")"; + break; + case HIP_API_ID_hipDrvMemcpy2DUnaligned: + oss << "hipDrvMemcpy2DUnaligned("; + if (data->args.hipDrvMemcpy2DUnaligned.pCopy == NULL) oss << "pCopy=NULL"; + else { oss << "pCopy="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvMemcpy2DUnaligned.pCopy__val); } + oss << ")"; + break; + case HIP_API_ID_hipDrvMemcpy3D: + oss << "hipDrvMemcpy3D("; + if (data->args.hipDrvMemcpy3D.pCopy == NULL) oss << "pCopy=NULL"; + else { oss << "pCopy="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvMemcpy3D.pCopy__val); } + oss << ")"; + break; + case HIP_API_ID_hipDrvMemcpy3DAsync: + oss << "hipDrvMemcpy3DAsync("; + if (data->args.hipDrvMemcpy3DAsync.pCopy == NULL) oss << "pCopy=NULL"; + else { oss << "pCopy="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvMemcpy3DAsync.pCopy__val); } + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvMemcpy3DAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipDrvPointerGetAttributes: + oss << "hipDrvPointerGetAttributes("; + oss << "numAttributes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvPointerGetAttributes.numAttributes); + if (data->args.hipDrvPointerGetAttributes.attributes == NULL) oss << ", attributes=NULL"; + else { oss << ", attributes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvPointerGetAttributes.attributes__val); } + if (data->args.hipDrvPointerGetAttributes.data == NULL) oss << ", data=NULL"; + else { oss << ", data="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvPointerGetAttributes.data__val); } + oss << ", ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipDrvPointerGetAttributes.ptr); + oss << ")"; + break; + case HIP_API_ID_hipEventCreate: + oss << "hipEventCreate("; + if (data->args.hipEventCreate.event == NULL) oss << "event=NULL"; + else { oss << "event="; roctracer::hip_support::detail::operator<<(oss, data->args.hipEventCreate.event__val); } + oss << ")"; + break; + case HIP_API_ID_hipEventCreateWithFlags: + oss << "hipEventCreateWithFlags("; + if (data->args.hipEventCreateWithFlags.event == NULL) oss << "event=NULL"; + else { oss << "event="; roctracer::hip_support::detail::operator<<(oss, data->args.hipEventCreateWithFlags.event__val); } + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipEventCreateWithFlags.flags); + oss << ")"; + break; + case HIP_API_ID_hipEventDestroy: + oss << "hipEventDestroy("; + oss << "event="; roctracer::hip_support::detail::operator<<(oss, data->args.hipEventDestroy.event); + oss << ")"; + break; + case HIP_API_ID_hipEventElapsedTime: + oss << "hipEventElapsedTime("; + if (data->args.hipEventElapsedTime.ms == NULL) oss << "ms=NULL"; + else { oss << "ms="; roctracer::hip_support::detail::operator<<(oss, data->args.hipEventElapsedTime.ms__val); } + oss << ", start="; roctracer::hip_support::detail::operator<<(oss, data->args.hipEventElapsedTime.start); + oss << ", stop="; roctracer::hip_support::detail::operator<<(oss, data->args.hipEventElapsedTime.stop); + oss << ")"; + break; + case HIP_API_ID_hipEventQuery: + oss << "hipEventQuery("; + oss << "event="; roctracer::hip_support::detail::operator<<(oss, data->args.hipEventQuery.event); + oss << ")"; + break; + case HIP_API_ID_hipEventRecord: + oss << "hipEventRecord("; + oss << "event="; roctracer::hip_support::detail::operator<<(oss, data->args.hipEventRecord.event); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipEventRecord.stream); + oss << ")"; + break; + case HIP_API_ID_hipEventSynchronize: + oss << "hipEventSynchronize("; + oss << "event="; roctracer::hip_support::detail::operator<<(oss, data->args.hipEventSynchronize.event); + oss << ")"; + break; + case HIP_API_ID_hipExtGetLastError: + oss << "hipExtGetLastError("; + oss << ")"; + break; + case HIP_API_ID_hipExtGetLinkTypeAndHopCount: + oss << "hipExtGetLinkTypeAndHopCount("; + oss << "device1="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtGetLinkTypeAndHopCount.device1); + oss << ", device2="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtGetLinkTypeAndHopCount.device2); + if (data->args.hipExtGetLinkTypeAndHopCount.linktype == NULL) oss << ", linktype=NULL"; + else { oss << ", linktype="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtGetLinkTypeAndHopCount.linktype__val); } + if (data->args.hipExtGetLinkTypeAndHopCount.hopcount == NULL) oss << ", hopcount=NULL"; + else { oss << ", hopcount="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtGetLinkTypeAndHopCount.hopcount__val); } + oss << ")"; + break; + case HIP_API_ID_hipExtLaunchKernel: + oss << "hipExtLaunchKernel("; + oss << "function_address="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtLaunchKernel.function_address); + oss << ", numBlocks="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtLaunchKernel.numBlocks); + oss << ", dimBlocks="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtLaunchKernel.dimBlocks); + if (data->args.hipExtLaunchKernel.args == NULL) oss << ", args=NULL"; + else { oss << ", args="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtLaunchKernel.args__val); } + oss << ", sharedMemBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtLaunchKernel.sharedMemBytes); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtLaunchKernel.stream); + oss << ", startEvent="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtLaunchKernel.startEvent); + oss << ", stopEvent="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtLaunchKernel.stopEvent); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtLaunchKernel.flags); + oss << ")"; + break; + case HIP_API_ID_hipExtLaunchMultiKernelMultiDevice: + oss << "hipExtLaunchMultiKernelMultiDevice("; + if (data->args.hipExtLaunchMultiKernelMultiDevice.launchParamsList == NULL) oss << "launchParamsList=NULL"; + else { oss << "launchParamsList="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtLaunchMultiKernelMultiDevice.launchParamsList__val); } + oss << ", numDevices="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtLaunchMultiKernelMultiDevice.numDevices); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtLaunchMultiKernelMultiDevice.flags); + oss << ")"; + break; + case HIP_API_ID_hipExtMallocWithFlags: + oss << "hipExtMallocWithFlags("; + if (data->args.hipExtMallocWithFlags.ptr == NULL) oss << "ptr=NULL"; + else { oss << "ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtMallocWithFlags.ptr__val); } + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtMallocWithFlags.sizeBytes); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtMallocWithFlags.flags); + oss << ")"; + break; + case HIP_API_ID_hipExtModuleLaunchKernel: + oss << "hipExtModuleLaunchKernel("; + oss << "f="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtModuleLaunchKernel.f); + oss << ", globalWorkSizeX="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtModuleLaunchKernel.globalWorkSizeX); + oss << ", globalWorkSizeY="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtModuleLaunchKernel.globalWorkSizeY); + oss << ", globalWorkSizeZ="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtModuleLaunchKernel.globalWorkSizeZ); + oss << ", localWorkSizeX="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtModuleLaunchKernel.localWorkSizeX); + oss << ", localWorkSizeY="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtModuleLaunchKernel.localWorkSizeY); + oss << ", localWorkSizeZ="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtModuleLaunchKernel.localWorkSizeZ); + oss << ", sharedMemBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtModuleLaunchKernel.sharedMemBytes); + oss << ", hStream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtModuleLaunchKernel.hStream); + if (data->args.hipExtModuleLaunchKernel.kernelParams == NULL) oss << ", kernelParams=NULL"; + else { oss << ", kernelParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtModuleLaunchKernel.kernelParams__val); } + if (data->args.hipExtModuleLaunchKernel.extra == NULL) oss << ", extra=NULL"; + else { oss << ", extra="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtModuleLaunchKernel.extra__val); } + oss << ", startEvent="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtModuleLaunchKernel.startEvent); + oss << ", stopEvent="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtModuleLaunchKernel.stopEvent); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtModuleLaunchKernel.flags); + oss << ")"; + break; + case HIP_API_ID_hipExtStreamCreateWithCUMask: + oss << "hipExtStreamCreateWithCUMask("; + if (data->args.hipExtStreamCreateWithCUMask.stream == NULL) oss << "stream=NULL"; + else { oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtStreamCreateWithCUMask.stream__val); } + oss << ", cuMaskSize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtStreamCreateWithCUMask.cuMaskSize); + if (data->args.hipExtStreamCreateWithCUMask.cuMask == NULL) oss << ", cuMask=NULL"; + else { oss << ", cuMask="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtStreamCreateWithCUMask.cuMask__val); } + oss << ")"; + break; + case HIP_API_ID_hipExtStreamGetCUMask: + oss << "hipExtStreamGetCUMask("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtStreamGetCUMask.stream); + oss << ", cuMaskSize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtStreamGetCUMask.cuMaskSize); + if (data->args.hipExtStreamGetCUMask.cuMask == NULL) oss << ", cuMask=NULL"; + else { oss << ", cuMask="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExtStreamGetCUMask.cuMask__val); } + oss << ")"; + break; + case HIP_API_ID_hipExternalMemoryGetMappedBuffer: + oss << "hipExternalMemoryGetMappedBuffer("; + if (data->args.hipExternalMemoryGetMappedBuffer.devPtr == NULL) oss << "devPtr=NULL"; + else { oss << "devPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExternalMemoryGetMappedBuffer.devPtr__val); } + oss << ", extMem="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExternalMemoryGetMappedBuffer.extMem); + if (data->args.hipExternalMemoryGetMappedBuffer.bufferDesc == NULL) oss << ", bufferDesc=NULL"; + else { oss << ", bufferDesc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExternalMemoryGetMappedBuffer.bufferDesc__val); } + oss << ")"; + break; + case HIP_API_ID_hipExternalMemoryGetMappedMipmappedArray: + oss << "hipExternalMemoryGetMappedMipmappedArray("; + if (data->args.hipExternalMemoryGetMappedMipmappedArray.mipmap == NULL) oss << "mipmap=NULL"; + else { oss << "mipmap="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExternalMemoryGetMappedMipmappedArray.mipmap__val); } + oss << ", extMem="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExternalMemoryGetMappedMipmappedArray.extMem); + if (data->args.hipExternalMemoryGetMappedMipmappedArray.mipmapDesc == NULL) oss << ", mipmapDesc=NULL"; + else { oss << ", mipmapDesc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipExternalMemoryGetMappedMipmappedArray.mipmapDesc__val); } + oss << ")"; + break; + case HIP_API_ID_hipFree: + oss << "hipFree("; + oss << "ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFree.ptr); + oss << ")"; + break; + case HIP_API_ID_hipFreeArray: + oss << "hipFreeArray("; + oss << "array="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFreeArray.array); + oss << ")"; + break; + case HIP_API_ID_hipFreeAsync: + oss << "hipFreeAsync("; + oss << "dev_ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFreeAsync.dev_ptr); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFreeAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipFreeHost: + oss << "hipFreeHost("; + oss << "ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFreeHost.ptr); + oss << ")"; + break; + case HIP_API_ID_hipFreeMipmappedArray: + oss << "hipFreeMipmappedArray("; + oss << "mipmappedArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFreeMipmappedArray.mipmappedArray); + oss << ")"; + break; + case HIP_API_ID_hipFuncGetAttribute: + oss << "hipFuncGetAttribute("; + if (data->args.hipFuncGetAttribute.value == NULL) oss << "value=NULL"; + else { oss << "value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFuncGetAttribute.value__val); } + oss << ", attrib="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFuncGetAttribute.attrib); + oss << ", hfunc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFuncGetAttribute.hfunc); + oss << ")"; + break; + case HIP_API_ID_hipFuncGetAttributes: + oss << "hipFuncGetAttributes("; + if (data->args.hipFuncGetAttributes.attr == NULL) oss << "attr=NULL"; + else { oss << "attr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFuncGetAttributes.attr__val); } + oss << ", func="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFuncGetAttributes.func); + oss << ")"; + break; + case HIP_API_ID_hipFuncSetAttribute: + oss << "hipFuncSetAttribute("; + oss << "func="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFuncSetAttribute.func); + oss << ", attr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFuncSetAttribute.attr); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFuncSetAttribute.value); + oss << ")"; + break; + case HIP_API_ID_hipFuncSetCacheConfig: + oss << "hipFuncSetCacheConfig("; + oss << "func="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFuncSetCacheConfig.func); + oss << ", config="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFuncSetCacheConfig.config); + oss << ")"; + break; + case HIP_API_ID_hipFuncSetSharedMemConfig: + oss << "hipFuncSetSharedMemConfig("; + oss << "func="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFuncSetSharedMemConfig.func); + oss << ", config="; roctracer::hip_support::detail::operator<<(oss, data->args.hipFuncSetSharedMemConfig.config); + oss << ")"; + break; + case HIP_API_ID_hipGLGetDevices: + oss << "hipGLGetDevices("; + if (data->args.hipGLGetDevices.pHipDeviceCount == NULL) oss << "pHipDeviceCount=NULL"; + else { oss << "pHipDeviceCount="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGLGetDevices.pHipDeviceCount__val); } + if (data->args.hipGLGetDevices.pHipDevices == NULL) oss << ", pHipDevices=NULL"; + else { oss << ", pHipDevices="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGLGetDevices.pHipDevices__val); } + oss << ", hipDeviceCount="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGLGetDevices.hipDeviceCount); + oss << ", deviceList="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGLGetDevices.deviceList); + oss << ")"; + break; + case HIP_API_ID_hipGetChannelDesc: + oss << "hipGetChannelDesc("; + if (data->args.hipGetChannelDesc.desc == NULL) oss << "desc=NULL"; + else { oss << "desc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetChannelDesc.desc__val); } + oss << ", array="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetChannelDesc.array); + oss << ")"; + break; + case HIP_API_ID_hipGetDevice: + oss << "hipGetDevice("; + if (data->args.hipGetDevice.deviceId == NULL) oss << "deviceId=NULL"; + else { oss << "deviceId="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetDevice.deviceId__val); } + oss << ")"; + break; + case HIP_API_ID_hipGetDeviceCount: + oss << "hipGetDeviceCount("; + if (data->args.hipGetDeviceCount.count == NULL) oss << "count=NULL"; + else { oss << "count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetDeviceCount.count__val); } + oss << ")"; + break; + case HIP_API_ID_hipGetDeviceFlags: + oss << "hipGetDeviceFlags("; + if (data->args.hipGetDeviceFlags.flags == NULL) oss << "flags=NULL"; + else { oss << "flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetDeviceFlags.flags__val); } + oss << ")"; + break; + case HIP_API_ID_hipGetDevicePropertiesR0000: + oss << "hipGetDevicePropertiesR0000("; + if (data->args.hipGetDevicePropertiesR0000.prop == NULL) oss << "prop=NULL"; + else { oss << "prop="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetDevicePropertiesR0000.prop__val); } + oss << ", device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetDevicePropertiesR0000.device); + oss << ")"; + break; + case HIP_API_ID_hipGetDevicePropertiesR0600: + oss << "hipGetDevicePropertiesR0600("; + if (data->args.hipGetDevicePropertiesR0600.prop == NULL) oss << "prop=NULL"; + else { oss << "prop="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetDevicePropertiesR0600.prop__val); } + oss << ", deviceId="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetDevicePropertiesR0600.deviceId); + oss << ")"; + break; + case HIP_API_ID_hipGetErrorString: + oss << "hipGetErrorString("; + oss << ")"; + break; + case HIP_API_ID_hipGetFuncBySymbol: + oss << "hipGetFuncBySymbol("; + if (data->args.hipGetFuncBySymbol.functionPtr == NULL) oss << "functionPtr=NULL"; + else { oss << "functionPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetFuncBySymbol.functionPtr__val); } + oss << ", symbolPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetFuncBySymbol.symbolPtr); + oss << ")"; + break; + case HIP_API_ID_hipGetLastError: + oss << "hipGetLastError("; + oss << ")"; + break; + case HIP_API_ID_hipGetMipmappedArrayLevel: + oss << "hipGetMipmappedArrayLevel("; + if (data->args.hipGetMipmappedArrayLevel.levelArray == NULL) oss << "levelArray=NULL"; + else { oss << "levelArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetMipmappedArrayLevel.levelArray__val); } + oss << ", mipmappedArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetMipmappedArrayLevel.mipmappedArray); + oss << ", level="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetMipmappedArrayLevel.level); + oss << ")"; + break; + case HIP_API_ID_hipGetProcAddress: + oss << "hipGetProcAddress("; + if (data->args.hipGetProcAddress.symbol == NULL) oss << "symbol=NULL"; + else { oss << "symbol="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetProcAddress.symbol__val); } + if (data->args.hipGetProcAddress.pfn == NULL) oss << ", pfn=NULL"; + else { oss << ", pfn="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetProcAddress.pfn__val); } + oss << ", hipVersion="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetProcAddress.hipVersion); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetProcAddress.flags); + if (data->args.hipGetProcAddress.symbolStatus == NULL) oss << ", symbolStatus=NULL"; + else { oss << ", symbolStatus="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetProcAddress.symbolStatus__val); } + oss << ")"; + break; + case HIP_API_ID_hipGetSymbolAddress: + oss << "hipGetSymbolAddress("; + if (data->args.hipGetSymbolAddress.devPtr == NULL) oss << "devPtr=NULL"; + else { oss << "devPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetSymbolAddress.devPtr__val); } + oss << ", symbol="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetSymbolAddress.symbol); + oss << ")"; + break; + case HIP_API_ID_hipGetSymbolSize: + oss << "hipGetSymbolSize("; + if (data->args.hipGetSymbolSize.size == NULL) oss << "size=NULL"; + else { oss << "size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetSymbolSize.size__val); } + oss << ", symbol="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGetSymbolSize.symbol); + oss << ")"; + break; + case HIP_API_ID_hipGraphAddChildGraphNode: + oss << "hipGraphAddChildGraphNode("; + if (data->args.hipGraphAddChildGraphNode.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddChildGraphNode.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddChildGraphNode.graph); + if (data->args.hipGraphAddChildGraphNode.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddChildGraphNode.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddChildGraphNode.numDependencies); + oss << ", childGraph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddChildGraphNode.childGraph); + oss << ")"; + break; + case HIP_API_ID_hipGraphAddDependencies: + oss << "hipGraphAddDependencies("; + oss << "graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddDependencies.graph); + if (data->args.hipGraphAddDependencies.from == NULL) oss << ", from=NULL"; + else { oss << ", from="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddDependencies.from__val); } + if (data->args.hipGraphAddDependencies.to == NULL) oss << ", to=NULL"; + else { oss << ", to="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddDependencies.to__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddDependencies.numDependencies); + oss << ")"; + break; + case HIP_API_ID_hipGraphAddEmptyNode: + oss << "hipGraphAddEmptyNode("; + if (data->args.hipGraphAddEmptyNode.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddEmptyNode.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddEmptyNode.graph); + if (data->args.hipGraphAddEmptyNode.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddEmptyNode.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddEmptyNode.numDependencies); + oss << ")"; + break; + case HIP_API_ID_hipGraphAddEventRecordNode: + oss << "hipGraphAddEventRecordNode("; + if (data->args.hipGraphAddEventRecordNode.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddEventRecordNode.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddEventRecordNode.graph); + if (data->args.hipGraphAddEventRecordNode.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddEventRecordNode.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddEventRecordNode.numDependencies); + oss << ", event="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddEventRecordNode.event); + oss << ")"; + break; + case HIP_API_ID_hipGraphAddEventWaitNode: + oss << "hipGraphAddEventWaitNode("; + if (data->args.hipGraphAddEventWaitNode.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddEventWaitNode.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddEventWaitNode.graph); + if (data->args.hipGraphAddEventWaitNode.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddEventWaitNode.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddEventWaitNode.numDependencies); + oss << ", event="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddEventWaitNode.event); + oss << ")"; + break; + case HIP_API_ID_hipGraphAddExternalSemaphoresSignalNode: + oss << "hipGraphAddExternalSemaphoresSignalNode("; + if (data->args.hipGraphAddExternalSemaphoresSignalNode.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddExternalSemaphoresSignalNode.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddExternalSemaphoresSignalNode.graph); + if (data->args.hipGraphAddExternalSemaphoresSignalNode.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddExternalSemaphoresSignalNode.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddExternalSemaphoresSignalNode.numDependencies); + if (data->args.hipGraphAddExternalSemaphoresSignalNode.nodeParams == NULL) oss << ", nodeParams=NULL"; + else { oss << ", nodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddExternalSemaphoresSignalNode.nodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphAddExternalSemaphoresWaitNode: + oss << "hipGraphAddExternalSemaphoresWaitNode("; + if (data->args.hipGraphAddExternalSemaphoresWaitNode.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddExternalSemaphoresWaitNode.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddExternalSemaphoresWaitNode.graph); + if (data->args.hipGraphAddExternalSemaphoresWaitNode.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddExternalSemaphoresWaitNode.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddExternalSemaphoresWaitNode.numDependencies); + if (data->args.hipGraphAddExternalSemaphoresWaitNode.nodeParams == NULL) oss << ", nodeParams=NULL"; + else { oss << ", nodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddExternalSemaphoresWaitNode.nodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphAddHostNode: + oss << "hipGraphAddHostNode("; + if (data->args.hipGraphAddHostNode.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddHostNode.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddHostNode.graph); + if (data->args.hipGraphAddHostNode.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddHostNode.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddHostNode.numDependencies); + if (data->args.hipGraphAddHostNode.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddHostNode.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphAddKernelNode: + oss << "hipGraphAddKernelNode("; + if (data->args.hipGraphAddKernelNode.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddKernelNode.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddKernelNode.graph); + if (data->args.hipGraphAddKernelNode.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddKernelNode.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddKernelNode.numDependencies); + if (data->args.hipGraphAddKernelNode.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddKernelNode.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphAddMemAllocNode: + oss << "hipGraphAddMemAllocNode("; + if (data->args.hipGraphAddMemAllocNode.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemAllocNode.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemAllocNode.graph); + if (data->args.hipGraphAddMemAllocNode.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemAllocNode.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemAllocNode.numDependencies); + if (data->args.hipGraphAddMemAllocNode.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemAllocNode.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphAddMemFreeNode: + oss << "hipGraphAddMemFreeNode("; + if (data->args.hipGraphAddMemFreeNode.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemFreeNode.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemFreeNode.graph); + if (data->args.hipGraphAddMemFreeNode.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemFreeNode.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemFreeNode.numDependencies); + oss << ", dev_ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemFreeNode.dev_ptr); + oss << ")"; + break; + case HIP_API_ID_hipGraphAddMemcpyNode: + oss << "hipGraphAddMemcpyNode("; + if (data->args.hipGraphAddMemcpyNode.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNode.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNode.graph); + if (data->args.hipGraphAddMemcpyNode.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNode.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNode.numDependencies); + if (data->args.hipGraphAddMemcpyNode.pCopyParams == NULL) oss << ", pCopyParams=NULL"; + else { oss << ", pCopyParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNode.pCopyParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphAddMemcpyNode1D: + oss << "hipGraphAddMemcpyNode1D("; + if (data->args.hipGraphAddMemcpyNode1D.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNode1D.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNode1D.graph); + if (data->args.hipGraphAddMemcpyNode1D.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNode1D.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNode1D.numDependencies); + oss << ", dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNode1D.dst); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNode1D.src); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNode1D.count); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNode1D.kind); + oss << ")"; + break; + case HIP_API_ID_hipGraphAddMemcpyNodeFromSymbol: + oss << "hipGraphAddMemcpyNodeFromSymbol("; + if (data->args.hipGraphAddMemcpyNodeFromSymbol.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeFromSymbol.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeFromSymbol.graph); + if (data->args.hipGraphAddMemcpyNodeFromSymbol.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeFromSymbol.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeFromSymbol.numDependencies); + oss << ", dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeFromSymbol.dst); + oss << ", symbol="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeFromSymbol.symbol); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeFromSymbol.count); + oss << ", offset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeFromSymbol.offset); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeFromSymbol.kind); + oss << ")"; + break; + case HIP_API_ID_hipGraphAddMemcpyNodeToSymbol: + oss << "hipGraphAddMemcpyNodeToSymbol("; + if (data->args.hipGraphAddMemcpyNodeToSymbol.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeToSymbol.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeToSymbol.graph); + if (data->args.hipGraphAddMemcpyNodeToSymbol.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeToSymbol.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeToSymbol.numDependencies); + oss << ", symbol="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeToSymbol.symbol); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeToSymbol.src); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeToSymbol.count); + oss << ", offset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeToSymbol.offset); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemcpyNodeToSymbol.kind); + oss << ")"; + break; + case HIP_API_ID_hipGraphAddMemsetNode: + oss << "hipGraphAddMemsetNode("; + if (data->args.hipGraphAddMemsetNode.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemsetNode.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemsetNode.graph); + if (data->args.hipGraphAddMemsetNode.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemsetNode.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemsetNode.numDependencies); + if (data->args.hipGraphAddMemsetNode.pMemsetParams == NULL) oss << ", pMemsetParams=NULL"; + else { oss << ", pMemsetParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddMemsetNode.pMemsetParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphAddNode: + oss << "hipGraphAddNode("; + if (data->args.hipGraphAddNode.pGraphNode == NULL) oss << "pGraphNode=NULL"; + else { oss << "pGraphNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddNode.pGraphNode__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddNode.graph); + if (data->args.hipGraphAddNode.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddNode.pDependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddNode.numDependencies); + if (data->args.hipGraphAddNode.nodeParams == NULL) oss << ", nodeParams=NULL"; + else { oss << ", nodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphAddNode.nodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphChildGraphNodeGetGraph: + oss << "hipGraphChildGraphNodeGetGraph("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphChildGraphNodeGetGraph.node); + if (data->args.hipGraphChildGraphNodeGetGraph.pGraph == NULL) oss << ", pGraph=NULL"; + else { oss << ", pGraph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphChildGraphNodeGetGraph.pGraph__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphClone: + oss << "hipGraphClone("; + if (data->args.hipGraphClone.pGraphClone == NULL) oss << "pGraphClone=NULL"; + else { oss << "pGraphClone="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphClone.pGraphClone__val); } + oss << ", originalGraph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphClone.originalGraph); + oss << ")"; + break; + case HIP_API_ID_hipGraphCreate: + oss << "hipGraphCreate("; + if (data->args.hipGraphCreate.pGraph == NULL) oss << "pGraph=NULL"; + else { oss << "pGraph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphCreate.pGraph__val); } + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphCreate.flags); + oss << ")"; + break; + case HIP_API_ID_hipGraphDebugDotPrint: + oss << "hipGraphDebugDotPrint("; + oss << "graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphDebugDotPrint.graph); + if (data->args.hipGraphDebugDotPrint.path == NULL) oss << ", path=NULL"; + else { oss << ", path="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphDebugDotPrint.path__val); } + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphDebugDotPrint.flags); + oss << ")"; + break; + case HIP_API_ID_hipGraphDestroy: + oss << "hipGraphDestroy("; + oss << "graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphDestroy.graph); + oss << ")"; + break; + case HIP_API_ID_hipGraphDestroyNode: + oss << "hipGraphDestroyNode("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphDestroyNode.node); + oss << ")"; + break; + case HIP_API_ID_hipGraphEventRecordNodeGetEvent: + oss << "hipGraphEventRecordNodeGetEvent("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphEventRecordNodeGetEvent.node); + if (data->args.hipGraphEventRecordNodeGetEvent.event_out == NULL) oss << ", event_out=NULL"; + else { oss << ", event_out="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphEventRecordNodeGetEvent.event_out__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphEventRecordNodeSetEvent: + oss << "hipGraphEventRecordNodeSetEvent("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphEventRecordNodeSetEvent.node); + oss << ", event="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphEventRecordNodeSetEvent.event); + oss << ")"; + break; + case HIP_API_ID_hipGraphEventWaitNodeGetEvent: + oss << "hipGraphEventWaitNodeGetEvent("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphEventWaitNodeGetEvent.node); + if (data->args.hipGraphEventWaitNodeGetEvent.event_out == NULL) oss << ", event_out=NULL"; + else { oss << ", event_out="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphEventWaitNodeGetEvent.event_out__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphEventWaitNodeSetEvent: + oss << "hipGraphEventWaitNodeSetEvent("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphEventWaitNodeSetEvent.node); + oss << ", event="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphEventWaitNodeSetEvent.event); + oss << ")"; + break; + case HIP_API_ID_hipGraphExecChildGraphNodeSetParams: + oss << "hipGraphExecChildGraphNodeSetParams("; + oss << "hGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecChildGraphNodeSetParams.hGraphExec); + oss << ", node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecChildGraphNodeSetParams.node); + oss << ", childGraph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecChildGraphNodeSetParams.childGraph); + oss << ")"; + break; + case HIP_API_ID_hipGraphExecDestroy: + oss << "hipGraphExecDestroy("; + oss << "graphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecDestroy.graphExec); + oss << ")"; + break; + case HIP_API_ID_hipGraphExecEventRecordNodeSetEvent: + oss << "hipGraphExecEventRecordNodeSetEvent("; + oss << "hGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecEventRecordNodeSetEvent.hGraphExec); + oss << ", hNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecEventRecordNodeSetEvent.hNode); + oss << ", event="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecEventRecordNodeSetEvent.event); + oss << ")"; + break; + case HIP_API_ID_hipGraphExecEventWaitNodeSetEvent: + oss << "hipGraphExecEventWaitNodeSetEvent("; + oss << "hGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecEventWaitNodeSetEvent.hGraphExec); + oss << ", hNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecEventWaitNodeSetEvent.hNode); + oss << ", event="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecEventWaitNodeSetEvent.event); + oss << ")"; + break; + case HIP_API_ID_hipGraphExecExternalSemaphoresSignalNodeSetParams: + oss << "hipGraphExecExternalSemaphoresSignalNodeSetParams("; + oss << "hGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecExternalSemaphoresSignalNodeSetParams.hGraphExec); + oss << ", hNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecExternalSemaphoresSignalNodeSetParams.hNode); + if (data->args.hipGraphExecExternalSemaphoresSignalNodeSetParams.nodeParams == NULL) oss << ", nodeParams=NULL"; + else { oss << ", nodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecExternalSemaphoresSignalNodeSetParams.nodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphExecExternalSemaphoresWaitNodeSetParams: + oss << "hipGraphExecExternalSemaphoresWaitNodeSetParams("; + oss << "hGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecExternalSemaphoresWaitNodeSetParams.hGraphExec); + oss << ", hNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecExternalSemaphoresWaitNodeSetParams.hNode); + if (data->args.hipGraphExecExternalSemaphoresWaitNodeSetParams.nodeParams == NULL) oss << ", nodeParams=NULL"; + else { oss << ", nodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecExternalSemaphoresWaitNodeSetParams.nodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphExecHostNodeSetParams: + oss << "hipGraphExecHostNodeSetParams("; + oss << "hGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecHostNodeSetParams.hGraphExec); + oss << ", node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecHostNodeSetParams.node); + if (data->args.hipGraphExecHostNodeSetParams.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecHostNodeSetParams.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphExecKernelNodeSetParams: + oss << "hipGraphExecKernelNodeSetParams("; + oss << "hGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecKernelNodeSetParams.hGraphExec); + oss << ", node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecKernelNodeSetParams.node); + if (data->args.hipGraphExecKernelNodeSetParams.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecKernelNodeSetParams.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphExecMemcpyNodeSetParams: + oss << "hipGraphExecMemcpyNodeSetParams("; + oss << "hGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParams.hGraphExec); + oss << ", node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParams.node); + if (data->args.hipGraphExecMemcpyNodeSetParams.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParams.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphExecMemcpyNodeSetParams1D: + oss << "hipGraphExecMemcpyNodeSetParams1D("; + oss << "hGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParams1D.hGraphExec); + oss << ", node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParams1D.node); + oss << ", dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParams1D.dst); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParams1D.src); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParams1D.count); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParams1D.kind); + oss << ")"; + break; + case HIP_API_ID_hipGraphExecMemcpyNodeSetParamsFromSymbol: + oss << "hipGraphExecMemcpyNodeSetParamsFromSymbol("; + oss << "hGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParamsFromSymbol.hGraphExec); + oss << ", node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParamsFromSymbol.node); + oss << ", dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParamsFromSymbol.dst); + oss << ", symbol="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParamsFromSymbol.symbol); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParamsFromSymbol.count); + oss << ", offset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParamsFromSymbol.offset); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParamsFromSymbol.kind); + oss << ")"; + break; + case HIP_API_ID_hipGraphExecMemcpyNodeSetParamsToSymbol: + oss << "hipGraphExecMemcpyNodeSetParamsToSymbol("; + oss << "hGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParamsToSymbol.hGraphExec); + oss << ", node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParamsToSymbol.node); + oss << ", symbol="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParamsToSymbol.symbol); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParamsToSymbol.src); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParamsToSymbol.count); + oss << ", offset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParamsToSymbol.offset); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemcpyNodeSetParamsToSymbol.kind); + oss << ")"; + break; + case HIP_API_ID_hipGraphExecMemsetNodeSetParams: + oss << "hipGraphExecMemsetNodeSetParams("; + oss << "hGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemsetNodeSetParams.hGraphExec); + oss << ", node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemsetNodeSetParams.node); + if (data->args.hipGraphExecMemsetNodeSetParams.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecMemsetNodeSetParams.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphExecUpdate: + oss << "hipGraphExecUpdate("; + oss << "hGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecUpdate.hGraphExec); + oss << ", hGraph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecUpdate.hGraph); + if (data->args.hipGraphExecUpdate.hErrorNode_out == NULL) oss << ", hErrorNode_out=NULL"; + else { oss << ", hErrorNode_out="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecUpdate.hErrorNode_out__val); } + if (data->args.hipGraphExecUpdate.updateResult_out == NULL) oss << ", updateResult_out=NULL"; + else { oss << ", updateResult_out="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExecUpdate.updateResult_out__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphExternalSemaphoresSignalNodeGetParams: + oss << "hipGraphExternalSemaphoresSignalNodeGetParams("; + oss << "hNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExternalSemaphoresSignalNodeGetParams.hNode); + if (data->args.hipGraphExternalSemaphoresSignalNodeGetParams.params_out == NULL) oss << ", params_out=NULL"; + else { oss << ", params_out="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExternalSemaphoresSignalNodeGetParams.params_out__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphExternalSemaphoresSignalNodeSetParams: + oss << "hipGraphExternalSemaphoresSignalNodeSetParams("; + oss << "hNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExternalSemaphoresSignalNodeSetParams.hNode); + if (data->args.hipGraphExternalSemaphoresSignalNodeSetParams.nodeParams == NULL) oss << ", nodeParams=NULL"; + else { oss << ", nodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExternalSemaphoresSignalNodeSetParams.nodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphExternalSemaphoresWaitNodeGetParams: + oss << "hipGraphExternalSemaphoresWaitNodeGetParams("; + oss << "hNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExternalSemaphoresWaitNodeGetParams.hNode); + if (data->args.hipGraphExternalSemaphoresWaitNodeGetParams.params_out == NULL) oss << ", params_out=NULL"; + else { oss << ", params_out="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExternalSemaphoresWaitNodeGetParams.params_out__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphExternalSemaphoresWaitNodeSetParams: + oss << "hipGraphExternalSemaphoresWaitNodeSetParams("; + oss << "hNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExternalSemaphoresWaitNodeSetParams.hNode); + if (data->args.hipGraphExternalSemaphoresWaitNodeSetParams.nodeParams == NULL) oss << ", nodeParams=NULL"; + else { oss << ", nodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphExternalSemaphoresWaitNodeSetParams.nodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphGetEdges: + oss << "hipGraphGetEdges("; + oss << "graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphGetEdges.graph); + if (data->args.hipGraphGetEdges.from == NULL) oss << ", from=NULL"; + else { oss << ", from="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphGetEdges.from__val); } + if (data->args.hipGraphGetEdges.to == NULL) oss << ", to=NULL"; + else { oss << ", to="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphGetEdges.to__val); } + if (data->args.hipGraphGetEdges.numEdges == NULL) oss << ", numEdges=NULL"; + else { oss << ", numEdges="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphGetEdges.numEdges__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphGetNodes: + oss << "hipGraphGetNodes("; + oss << "graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphGetNodes.graph); + if (data->args.hipGraphGetNodes.nodes == NULL) oss << ", nodes=NULL"; + else { oss << ", nodes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphGetNodes.nodes__val); } + if (data->args.hipGraphGetNodes.numNodes == NULL) oss << ", numNodes=NULL"; + else { oss << ", numNodes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphGetNodes.numNodes__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphGetRootNodes: + oss << "hipGraphGetRootNodes("; + oss << "graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphGetRootNodes.graph); + if (data->args.hipGraphGetRootNodes.pRootNodes == NULL) oss << ", pRootNodes=NULL"; + else { oss << ", pRootNodes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphGetRootNodes.pRootNodes__val); } + if (data->args.hipGraphGetRootNodes.pNumRootNodes == NULL) oss << ", pNumRootNodes=NULL"; + else { oss << ", pNumRootNodes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphGetRootNodes.pNumRootNodes__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphHostNodeGetParams: + oss << "hipGraphHostNodeGetParams("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphHostNodeGetParams.node); + if (data->args.hipGraphHostNodeGetParams.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphHostNodeGetParams.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphHostNodeSetParams: + oss << "hipGraphHostNodeSetParams("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphHostNodeSetParams.node); + if (data->args.hipGraphHostNodeSetParams.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphHostNodeSetParams.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphInstantiate: + oss << "hipGraphInstantiate("; + if (data->args.hipGraphInstantiate.pGraphExec == NULL) oss << "pGraphExec=NULL"; + else { oss << "pGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphInstantiate.pGraphExec__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphInstantiate.graph); + if (data->args.hipGraphInstantiate.pErrorNode == NULL) oss << ", pErrorNode=NULL"; + else { oss << ", pErrorNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphInstantiate.pErrorNode__val); } + if (data->args.hipGraphInstantiate.pLogBuffer == NULL) oss << ", pLogBuffer=NULL"; + else { oss << ", pLogBuffer="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphInstantiate.pLogBuffer__val); } + oss << ", bufferSize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphInstantiate.bufferSize); + oss << ")"; + break; + case HIP_API_ID_hipGraphInstantiateWithFlags: + oss << "hipGraphInstantiateWithFlags("; + if (data->args.hipGraphInstantiateWithFlags.pGraphExec == NULL) oss << "pGraphExec=NULL"; + else { oss << "pGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphInstantiateWithFlags.pGraphExec__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphInstantiateWithFlags.graph); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphInstantiateWithFlags.flags); + oss << ")"; + break; + case HIP_API_ID_hipGraphInstantiateWithParams: + oss << "hipGraphInstantiateWithParams("; + if (data->args.hipGraphInstantiateWithParams.pGraphExec == NULL) oss << "pGraphExec=NULL"; + else { oss << "pGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphInstantiateWithParams.pGraphExec__val); } + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphInstantiateWithParams.graph); + if (data->args.hipGraphInstantiateWithParams.instantiateParams == NULL) oss << ", instantiateParams=NULL"; + else { oss << ", instantiateParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphInstantiateWithParams.instantiateParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphKernelNodeCopyAttributes: + oss << "hipGraphKernelNodeCopyAttributes("; + oss << "hSrc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphKernelNodeCopyAttributes.hSrc); + oss << ", hDst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphKernelNodeCopyAttributes.hDst); + oss << ")"; + break; + case HIP_API_ID_hipGraphKernelNodeGetAttribute: + oss << "hipGraphKernelNodeGetAttribute("; + oss << "hNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphKernelNodeGetAttribute.hNode); + oss << ", attr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphKernelNodeGetAttribute.attr); + if (data->args.hipGraphKernelNodeGetAttribute.value == NULL) oss << ", value=NULL"; + else { oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphKernelNodeGetAttribute.value__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphKernelNodeGetParams: + oss << "hipGraphKernelNodeGetParams("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphKernelNodeGetParams.node); + if (data->args.hipGraphKernelNodeGetParams.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphKernelNodeGetParams.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphKernelNodeSetAttribute: + oss << "hipGraphKernelNodeSetAttribute("; + oss << "hNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphKernelNodeSetAttribute.hNode); + oss << ", attr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphKernelNodeSetAttribute.attr); + if (data->args.hipGraphKernelNodeSetAttribute.value == NULL) oss << ", value=NULL"; + else { oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphKernelNodeSetAttribute.value__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphKernelNodeSetParams: + oss << "hipGraphKernelNodeSetParams("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphKernelNodeSetParams.node); + if (data->args.hipGraphKernelNodeSetParams.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphKernelNodeSetParams.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphLaunch: + oss << "hipGraphLaunch("; + oss << "graphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphLaunch.graphExec); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphLaunch.stream); + oss << ")"; + break; + case HIP_API_ID_hipGraphMemAllocNodeGetParams: + oss << "hipGraphMemAllocNodeGetParams("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemAllocNodeGetParams.node); + if (data->args.hipGraphMemAllocNodeGetParams.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemAllocNodeGetParams.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphMemFreeNodeGetParams: + oss << "hipGraphMemFreeNodeGetParams("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemFreeNodeGetParams.node); + oss << ", dev_ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemFreeNodeGetParams.dev_ptr); + oss << ")"; + break; + case HIP_API_ID_hipGraphMemcpyNodeGetParams: + oss << "hipGraphMemcpyNodeGetParams("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeGetParams.node); + if (data->args.hipGraphMemcpyNodeGetParams.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeGetParams.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphMemcpyNodeSetParams: + oss << "hipGraphMemcpyNodeSetParams("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParams.node); + if (data->args.hipGraphMemcpyNodeSetParams.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParams.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphMemcpyNodeSetParams1D: + oss << "hipGraphMemcpyNodeSetParams1D("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParams1D.node); + oss << ", dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParams1D.dst); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParams1D.src); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParams1D.count); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParams1D.kind); + oss << ")"; + break; + case HIP_API_ID_hipGraphMemcpyNodeSetParamsFromSymbol: + oss << "hipGraphMemcpyNodeSetParamsFromSymbol("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParamsFromSymbol.node); + oss << ", dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParamsFromSymbol.dst); + oss << ", symbol="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParamsFromSymbol.symbol); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParamsFromSymbol.count); + oss << ", offset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParamsFromSymbol.offset); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParamsFromSymbol.kind); + oss << ")"; + break; + case HIP_API_ID_hipGraphMemcpyNodeSetParamsToSymbol: + oss << "hipGraphMemcpyNodeSetParamsToSymbol("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParamsToSymbol.node); + oss << ", symbol="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParamsToSymbol.symbol); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParamsToSymbol.src); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParamsToSymbol.count); + oss << ", offset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParamsToSymbol.offset); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemcpyNodeSetParamsToSymbol.kind); + oss << ")"; + break; + case HIP_API_ID_hipGraphMemsetNodeGetParams: + oss << "hipGraphMemsetNodeGetParams("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemsetNodeGetParams.node); + if (data->args.hipGraphMemsetNodeGetParams.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemsetNodeGetParams.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphMemsetNodeSetParams: + oss << "hipGraphMemsetNodeSetParams("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemsetNodeSetParams.node); + if (data->args.hipGraphMemsetNodeSetParams.pNodeParams == NULL) oss << ", pNodeParams=NULL"; + else { oss << ", pNodeParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphMemsetNodeSetParams.pNodeParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphNodeFindInClone: + oss << "hipGraphNodeFindInClone("; + if (data->args.hipGraphNodeFindInClone.pNode == NULL) oss << "pNode=NULL"; + else { oss << "pNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeFindInClone.pNode__val); } + oss << ", originalNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeFindInClone.originalNode); + oss << ", clonedGraph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeFindInClone.clonedGraph); + oss << ")"; + break; + case HIP_API_ID_hipGraphNodeGetDependencies: + oss << "hipGraphNodeGetDependencies("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeGetDependencies.node); + if (data->args.hipGraphNodeGetDependencies.pDependencies == NULL) oss << ", pDependencies=NULL"; + else { oss << ", pDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeGetDependencies.pDependencies__val); } + if (data->args.hipGraphNodeGetDependencies.pNumDependencies == NULL) oss << ", pNumDependencies=NULL"; + else { oss << ", pNumDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeGetDependencies.pNumDependencies__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphNodeGetDependentNodes: + oss << "hipGraphNodeGetDependentNodes("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeGetDependentNodes.node); + if (data->args.hipGraphNodeGetDependentNodes.pDependentNodes == NULL) oss << ", pDependentNodes=NULL"; + else { oss << ", pDependentNodes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeGetDependentNodes.pDependentNodes__val); } + if (data->args.hipGraphNodeGetDependentNodes.pNumDependentNodes == NULL) oss << ", pNumDependentNodes=NULL"; + else { oss << ", pNumDependentNodes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeGetDependentNodes.pNumDependentNodes__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphNodeGetEnabled: + oss << "hipGraphNodeGetEnabled("; + oss << "hGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeGetEnabled.hGraphExec); + oss << ", hNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeGetEnabled.hNode); + if (data->args.hipGraphNodeGetEnabled.isEnabled == NULL) oss << ", isEnabled=NULL"; + else { oss << ", isEnabled="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeGetEnabled.isEnabled__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphNodeGetType: + oss << "hipGraphNodeGetType("; + oss << "node="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeGetType.node); + if (data->args.hipGraphNodeGetType.pType == NULL) oss << ", pType=NULL"; + else { oss << ", pType="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeGetType.pType__val); } + oss << ")"; + break; + case HIP_API_ID_hipGraphNodeSetEnabled: + oss << "hipGraphNodeSetEnabled("; + oss << "hGraphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeSetEnabled.hGraphExec); + oss << ", hNode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeSetEnabled.hNode); + oss << ", isEnabled="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphNodeSetEnabled.isEnabled); + oss << ")"; + break; + case HIP_API_ID_hipGraphReleaseUserObject: + oss << "hipGraphReleaseUserObject("; + oss << "graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphReleaseUserObject.graph); + oss << ", object="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphReleaseUserObject.object); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphReleaseUserObject.count); + oss << ")"; + break; + case HIP_API_ID_hipGraphRemoveDependencies: + oss << "hipGraphRemoveDependencies("; + oss << "graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphRemoveDependencies.graph); + if (data->args.hipGraphRemoveDependencies.from == NULL) oss << ", from=NULL"; + else { oss << ", from="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphRemoveDependencies.from__val); } + if (data->args.hipGraphRemoveDependencies.to == NULL) oss << ", to=NULL"; + else { oss << ", to="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphRemoveDependencies.to__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphRemoveDependencies.numDependencies); + oss << ")"; + break; + case HIP_API_ID_hipGraphRetainUserObject: + oss << "hipGraphRetainUserObject("; + oss << "graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphRetainUserObject.graph); + oss << ", object="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphRetainUserObject.object); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphRetainUserObject.count); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphRetainUserObject.flags); + oss << ")"; + break; + case HIP_API_ID_hipGraphUpload: + oss << "hipGraphUpload("; + oss << "graphExec="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphUpload.graphExec); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphUpload.stream); + oss << ")"; + break; + case HIP_API_ID_hipGraphicsGLRegisterBuffer: + oss << "hipGraphicsGLRegisterBuffer("; + if (data->args.hipGraphicsGLRegisterBuffer.resource == NULL) oss << "resource=NULL"; + else { oss << "resource="; roctracer::hip_support::detail::operator<<(oss, (void*)data->args.hipGraphicsGLRegisterBuffer.resource__val); } + oss << ", buffer="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsGLRegisterBuffer.buffer); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsGLRegisterBuffer.flags); + oss << ")"; + break; + case HIP_API_ID_hipGraphicsGLRegisterImage: + oss << "hipGraphicsGLRegisterImage("; + if (data->args.hipGraphicsGLRegisterImage.resource == NULL) oss << "resource=NULL"; + else { oss << "resource="; roctracer::hip_support::detail::operator<<(oss, (void*)data->args.hipGraphicsGLRegisterImage.resource__val); } + oss << ", image="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsGLRegisterImage.image); + oss << ", target="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsGLRegisterImage.target); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsGLRegisterImage.flags); + oss << ")"; + break; + case HIP_API_ID_hipGraphicsMapResources: + oss << "hipGraphicsMapResources("; + oss << "count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsMapResources.count); + if (data->args.hipGraphicsMapResources.resources == NULL) oss << ", resources=NULL"; + else { oss << ", resources="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsMapResources.resources__val); } + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsMapResources.stream); + oss << ")"; + break; + case HIP_API_ID_hipGraphicsResourceGetMappedPointer: + oss << "hipGraphicsResourceGetMappedPointer("; + if (data->args.hipGraphicsResourceGetMappedPointer.devPtr == NULL) oss << "devPtr=NULL"; + else { oss << "devPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsResourceGetMappedPointer.devPtr__val); } + if (data->args.hipGraphicsResourceGetMappedPointer.size == NULL) oss << ", size=NULL"; + else { oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsResourceGetMappedPointer.size__val); } + oss << ", resource="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsResourceGetMappedPointer.resource); + oss << ")"; + break; + case HIP_API_ID_hipGraphicsSubResourceGetMappedArray: + oss << "hipGraphicsSubResourceGetMappedArray("; + if (data->args.hipGraphicsSubResourceGetMappedArray.array == NULL) oss << "array=NULL"; + else { oss << "array="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsSubResourceGetMappedArray.array__val); } + oss << ", resource="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsSubResourceGetMappedArray.resource); + oss << ", arrayIndex="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsSubResourceGetMappedArray.arrayIndex); + oss << ", mipLevel="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsSubResourceGetMappedArray.mipLevel); + oss << ")"; + break; + case HIP_API_ID_hipGraphicsUnmapResources: + oss << "hipGraphicsUnmapResources("; + oss << "count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsUnmapResources.count); + if (data->args.hipGraphicsUnmapResources.resources == NULL) oss << ", resources=NULL"; + else { oss << ", resources="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsUnmapResources.resources__val); } + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsUnmapResources.stream); + oss << ")"; + break; + case HIP_API_ID_hipGraphicsUnregisterResource: + oss << "hipGraphicsUnregisterResource("; + oss << "resource="; roctracer::hip_support::detail::operator<<(oss, data->args.hipGraphicsUnregisterResource.resource); + oss << ")"; + break; + case HIP_API_ID_hipHccModuleLaunchKernel: + oss << "hipHccModuleLaunchKernel("; + oss << "f="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHccModuleLaunchKernel.f); + oss << ", globalWorkSizeX="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHccModuleLaunchKernel.globalWorkSizeX); + oss << ", globalWorkSizeY="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHccModuleLaunchKernel.globalWorkSizeY); + oss << ", globalWorkSizeZ="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHccModuleLaunchKernel.globalWorkSizeZ); + oss << ", blockDimX="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHccModuleLaunchKernel.blockDimX); + oss << ", blockDimY="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHccModuleLaunchKernel.blockDimY); + oss << ", blockDimZ="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHccModuleLaunchKernel.blockDimZ); + oss << ", sharedMemBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHccModuleLaunchKernel.sharedMemBytes); + oss << ", hStream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHccModuleLaunchKernel.hStream); + if (data->args.hipHccModuleLaunchKernel.kernelParams == NULL) oss << ", kernelParams=NULL"; + else { oss << ", kernelParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHccModuleLaunchKernel.kernelParams__val); } + if (data->args.hipHccModuleLaunchKernel.extra == NULL) oss << ", extra=NULL"; + else { oss << ", extra="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHccModuleLaunchKernel.extra__val); } + oss << ", startEvent="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHccModuleLaunchKernel.startEvent); + oss << ", stopEvent="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHccModuleLaunchKernel.stopEvent); + oss << ")"; + break; + case HIP_API_ID_hipHostAlloc: + oss << "hipHostAlloc("; + if (data->args.hipHostAlloc.ptr == NULL) oss << "ptr=NULL"; + else { oss << "ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostAlloc.ptr__val); } + oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostAlloc.size); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostAlloc.flags); + oss << ")"; + break; + case HIP_API_ID_hipHostFree: + oss << "hipHostFree("; + oss << "ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostFree.ptr); + oss << ")"; + break; + case HIP_API_ID_hipHostGetDevicePointer: + oss << "hipHostGetDevicePointer("; + if (data->args.hipHostGetDevicePointer.devPtr == NULL) oss << "devPtr=NULL"; + else { oss << "devPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostGetDevicePointer.devPtr__val); } + oss << ", hstPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostGetDevicePointer.hstPtr); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostGetDevicePointer.flags); + oss << ")"; + break; + case HIP_API_ID_hipHostGetFlags: + oss << "hipHostGetFlags("; + if (data->args.hipHostGetFlags.flagsPtr == NULL) oss << "flagsPtr=NULL"; + else { oss << "flagsPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostGetFlags.flagsPtr__val); } + oss << ", hostPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostGetFlags.hostPtr); + oss << ")"; + break; + case HIP_API_ID_hipHostMalloc: + oss << "hipHostMalloc("; + if (data->args.hipHostMalloc.ptr == NULL) oss << "ptr=NULL"; + else { oss << "ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostMalloc.ptr__val); } + oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostMalloc.size); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostMalloc.flags); + oss << ")"; + break; + case HIP_API_ID_hipHostRegister: + oss << "hipHostRegister("; + oss << "hostPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostRegister.hostPtr); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostRegister.sizeBytes); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostRegister.flags); + oss << ")"; + break; + case HIP_API_ID_hipHostUnregister: + oss << "hipHostUnregister("; + oss << "hostPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipHostUnregister.hostPtr); + oss << ")"; + break; + case HIP_API_ID_hipImportExternalMemory: + oss << "hipImportExternalMemory("; + if (data->args.hipImportExternalMemory.extMem_out == NULL) oss << "extMem_out=NULL"; + else { oss << "extMem_out="; roctracer::hip_support::detail::operator<<(oss, data->args.hipImportExternalMemory.extMem_out__val); } + if (data->args.hipImportExternalMemory.memHandleDesc == NULL) oss << ", memHandleDesc=NULL"; + else { oss << ", memHandleDesc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipImportExternalMemory.memHandleDesc__val); } + oss << ")"; + break; + case HIP_API_ID_hipImportExternalSemaphore: + oss << "hipImportExternalSemaphore("; + if (data->args.hipImportExternalSemaphore.extSem_out == NULL) oss << "extSem_out=NULL"; + else { oss << "extSem_out="; roctracer::hip_support::detail::operator<<(oss, data->args.hipImportExternalSemaphore.extSem_out__val); } + if (data->args.hipImportExternalSemaphore.semHandleDesc == NULL) oss << ", semHandleDesc=NULL"; + else { oss << ", semHandleDesc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipImportExternalSemaphore.semHandleDesc__val); } + oss << ")"; + break; + case HIP_API_ID_hipInit: + oss << "hipInit("; + oss << "flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipInit.flags); + oss << ")"; + break; + case HIP_API_ID_hipIpcCloseMemHandle: + oss << "hipIpcCloseMemHandle("; + oss << "devPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipIpcCloseMemHandle.devPtr); + oss << ")"; + break; + case HIP_API_ID_hipIpcGetEventHandle: + oss << "hipIpcGetEventHandle("; + if (data->args.hipIpcGetEventHandle.handle == NULL) oss << "handle=NULL"; + else { oss << "handle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipIpcGetEventHandle.handle__val); } + oss << ", event="; roctracer::hip_support::detail::operator<<(oss, data->args.hipIpcGetEventHandle.event); + oss << ")"; + break; + case HIP_API_ID_hipIpcGetMemHandle: + oss << "hipIpcGetMemHandle("; + if (data->args.hipIpcGetMemHandle.handle == NULL) oss << "handle=NULL"; + else { oss << "handle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipIpcGetMemHandle.handle__val); } + oss << ", devPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipIpcGetMemHandle.devPtr); + oss << ")"; + break; + case HIP_API_ID_hipIpcOpenEventHandle: + oss << "hipIpcOpenEventHandle("; + if (data->args.hipIpcOpenEventHandle.event == NULL) oss << "event=NULL"; + else { oss << "event="; roctracer::hip_support::detail::operator<<(oss, data->args.hipIpcOpenEventHandle.event__val); } + oss << ", handle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipIpcOpenEventHandle.handle); + oss << ")"; + break; + case HIP_API_ID_hipIpcOpenMemHandle: + oss << "hipIpcOpenMemHandle("; + if (data->args.hipIpcOpenMemHandle.devPtr == NULL) oss << "devPtr=NULL"; + else { oss << "devPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipIpcOpenMemHandle.devPtr__val); } + oss << ", handle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipIpcOpenMemHandle.handle); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipIpcOpenMemHandle.flags); + oss << ")"; + break; + case HIP_API_ID_hipLaunchByPtr: + oss << "hipLaunchByPtr("; + oss << "hostFunction="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchByPtr.hostFunction); + oss << ")"; + break; + case HIP_API_ID_hipLaunchCooperativeKernel: + oss << "hipLaunchCooperativeKernel("; + oss << "f="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchCooperativeKernel.f); + oss << ", gridDim="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchCooperativeKernel.gridDim); + oss << ", blockDimX="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchCooperativeKernel.blockDimX); + if (data->args.hipLaunchCooperativeKernel.kernelParams == NULL) oss << ", kernelParams=NULL"; + else { oss << ", kernelParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchCooperativeKernel.kernelParams__val); } + oss << ", sharedMemBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchCooperativeKernel.sharedMemBytes); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchCooperativeKernel.stream); + oss << ")"; + break; + case HIP_API_ID_hipLaunchCooperativeKernelMultiDevice: + oss << "hipLaunchCooperativeKernelMultiDevice("; + if (data->args.hipLaunchCooperativeKernelMultiDevice.launchParamsList == NULL) oss << "launchParamsList=NULL"; + else { oss << "launchParamsList="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchCooperativeKernelMultiDevice.launchParamsList__val); } + oss << ", numDevices="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchCooperativeKernelMultiDevice.numDevices); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchCooperativeKernelMultiDevice.flags); + oss << ")"; + break; + case HIP_API_ID_hipLaunchHostFunc: + oss << "hipLaunchHostFunc("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchHostFunc.stream); + oss << ", fn="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchHostFunc.fn); + oss << ", userData="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchHostFunc.userData); + oss << ")"; + break; + case HIP_API_ID_hipLaunchKernel: + oss << "hipLaunchKernel("; + oss << "function_address="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchKernel.function_address); + oss << ", numBlocks="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchKernel.numBlocks); + oss << ", dimBlocks="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchKernel.dimBlocks); + if (data->args.hipLaunchKernel.args == NULL) oss << ", args=NULL"; + else { oss << ", args="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchKernel.args__val); } + oss << ", sharedMemBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchKernel.sharedMemBytes); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipLaunchKernel.stream); + oss << ")"; + break; + case HIP_API_ID_hipMalloc: + oss << "hipMalloc("; + if (data->args.hipMalloc.ptr == NULL) oss << "ptr=NULL"; + else { oss << "ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMalloc.ptr__val); } + oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMalloc.size); + oss << ")"; + break; + case HIP_API_ID_hipMalloc3D: + oss << "hipMalloc3D("; + if (data->args.hipMalloc3D.pitchedDevPtr == NULL) oss << "pitchedDevPtr=NULL"; + else { oss << "pitchedDevPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMalloc3D.pitchedDevPtr__val); } + oss << ", extent="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMalloc3D.extent); + oss << ")"; + break; + case HIP_API_ID_hipMalloc3DArray: + oss << "hipMalloc3DArray("; + if (data->args.hipMalloc3DArray.array == NULL) oss << "array=NULL"; + else { oss << "array="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMalloc3DArray.array__val); } + if (data->args.hipMalloc3DArray.desc == NULL) oss << ", desc=NULL"; + else { oss << ", desc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMalloc3DArray.desc__val); } + oss << ", extent="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMalloc3DArray.extent); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMalloc3DArray.flags); + oss << ")"; + break; + case HIP_API_ID_hipMallocArray: + oss << "hipMallocArray("; + if (data->args.hipMallocArray.array == NULL) oss << "array=NULL"; + else { oss << "array="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocArray.array__val); } + if (data->args.hipMallocArray.desc == NULL) oss << ", desc=NULL"; + else { oss << ", desc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocArray.desc__val); } + oss << ", width="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocArray.width); + oss << ", height="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocArray.height); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocArray.flags); + oss << ")"; + break; + case HIP_API_ID_hipMallocAsync: + oss << "hipMallocAsync("; + if (data->args.hipMallocAsync.dev_ptr == NULL) oss << "dev_ptr=NULL"; + else { oss << "dev_ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocAsync.dev_ptr__val); } + oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocAsync.size); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMallocFromPoolAsync: + oss << "hipMallocFromPoolAsync("; + if (data->args.hipMallocFromPoolAsync.dev_ptr == NULL) oss << "dev_ptr=NULL"; + else { oss << "dev_ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocFromPoolAsync.dev_ptr__val); } + oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocFromPoolAsync.size); + oss << ", mem_pool="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocFromPoolAsync.mem_pool); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocFromPoolAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMallocHost: + oss << "hipMallocHost("; + if (data->args.hipMallocHost.ptr == NULL) oss << "ptr=NULL"; + else { oss << "ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocHost.ptr__val); } + oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocHost.size); + oss << ")"; + break; + case HIP_API_ID_hipMallocManaged: + oss << "hipMallocManaged("; + if (data->args.hipMallocManaged.dev_ptr == NULL) oss << "dev_ptr=NULL"; + else { oss << "dev_ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocManaged.dev_ptr__val); } + oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocManaged.size); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocManaged.flags); + oss << ")"; + break; + case HIP_API_ID_hipMallocMipmappedArray: + oss << "hipMallocMipmappedArray("; + if (data->args.hipMallocMipmappedArray.mipmappedArray == NULL) oss << "mipmappedArray=NULL"; + else { oss << "mipmappedArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocMipmappedArray.mipmappedArray__val); } + if (data->args.hipMallocMipmappedArray.desc == NULL) oss << ", desc=NULL"; + else { oss << ", desc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocMipmappedArray.desc__val); } + oss << ", extent="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocMipmappedArray.extent); + oss << ", numLevels="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocMipmappedArray.numLevels); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocMipmappedArray.flags); + oss << ")"; + break; + case HIP_API_ID_hipMallocPitch: + oss << "hipMallocPitch("; + if (data->args.hipMallocPitch.ptr == NULL) oss << "ptr=NULL"; + else { oss << "ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocPitch.ptr__val); } + if (data->args.hipMallocPitch.pitch == NULL) oss << ", pitch=NULL"; + else { oss << ", pitch="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocPitch.pitch__val); } + oss << ", width="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocPitch.width); + oss << ", height="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMallocPitch.height); + oss << ")"; + break; + case HIP_API_ID_hipMemAddressFree: + oss << "hipMemAddressFree("; + oss << "devPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAddressFree.devPtr); + oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAddressFree.size); + oss << ")"; + break; + case HIP_API_ID_hipMemAddressReserve: + oss << "hipMemAddressReserve("; + if (data->args.hipMemAddressReserve.ptr == NULL) oss << "ptr=NULL"; + else { oss << "ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAddressReserve.ptr__val); } + oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAddressReserve.size); + oss << ", alignment="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAddressReserve.alignment); + oss << ", addr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAddressReserve.addr); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAddressReserve.flags); + oss << ")"; + break; + case HIP_API_ID_hipMemAdvise: + oss << "hipMemAdvise("; + oss << "dev_ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAdvise.dev_ptr); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAdvise.count); + oss << ", advice="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAdvise.advice); + oss << ", device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAdvise.device); + oss << ")"; + break; + case HIP_API_ID_hipMemAllocHost: + oss << "hipMemAllocHost("; + if (data->args.hipMemAllocHost.ptr == NULL) oss << "ptr=NULL"; + else { oss << "ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAllocHost.ptr__val); } + oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAllocHost.size); + oss << ")"; + break; + case HIP_API_ID_hipMemAllocPitch: + oss << "hipMemAllocPitch("; + if (data->args.hipMemAllocPitch.dptr == NULL) oss << "dptr=NULL"; + else { oss << "dptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAllocPitch.dptr__val); } + if (data->args.hipMemAllocPitch.pitch == NULL) oss << ", pitch=NULL"; + else { oss << ", pitch="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAllocPitch.pitch__val); } + oss << ", widthInBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAllocPitch.widthInBytes); + oss << ", height="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAllocPitch.height); + oss << ", elementSizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemAllocPitch.elementSizeBytes); + oss << ")"; + break; + case HIP_API_ID_hipMemCreate: + oss << "hipMemCreate("; + if (data->args.hipMemCreate.handle == NULL) oss << "handle=NULL"; + else { oss << "handle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemCreate.handle__val); } + oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemCreate.size); + if (data->args.hipMemCreate.prop == NULL) oss << ", prop=NULL"; + else { oss << ", prop="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemCreate.prop__val); } + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemCreate.flags); + oss << ")"; + break; + case HIP_API_ID_hipMemExportToShareableHandle: + oss << "hipMemExportToShareableHandle("; + oss << "shareableHandle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemExportToShareableHandle.shareableHandle); + oss << ", handle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemExportToShareableHandle.handle); + oss << ", handleType="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemExportToShareableHandle.handleType); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemExportToShareableHandle.flags); + oss << ")"; + break; + case HIP_API_ID_hipMemGetAccess: + oss << "hipMemGetAccess("; + if (data->args.hipMemGetAccess.flags == NULL) oss << "flags=NULL"; + else { oss << "flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemGetAccess.flags__val); } + if (data->args.hipMemGetAccess.location == NULL) oss << ", location=NULL"; + else { oss << ", location="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemGetAccess.location__val); } + oss << ", ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemGetAccess.ptr); + oss << ")"; + break; + case HIP_API_ID_hipMemGetAddressRange: + oss << "hipMemGetAddressRange("; + if (data->args.hipMemGetAddressRange.pbase == NULL) oss << "pbase=NULL"; + else { oss << "pbase="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemGetAddressRange.pbase__val); } + if (data->args.hipMemGetAddressRange.psize == NULL) oss << ", psize=NULL"; + else { oss << ", psize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemGetAddressRange.psize__val); } + oss << ", dptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemGetAddressRange.dptr); + oss << ")"; + break; + case HIP_API_ID_hipMemGetAllocationGranularity: + oss << "hipMemGetAllocationGranularity("; + if (data->args.hipMemGetAllocationGranularity.granularity == NULL) oss << "granularity=NULL"; + else { oss << "granularity="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemGetAllocationGranularity.granularity__val); } + if (data->args.hipMemGetAllocationGranularity.prop == NULL) oss << ", prop=NULL"; + else { oss << ", prop="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemGetAllocationGranularity.prop__val); } + oss << ", option="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemGetAllocationGranularity.option); + oss << ")"; + break; + case HIP_API_ID_hipMemGetAllocationPropertiesFromHandle: + oss << "hipMemGetAllocationPropertiesFromHandle("; + if (data->args.hipMemGetAllocationPropertiesFromHandle.prop == NULL) oss << "prop=NULL"; + else { oss << "prop="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemGetAllocationPropertiesFromHandle.prop__val); } + oss << ", handle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemGetAllocationPropertiesFromHandle.handle); + oss << ")"; + break; + case HIP_API_ID_hipMemGetInfo: + oss << "hipMemGetInfo("; + if (data->args.hipMemGetInfo.free == NULL) oss << "free=NULL"; + else { oss << "free="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemGetInfo.free__val); } + if (data->args.hipMemGetInfo.total == NULL) oss << ", total=NULL"; + else { oss << ", total="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemGetInfo.total__val); } + oss << ")"; + break; + case HIP_API_ID_hipMemImportFromShareableHandle: + oss << "hipMemImportFromShareableHandle("; + if (data->args.hipMemImportFromShareableHandle.handle == NULL) oss << "handle=NULL"; + else { oss << "handle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemImportFromShareableHandle.handle__val); } + oss << ", osHandle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemImportFromShareableHandle.osHandle); + oss << ", shHandleType="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemImportFromShareableHandle.shHandleType); + oss << ")"; + break; + case HIP_API_ID_hipMemMap: + oss << "hipMemMap("; + oss << "ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemMap.ptr); + oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemMap.size); + oss << ", offset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemMap.offset); + oss << ", handle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemMap.handle); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemMap.flags); + oss << ")"; + break; + case HIP_API_ID_hipMemMapArrayAsync: + oss << "hipMemMapArrayAsync("; + if (data->args.hipMemMapArrayAsync.mapInfoList == NULL) oss << "mapInfoList=NULL"; + else { oss << "mapInfoList="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemMapArrayAsync.mapInfoList__val); } + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemMapArrayAsync.count); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemMapArrayAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemPoolCreate: + oss << "hipMemPoolCreate("; + if (data->args.hipMemPoolCreate.mem_pool == NULL) oss << "mem_pool=NULL"; + else { oss << "mem_pool="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolCreate.mem_pool__val); } + if (data->args.hipMemPoolCreate.pool_props == NULL) oss << ", pool_props=NULL"; + else { oss << ", pool_props="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolCreate.pool_props__val); } + oss << ")"; + break; + case HIP_API_ID_hipMemPoolDestroy: + oss << "hipMemPoolDestroy("; + oss << "mem_pool="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolDestroy.mem_pool); + oss << ")"; + break; + case HIP_API_ID_hipMemPoolExportPointer: + oss << "hipMemPoolExportPointer("; + if (data->args.hipMemPoolExportPointer.export_data == NULL) oss << "export_data=NULL"; + else { oss << "export_data="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolExportPointer.export_data__val); } + oss << ", dev_ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolExportPointer.dev_ptr); + oss << ")"; + break; + case HIP_API_ID_hipMemPoolExportToShareableHandle: + oss << "hipMemPoolExportToShareableHandle("; + oss << "shared_handle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolExportToShareableHandle.shared_handle); + oss << ", mem_pool="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolExportToShareableHandle.mem_pool); + oss << ", handle_type="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolExportToShareableHandle.handle_type); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolExportToShareableHandle.flags); + oss << ")"; + break; + case HIP_API_ID_hipMemPoolGetAccess: + oss << "hipMemPoolGetAccess("; + if (data->args.hipMemPoolGetAccess.flags == NULL) oss << "flags=NULL"; + else { oss << "flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolGetAccess.flags__val); } + oss << ", mem_pool="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolGetAccess.mem_pool); + if (data->args.hipMemPoolGetAccess.location == NULL) oss << ", location=NULL"; + else { oss << ", location="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolGetAccess.location__val); } + oss << ")"; + break; + case HIP_API_ID_hipMemPoolGetAttribute: + oss << "hipMemPoolGetAttribute("; + oss << "mem_pool="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolGetAttribute.mem_pool); + oss << ", attr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolGetAttribute.attr); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolGetAttribute.value); + oss << ")"; + break; + case HIP_API_ID_hipMemPoolImportFromShareableHandle: + oss << "hipMemPoolImportFromShareableHandle("; + if (data->args.hipMemPoolImportFromShareableHandle.mem_pool == NULL) oss << "mem_pool=NULL"; + else { oss << "mem_pool="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolImportFromShareableHandle.mem_pool__val); } + oss << ", shared_handle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolImportFromShareableHandle.shared_handle); + oss << ", handle_type="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolImportFromShareableHandle.handle_type); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolImportFromShareableHandle.flags); + oss << ")"; + break; + case HIP_API_ID_hipMemPoolImportPointer: + oss << "hipMemPoolImportPointer("; + if (data->args.hipMemPoolImportPointer.dev_ptr == NULL) oss << "dev_ptr=NULL"; + else { oss << "dev_ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolImportPointer.dev_ptr__val); } + oss << ", mem_pool="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolImportPointer.mem_pool); + if (data->args.hipMemPoolImportPointer.export_data == NULL) oss << ", export_data=NULL"; + else { oss << ", export_data="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolImportPointer.export_data__val); } + oss << ")"; + break; + case HIP_API_ID_hipMemPoolSetAccess: + oss << "hipMemPoolSetAccess("; + oss << "mem_pool="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolSetAccess.mem_pool); + if (data->args.hipMemPoolSetAccess.desc_list == NULL) oss << ", desc_list=NULL"; + else { oss << ", desc_list="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolSetAccess.desc_list__val); } + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolSetAccess.count); + oss << ")"; + break; + case HIP_API_ID_hipMemPoolSetAttribute: + oss << "hipMemPoolSetAttribute("; + oss << "mem_pool="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolSetAttribute.mem_pool); + oss << ", attr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolSetAttribute.attr); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolSetAttribute.value); + oss << ")"; + break; + case HIP_API_ID_hipMemPoolTrimTo: + oss << "hipMemPoolTrimTo("; + oss << "mem_pool="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolTrimTo.mem_pool); + oss << ", min_bytes_to_hold="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPoolTrimTo.min_bytes_to_hold); + oss << ")"; + break; + case HIP_API_ID_hipMemPrefetchAsync: + oss << "hipMemPrefetchAsync("; + oss << "dev_ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPrefetchAsync.dev_ptr); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPrefetchAsync.count); + oss << ", device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPrefetchAsync.device); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPrefetchAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemPtrGetInfo: + oss << "hipMemPtrGetInfo("; + oss << "ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPtrGetInfo.ptr); + if (data->args.hipMemPtrGetInfo.size == NULL) oss << ", size=NULL"; + else { oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemPtrGetInfo.size__val); } + oss << ")"; + break; + case HIP_API_ID_hipMemRangeGetAttribute: + oss << "hipMemRangeGetAttribute("; + oss << "data="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemRangeGetAttribute.data); + oss << ", data_size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemRangeGetAttribute.data_size); + oss << ", attribute="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemRangeGetAttribute.attribute); + oss << ", dev_ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemRangeGetAttribute.dev_ptr); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemRangeGetAttribute.count); + oss << ")"; + break; + case HIP_API_ID_hipMemRangeGetAttributes: + oss << "hipMemRangeGetAttributes("; + if (data->args.hipMemRangeGetAttributes.data == NULL) oss << "data=NULL"; + else { oss << "data="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemRangeGetAttributes.data__val); } + if (data->args.hipMemRangeGetAttributes.data_sizes == NULL) oss << ", data_sizes=NULL"; + else { oss << ", data_sizes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemRangeGetAttributes.data_sizes__val); } + if (data->args.hipMemRangeGetAttributes.attributes == NULL) oss << ", attributes=NULL"; + else { oss << ", attributes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemRangeGetAttributes.attributes__val); } + oss << ", num_attributes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemRangeGetAttributes.num_attributes); + oss << ", dev_ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemRangeGetAttributes.dev_ptr); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemRangeGetAttributes.count); + oss << ")"; + break; + case HIP_API_ID_hipMemRelease: + oss << "hipMemRelease("; + oss << "handle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemRelease.handle); + oss << ")"; + break; + case HIP_API_ID_hipMemRetainAllocationHandle: + oss << "hipMemRetainAllocationHandle("; + if (data->args.hipMemRetainAllocationHandle.handle == NULL) oss << "handle=NULL"; + else { oss << "handle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemRetainAllocationHandle.handle__val); } + oss << ", addr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemRetainAllocationHandle.addr); + oss << ")"; + break; + case HIP_API_ID_hipMemSetAccess: + oss << "hipMemSetAccess("; + oss << "ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemSetAccess.ptr); + oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemSetAccess.size); + if (data->args.hipMemSetAccess.desc == NULL) oss << ", desc=NULL"; + else { oss << ", desc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemSetAccess.desc__val); } + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemSetAccess.count); + oss << ")"; + break; + case HIP_API_ID_hipMemUnmap: + oss << "hipMemUnmap("; + oss << "ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemUnmap.ptr); + oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemUnmap.size); + oss << ")"; + break; + case HIP_API_ID_hipMemcpy: + oss << "hipMemcpy("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy.dst); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy.src); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy.sizeBytes); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy.kind); + oss << ")"; + break; + case HIP_API_ID_hipMemcpy2D: + oss << "hipMemcpy2D("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2D.dst); + oss << ", dpitch="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2D.dpitch); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2D.src); + oss << ", spitch="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2D.spitch); + oss << ", width="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2D.width); + oss << ", height="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2D.height); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2D.kind); + oss << ")"; + break; + case HIP_API_ID_hipMemcpy2DArrayToArray: + oss << "hipMemcpy2DArrayToArray("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DArrayToArray.dst); + oss << ", wOffsetDst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DArrayToArray.wOffsetDst); + oss << ", hOffsetDst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DArrayToArray.hOffsetDst); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DArrayToArray.src); + oss << ", wOffsetSrc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DArrayToArray.wOffsetSrc); + oss << ", hOffsetSrc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DArrayToArray.hOffsetSrc); + oss << ", width="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DArrayToArray.width); + oss << ", height="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DArrayToArray.height); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DArrayToArray.kind); + oss << ")"; + break; + case HIP_API_ID_hipMemcpy2DAsync: + oss << "hipMemcpy2DAsync("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DAsync.dst); + oss << ", dpitch="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DAsync.dpitch); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DAsync.src); + oss << ", spitch="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DAsync.spitch); + oss << ", width="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DAsync.width); + oss << ", height="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DAsync.height); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DAsync.kind); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemcpy2DFromArray: + oss << "hipMemcpy2DFromArray("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArray.dst); + oss << ", dpitch="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArray.dpitch); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArray.src); + oss << ", wOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArray.wOffset); + oss << ", hOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArray.hOffset); + oss << ", width="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArray.width); + oss << ", height="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArray.height); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArray.kind); + oss << ")"; + break; + case HIP_API_ID_hipMemcpy2DFromArrayAsync: + oss << "hipMemcpy2DFromArrayAsync("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArrayAsync.dst); + oss << ", dpitch="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArrayAsync.dpitch); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArrayAsync.src); + oss << ", wOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArrayAsync.wOffset); + oss << ", hOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArrayAsync.hOffset); + oss << ", width="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArrayAsync.width); + oss << ", height="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArrayAsync.height); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArrayAsync.kind); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DFromArrayAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemcpy2DToArray: + oss << "hipMemcpy2DToArray("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArray.dst); + oss << ", wOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArray.wOffset); + oss << ", hOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArray.hOffset); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArray.src); + oss << ", spitch="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArray.spitch); + oss << ", width="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArray.width); + oss << ", height="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArray.height); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArray.kind); + oss << ")"; + break; + case HIP_API_ID_hipMemcpy2DToArrayAsync: + oss << "hipMemcpy2DToArrayAsync("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArrayAsync.dst); + oss << ", wOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArrayAsync.wOffset); + oss << ", hOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArrayAsync.hOffset); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArrayAsync.src); + oss << ", spitch="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArrayAsync.spitch); + oss << ", width="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArrayAsync.width); + oss << ", height="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArrayAsync.height); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArrayAsync.kind); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy2DToArrayAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemcpy3D: + oss << "hipMemcpy3D("; + if (data->args.hipMemcpy3D.p == NULL) oss << "p=NULL"; + else { oss << "p="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy3D.p__val); } + oss << ")"; + break; + case HIP_API_ID_hipMemcpy3DAsync: + oss << "hipMemcpy3DAsync("; + if (data->args.hipMemcpy3DAsync.p == NULL) oss << "p=NULL"; + else { oss << "p="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy3DAsync.p__val); } + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpy3DAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyAsync: + oss << "hipMemcpyAsync("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAsync.dst); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAsync.src); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAsync.sizeBytes); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAsync.kind); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyAtoA: + oss << "hipMemcpyAtoA("; + oss << "dstArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoA.dstArray); + oss << ", dstOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoA.dstOffset); + oss << ", srcArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoA.srcArray); + oss << ", srcOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoA.srcOffset); + oss << ", ByteCount="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoA.ByteCount); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyAtoD: + oss << "hipMemcpyAtoD("; + oss << "dstDevice="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoD.dstDevice); + oss << ", srcArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoD.srcArray); + oss << ", srcOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoD.srcOffset); + oss << ", ByteCount="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoD.ByteCount); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyAtoH: + oss << "hipMemcpyAtoH("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoH.dst); + oss << ", srcArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoH.srcArray); + oss << ", srcOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoH.srcOffset); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoH.count); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyAtoHAsync: + oss << "hipMemcpyAtoHAsync("; + oss << "dstHost="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoHAsync.dstHost); + oss << ", srcArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoHAsync.srcArray); + oss << ", srcOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoHAsync.srcOffset); + oss << ", ByteCount="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoHAsync.ByteCount); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyAtoHAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyDtoA: + oss << "hipMemcpyDtoA("; + oss << "dstArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoA.dstArray); + oss << ", dstOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoA.dstOffset); + oss << ", srcDevice="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoA.srcDevice); + oss << ", ByteCount="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoA.ByteCount); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyDtoD: + oss << "hipMemcpyDtoD("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoD.dst); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoD.src); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoD.sizeBytes); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyDtoDAsync: + oss << "hipMemcpyDtoDAsync("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoDAsync.dst); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoDAsync.src); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoDAsync.sizeBytes); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoDAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyDtoH: + oss << "hipMemcpyDtoH("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoH.dst); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoH.src); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoH.sizeBytes); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyDtoHAsync: + oss << "hipMemcpyDtoHAsync("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoHAsync.dst); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoHAsync.src); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoHAsync.sizeBytes); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyDtoHAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyFromArray: + oss << "hipMemcpyFromArray("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromArray.dst); + oss << ", srcArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromArray.srcArray); + oss << ", wOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromArray.wOffset); + oss << ", hOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromArray.hOffset); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromArray.count); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromArray.kind); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyFromSymbol: + oss << "hipMemcpyFromSymbol("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromSymbol.dst); + oss << ", symbol="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromSymbol.symbol); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromSymbol.sizeBytes); + oss << ", offset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromSymbol.offset); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromSymbol.kind); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyFromSymbolAsync: + oss << "hipMemcpyFromSymbolAsync("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromSymbolAsync.dst); + oss << ", symbol="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromSymbolAsync.symbol); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromSymbolAsync.sizeBytes); + oss << ", offset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromSymbolAsync.offset); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromSymbolAsync.kind); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyFromSymbolAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyHtoA: + oss << "hipMemcpyHtoA("; + oss << "dstArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoA.dstArray); + oss << ", dstOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoA.dstOffset); + oss << ", srcHost="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoA.srcHost); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoA.count); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyHtoAAsync: + oss << "hipMemcpyHtoAAsync("; + oss << "dstArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoAAsync.dstArray); + oss << ", dstOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoAAsync.dstOffset); + oss << ", srcHost="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoAAsync.srcHost); + oss << ", ByteCount="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoAAsync.ByteCount); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoAAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyHtoD: + oss << "hipMemcpyHtoD("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoD.dst); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoD.src); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoD.sizeBytes); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyHtoDAsync: + oss << "hipMemcpyHtoDAsync("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoDAsync.dst); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoDAsync.src); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoDAsync.sizeBytes); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyHtoDAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyParam2D: + oss << "hipMemcpyParam2D("; + if (data->args.hipMemcpyParam2D.pCopy == NULL) oss << "pCopy=NULL"; + else { oss << "pCopy="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyParam2D.pCopy__val); } + oss << ")"; + break; + case HIP_API_ID_hipMemcpyParam2DAsync: + oss << "hipMemcpyParam2DAsync("; + if (data->args.hipMemcpyParam2DAsync.pCopy == NULL) oss << "pCopy=NULL"; + else { oss << "pCopy="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyParam2DAsync.pCopy__val); } + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyParam2DAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyPeer: + oss << "hipMemcpyPeer("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyPeer.dst); + oss << ", dstDeviceId="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyPeer.dstDeviceId); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyPeer.src); + oss << ", srcDeviceId="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyPeer.srcDeviceId); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyPeer.sizeBytes); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyPeerAsync: + oss << "hipMemcpyPeerAsync("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyPeerAsync.dst); + oss << ", dstDeviceId="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyPeerAsync.dstDeviceId); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyPeerAsync.src); + oss << ", srcDevice="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyPeerAsync.srcDevice); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyPeerAsync.sizeBytes); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyPeerAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyToArray: + oss << "hipMemcpyToArray("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToArray.dst); + oss << ", wOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToArray.wOffset); + oss << ", hOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToArray.hOffset); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToArray.src); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToArray.count); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToArray.kind); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyToSymbol: + oss << "hipMemcpyToSymbol("; + oss << "symbol="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToSymbol.symbol); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToSymbol.src); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToSymbol.sizeBytes); + oss << ", offset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToSymbol.offset); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToSymbol.kind); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyToSymbolAsync: + oss << "hipMemcpyToSymbolAsync("; + oss << "symbol="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToSymbolAsync.symbol); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToSymbolAsync.src); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToSymbolAsync.sizeBytes); + oss << ", offset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToSymbolAsync.offset); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToSymbolAsync.kind); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyToSymbolAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemcpyWithStream: + oss << "hipMemcpyWithStream("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyWithStream.dst); + oss << ", src="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyWithStream.src); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyWithStream.sizeBytes); + oss << ", kind="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyWithStream.kind); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemcpyWithStream.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemset: + oss << "hipMemset("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset.dst); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset.value); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset.sizeBytes); + oss << ")"; + break; + case HIP_API_ID_hipMemset2D: + oss << "hipMemset2D("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset2D.dst); + oss << ", pitch="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset2D.pitch); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset2D.value); + oss << ", width="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset2D.width); + oss << ", height="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset2D.height); + oss << ")"; + break; + case HIP_API_ID_hipMemset2DAsync: + oss << "hipMemset2DAsync("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset2DAsync.dst); + oss << ", pitch="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset2DAsync.pitch); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset2DAsync.value); + oss << ", width="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset2DAsync.width); + oss << ", height="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset2DAsync.height); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset2DAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemset3D: + oss << "hipMemset3D("; + oss << "pitchedDevPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset3D.pitchedDevPtr); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset3D.value); + oss << ", extent="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset3D.extent); + oss << ")"; + break; + case HIP_API_ID_hipMemset3DAsync: + oss << "hipMemset3DAsync("; + oss << "pitchedDevPtr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset3DAsync.pitchedDevPtr); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset3DAsync.value); + oss << ", extent="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset3DAsync.extent); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemset3DAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemsetAsync: + oss << "hipMemsetAsync("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetAsync.dst); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetAsync.value); + oss << ", sizeBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetAsync.sizeBytes); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemsetD16: + oss << "hipMemsetD16("; + oss << "dest="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD16.dest); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD16.value); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD16.count); + oss << ")"; + break; + case HIP_API_ID_hipMemsetD16Async: + oss << "hipMemsetD16Async("; + oss << "dest="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD16Async.dest); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD16Async.value); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD16Async.count); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD16Async.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemsetD32: + oss << "hipMemsetD32("; + oss << "dest="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD32.dest); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD32.value); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD32.count); + oss << ")"; + break; + case HIP_API_ID_hipMemsetD32Async: + oss << "hipMemsetD32Async("; + oss << "dst="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD32Async.dst); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD32Async.value); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD32Async.count); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD32Async.stream); + oss << ")"; + break; + case HIP_API_ID_hipMemsetD8: + oss << "hipMemsetD8("; + oss << "dest="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD8.dest); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD8.value); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD8.count); + oss << ")"; + break; + case HIP_API_ID_hipMemsetD8Async: + oss << "hipMemsetD8Async("; + oss << "dest="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD8Async.dest); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD8Async.value); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD8Async.count); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMemsetD8Async.stream); + oss << ")"; + break; + case HIP_API_ID_hipMipmappedArrayCreate: + oss << "hipMipmappedArrayCreate("; + if (data->args.hipMipmappedArrayCreate.pHandle == NULL) oss << "pHandle=NULL"; + else { oss << "pHandle="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMipmappedArrayCreate.pHandle__val); } + if (data->args.hipMipmappedArrayCreate.pMipmappedArrayDesc == NULL) oss << ", pMipmappedArrayDesc=NULL"; + else { oss << ", pMipmappedArrayDesc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMipmappedArrayCreate.pMipmappedArrayDesc__val); } + oss << ", numMipmapLevels="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMipmappedArrayCreate.numMipmapLevels); + oss << ")"; + break; + case HIP_API_ID_hipMipmappedArrayDestroy: + oss << "hipMipmappedArrayDestroy("; + oss << "hMipmappedArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMipmappedArrayDestroy.hMipmappedArray); + oss << ")"; + break; + case HIP_API_ID_hipMipmappedArrayGetLevel: + oss << "hipMipmappedArrayGetLevel("; + if (data->args.hipMipmappedArrayGetLevel.pLevelArray == NULL) oss << "pLevelArray=NULL"; + else { oss << "pLevelArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMipmappedArrayGetLevel.pLevelArray__val); } + oss << ", hMipMappedArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMipmappedArrayGetLevel.hMipMappedArray); + oss << ", level="; roctracer::hip_support::detail::operator<<(oss, data->args.hipMipmappedArrayGetLevel.level); + oss << ")"; + break; + case HIP_API_ID_hipModuleGetFunction: + oss << "hipModuleGetFunction("; + if (data->args.hipModuleGetFunction.function == NULL) oss << "function=NULL"; + else { oss << "function="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleGetFunction.function__val); } + oss << ", module="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleGetFunction.module); + if (data->args.hipModuleGetFunction.kname == NULL) oss << ", kname=NULL"; + else { oss << ", kname="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleGetFunction.kname__val); } + oss << ")"; + break; + case HIP_API_ID_hipModuleGetGlobal: + oss << "hipModuleGetGlobal("; + if (data->args.hipModuleGetGlobal.dptr == NULL) oss << "dptr=NULL"; + else { oss << "dptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleGetGlobal.dptr__val); } + if (data->args.hipModuleGetGlobal.bytes == NULL) oss << ", bytes=NULL"; + else { oss << ", bytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleGetGlobal.bytes__val); } + oss << ", hmod="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleGetGlobal.hmod); + if (data->args.hipModuleGetGlobal.name == NULL) oss << ", name=NULL"; + else { oss << ", name="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleGetGlobal.name__val); } + oss << ")"; + break; + case HIP_API_ID_hipModuleGetTexRef: + oss << "hipModuleGetTexRef("; + if (data->args.hipModuleGetTexRef.texRef == NULL) oss << "texRef=NULL"; + else { oss << "texRef="; roctracer::hip_support::detail::operator<<(oss, (void*)data->args.hipModuleGetTexRef.texRef__val); } + oss << ", hmod="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleGetTexRef.hmod); + if (data->args.hipModuleGetTexRef.name == NULL) oss << ", name=NULL"; + else { oss << ", name="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleGetTexRef.name__val); } + oss << ")"; + break; + case HIP_API_ID_hipModuleLaunchCooperativeKernel: + oss << "hipModuleLaunchCooperativeKernel("; + oss << "f="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchCooperativeKernel.f); + oss << ", gridDimX="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchCooperativeKernel.gridDimX); + oss << ", gridDimY="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchCooperativeKernel.gridDimY); + oss << ", gridDimZ="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchCooperativeKernel.gridDimZ); + oss << ", blockDimX="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchCooperativeKernel.blockDimX); + oss << ", blockDimY="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchCooperativeKernel.blockDimY); + oss << ", blockDimZ="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchCooperativeKernel.blockDimZ); + oss << ", sharedMemBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchCooperativeKernel.sharedMemBytes); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchCooperativeKernel.stream); + if (data->args.hipModuleLaunchCooperativeKernel.kernelParams == NULL) oss << ", kernelParams=NULL"; + else { oss << ", kernelParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchCooperativeKernel.kernelParams__val); } + oss << ")"; + break; + case HIP_API_ID_hipModuleLaunchCooperativeKernelMultiDevice: + oss << "hipModuleLaunchCooperativeKernelMultiDevice("; + if (data->args.hipModuleLaunchCooperativeKernelMultiDevice.launchParamsList == NULL) oss << "launchParamsList=NULL"; + else { oss << "launchParamsList="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchCooperativeKernelMultiDevice.launchParamsList__val); } + oss << ", numDevices="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchCooperativeKernelMultiDevice.numDevices); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchCooperativeKernelMultiDevice.flags); + oss << ")"; + break; + case HIP_API_ID_hipModuleLaunchKernel: + oss << "hipModuleLaunchKernel("; + oss << "f="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchKernel.f); + oss << ", gridDimX="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchKernel.gridDimX); + oss << ", gridDimY="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchKernel.gridDimY); + oss << ", gridDimZ="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchKernel.gridDimZ); + oss << ", blockDimX="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchKernel.blockDimX); + oss << ", blockDimY="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchKernel.blockDimY); + oss << ", blockDimZ="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchKernel.blockDimZ); + oss << ", sharedMemBytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchKernel.sharedMemBytes); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchKernel.stream); + if (data->args.hipModuleLaunchKernel.kernelParams == NULL) oss << ", kernelParams=NULL"; + else { oss << ", kernelParams="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchKernel.kernelParams__val); } + if (data->args.hipModuleLaunchKernel.extra == NULL) oss << ", extra=NULL"; + else { oss << ", extra="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLaunchKernel.extra__val); } + oss << ")"; + break; + case HIP_API_ID_hipModuleLoad: + oss << "hipModuleLoad("; + if (data->args.hipModuleLoad.module == NULL) oss << "module=NULL"; + else { oss << "module="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLoad.module__val); } + if (data->args.hipModuleLoad.fname == NULL) oss << ", fname=NULL"; + else { oss << ", fname="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLoad.fname__val); } + oss << ")"; + break; + case HIP_API_ID_hipModuleLoadData: + oss << "hipModuleLoadData("; + if (data->args.hipModuleLoadData.module == NULL) oss << "module=NULL"; + else { oss << "module="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLoadData.module__val); } + oss << ", image="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLoadData.image); + oss << ")"; + break; + case HIP_API_ID_hipModuleLoadDataEx: + oss << "hipModuleLoadDataEx("; + if (data->args.hipModuleLoadDataEx.module == NULL) oss << "module=NULL"; + else { oss << "module="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLoadDataEx.module__val); } + oss << ", image="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLoadDataEx.image); + oss << ", numOptions="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLoadDataEx.numOptions); + if (data->args.hipModuleLoadDataEx.options == NULL) oss << ", options=NULL"; + else { oss << ", options="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLoadDataEx.options__val); } + if (data->args.hipModuleLoadDataEx.optionsValues == NULL) oss << ", optionsValues=NULL"; + else { oss << ", optionsValues="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleLoadDataEx.optionsValues__val); } + oss << ")"; + break; + case HIP_API_ID_hipModuleOccupancyMaxActiveBlocksPerMultiprocessor: + oss << "hipModuleOccupancyMaxActiveBlocksPerMultiprocessor("; + if (data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessor.numBlocks == NULL) oss << "numBlocks=NULL"; + else { oss << "numBlocks="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessor.numBlocks__val); } + oss << ", f="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessor.f); + oss << ", blockSize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessor.blockSize); + oss << ", dynSharedMemPerBlk="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessor.dynSharedMemPerBlk); + oss << ")"; + break; + case HIP_API_ID_hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags: + oss << "hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags("; + if (data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.numBlocks == NULL) oss << "numBlocks=NULL"; + else { oss << "numBlocks="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.numBlocks__val); } + oss << ", f="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.f); + oss << ", blockSize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.blockSize); + oss << ", dynSharedMemPerBlk="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.dynSharedMemPerBlk); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.flags); + oss << ")"; + break; + case HIP_API_ID_hipModuleOccupancyMaxPotentialBlockSize: + oss << "hipModuleOccupancyMaxPotentialBlockSize("; + if (data->args.hipModuleOccupancyMaxPotentialBlockSize.gridSize == NULL) oss << "gridSize=NULL"; + else { oss << "gridSize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxPotentialBlockSize.gridSize__val); } + if (data->args.hipModuleOccupancyMaxPotentialBlockSize.blockSize == NULL) oss << ", blockSize=NULL"; + else { oss << ", blockSize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxPotentialBlockSize.blockSize__val); } + oss << ", f="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxPotentialBlockSize.f); + oss << ", dynSharedMemPerBlk="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxPotentialBlockSize.dynSharedMemPerBlk); + oss << ", blockSizeLimit="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxPotentialBlockSize.blockSizeLimit); + oss << ")"; + break; + case HIP_API_ID_hipModuleOccupancyMaxPotentialBlockSizeWithFlags: + oss << "hipModuleOccupancyMaxPotentialBlockSizeWithFlags("; + if (data->args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.gridSize == NULL) oss << "gridSize=NULL"; + else { oss << "gridSize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.gridSize__val); } + if (data->args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.blockSize == NULL) oss << ", blockSize=NULL"; + else { oss << ", blockSize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.blockSize__val); } + oss << ", f="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.f); + oss << ", dynSharedMemPerBlk="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.dynSharedMemPerBlk); + oss << ", blockSizeLimit="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.blockSizeLimit); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleOccupancyMaxPotentialBlockSizeWithFlags.flags); + oss << ")"; + break; + case HIP_API_ID_hipModuleUnload: + oss << "hipModuleUnload("; + oss << "module="; roctracer::hip_support::detail::operator<<(oss, data->args.hipModuleUnload.module); + oss << ")"; + break; + case HIP_API_ID_hipOccupancyMaxActiveBlocksPerMultiprocessor: + oss << "hipOccupancyMaxActiveBlocksPerMultiprocessor("; + if (data->args.hipOccupancyMaxActiveBlocksPerMultiprocessor.numBlocks == NULL) oss << "numBlocks=NULL"; + else { oss << "numBlocks="; roctracer::hip_support::detail::operator<<(oss, data->args.hipOccupancyMaxActiveBlocksPerMultiprocessor.numBlocks__val); } + oss << ", f="; roctracer::hip_support::detail::operator<<(oss, data->args.hipOccupancyMaxActiveBlocksPerMultiprocessor.f); + oss << ", blockSize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipOccupancyMaxActiveBlocksPerMultiprocessor.blockSize); + oss << ", dynamicSMemSize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipOccupancyMaxActiveBlocksPerMultiprocessor.dynamicSMemSize); + oss << ")"; + break; + case HIP_API_ID_hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags: + oss << "hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags("; + if (data->args.hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.numBlocks == NULL) oss << "numBlocks=NULL"; + else { oss << "numBlocks="; roctracer::hip_support::detail::operator<<(oss, data->args.hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.numBlocks__val); } + oss << ", f="; roctracer::hip_support::detail::operator<<(oss, data->args.hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.f); + oss << ", blockSize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.blockSize); + oss << ", dynamicSMemSize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.dynamicSMemSize); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.flags); + oss << ")"; + break; + case HIP_API_ID_hipOccupancyMaxPotentialBlockSize: + oss << "hipOccupancyMaxPotentialBlockSize("; + if (data->args.hipOccupancyMaxPotentialBlockSize.gridSize == NULL) oss << "gridSize=NULL"; + else { oss << "gridSize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipOccupancyMaxPotentialBlockSize.gridSize__val); } + if (data->args.hipOccupancyMaxPotentialBlockSize.blockSize == NULL) oss << ", blockSize=NULL"; + else { oss << ", blockSize="; roctracer::hip_support::detail::operator<<(oss, data->args.hipOccupancyMaxPotentialBlockSize.blockSize__val); } + oss << ", f="; roctracer::hip_support::detail::operator<<(oss, data->args.hipOccupancyMaxPotentialBlockSize.f); + oss << ", dynSharedMemPerBlk="; roctracer::hip_support::detail::operator<<(oss, data->args.hipOccupancyMaxPotentialBlockSize.dynSharedMemPerBlk); + oss << ", blockSizeLimit="; roctracer::hip_support::detail::operator<<(oss, data->args.hipOccupancyMaxPotentialBlockSize.blockSizeLimit); + oss << ")"; + break; + case HIP_API_ID_hipPeekAtLastError: + oss << "hipPeekAtLastError("; + oss << ")"; + break; + case HIP_API_ID_hipPointerGetAttribute: + oss << "hipPointerGetAttribute("; + oss << "data="; roctracer::hip_support::detail::operator<<(oss, data->args.hipPointerGetAttribute.data); + oss << ", attribute="; roctracer::hip_support::detail::operator<<(oss, data->args.hipPointerGetAttribute.attribute); + oss << ", ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipPointerGetAttribute.ptr); + oss << ")"; + break; + case HIP_API_ID_hipPointerGetAttributes: + oss << "hipPointerGetAttributes("; + if (data->args.hipPointerGetAttributes.attributes == NULL) oss << "attributes=NULL"; + else { oss << "attributes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipPointerGetAttributes.attributes__val); } + oss << ", ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipPointerGetAttributes.ptr); + oss << ")"; + break; + case HIP_API_ID_hipPointerSetAttribute: + oss << "hipPointerSetAttribute("; + oss << "value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipPointerSetAttribute.value); + oss << ", attribute="; roctracer::hip_support::detail::operator<<(oss, data->args.hipPointerSetAttribute.attribute); + oss << ", ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipPointerSetAttribute.ptr); + oss << ")"; + break; + case HIP_API_ID_hipProfilerStart: + oss << "hipProfilerStart("; + oss << ")"; + break; + case HIP_API_ID_hipProfilerStop: + oss << "hipProfilerStop("; + oss << ")"; + break; + case HIP_API_ID_hipRuntimeGetVersion: + oss << "hipRuntimeGetVersion("; + if (data->args.hipRuntimeGetVersion.runtimeVersion == NULL) oss << "runtimeVersion=NULL"; + else { oss << "runtimeVersion="; roctracer::hip_support::detail::operator<<(oss, data->args.hipRuntimeGetVersion.runtimeVersion__val); } + oss << ")"; + break; + case HIP_API_ID_hipSetDevice: + oss << "hipSetDevice("; + oss << "deviceId="; roctracer::hip_support::detail::operator<<(oss, data->args.hipSetDevice.deviceId); + oss << ")"; + break; + case HIP_API_ID_hipSetDeviceFlags: + oss << "hipSetDeviceFlags("; + oss << "flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipSetDeviceFlags.flags); + oss << ")"; + break; + case HIP_API_ID_hipSetValidDevices: + oss << "hipSetValidDevices("; + if (data->args.hipSetValidDevices.device_arr == NULL) oss << "device_arr=NULL"; + else { oss << "device_arr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipSetValidDevices.device_arr__val); } + oss << ", len="; roctracer::hip_support::detail::operator<<(oss, data->args.hipSetValidDevices.len); + oss << ")"; + break; + case HIP_API_ID_hipSetupArgument: + oss << "hipSetupArgument("; + oss << "arg="; roctracer::hip_support::detail::operator<<(oss, data->args.hipSetupArgument.arg); + oss << ", size="; roctracer::hip_support::detail::operator<<(oss, data->args.hipSetupArgument.size); + oss << ", offset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipSetupArgument.offset); + oss << ")"; + break; + case HIP_API_ID_hipSignalExternalSemaphoresAsync: + oss << "hipSignalExternalSemaphoresAsync("; + if (data->args.hipSignalExternalSemaphoresAsync.extSemArray == NULL) oss << "extSemArray=NULL"; + else { oss << "extSemArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipSignalExternalSemaphoresAsync.extSemArray__val); } + if (data->args.hipSignalExternalSemaphoresAsync.paramsArray == NULL) oss << ", paramsArray=NULL"; + else { oss << ", paramsArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipSignalExternalSemaphoresAsync.paramsArray__val); } + oss << ", numExtSems="; roctracer::hip_support::detail::operator<<(oss, data->args.hipSignalExternalSemaphoresAsync.numExtSems); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipSignalExternalSemaphoresAsync.stream); + oss << ")"; + break; + case HIP_API_ID_hipStreamAddCallback: + oss << "hipStreamAddCallback("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamAddCallback.stream); + oss << ", callback="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamAddCallback.callback); + oss << ", userData="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamAddCallback.userData); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamAddCallback.flags); + oss << ")"; + break; + case HIP_API_ID_hipStreamAttachMemAsync: + oss << "hipStreamAttachMemAsync("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamAttachMemAsync.stream); + oss << ", dev_ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamAttachMemAsync.dev_ptr); + oss << ", length="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamAttachMemAsync.length); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamAttachMemAsync.flags); + oss << ")"; + break; + case HIP_API_ID_hipStreamBeginCapture: + oss << "hipStreamBeginCapture("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamBeginCapture.stream); + oss << ", mode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamBeginCapture.mode); + oss << ")"; + break; + case HIP_API_ID_hipStreamBeginCaptureToGraph: + oss << "hipStreamBeginCaptureToGraph("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamBeginCaptureToGraph.stream); + oss << ", graph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamBeginCaptureToGraph.graph); + if (data->args.hipStreamBeginCaptureToGraph.dependencies == NULL) oss << ", dependencies=NULL"; + else { oss << ", dependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamBeginCaptureToGraph.dependencies__val); } + if (data->args.hipStreamBeginCaptureToGraph.dependencyData == NULL) oss << ", dependencyData=NULL"; + else { oss << ", dependencyData="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamBeginCaptureToGraph.dependencyData__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamBeginCaptureToGraph.numDependencies); + oss << ", mode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamBeginCaptureToGraph.mode); + oss << ")"; + break; + case HIP_API_ID_hipStreamCreate: + oss << "hipStreamCreate("; + if (data->args.hipStreamCreate.stream == NULL) oss << "stream=NULL"; + else { oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamCreate.stream__val); } + oss << ")"; + break; + case HIP_API_ID_hipStreamCreateWithFlags: + oss << "hipStreamCreateWithFlags("; + if (data->args.hipStreamCreateWithFlags.stream == NULL) oss << "stream=NULL"; + else { oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamCreateWithFlags.stream__val); } + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamCreateWithFlags.flags); + oss << ")"; + break; + case HIP_API_ID_hipStreamCreateWithPriority: + oss << "hipStreamCreateWithPriority("; + if (data->args.hipStreamCreateWithPriority.stream == NULL) oss << "stream=NULL"; + else { oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamCreateWithPriority.stream__val); } + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamCreateWithPriority.flags); + oss << ", priority="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamCreateWithPriority.priority); + oss << ")"; + break; + case HIP_API_ID_hipStreamDestroy: + oss << "hipStreamDestroy("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamDestroy.stream); + oss << ")"; + break; + case HIP_API_ID_hipStreamEndCapture: + oss << "hipStreamEndCapture("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamEndCapture.stream); + if (data->args.hipStreamEndCapture.pGraph == NULL) oss << ", pGraph=NULL"; + else { oss << ", pGraph="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamEndCapture.pGraph__val); } + oss << ")"; + break; + case HIP_API_ID_hipStreamGetCaptureInfo: + oss << "hipStreamGetCaptureInfo("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamGetCaptureInfo.stream); + if (data->args.hipStreamGetCaptureInfo.pCaptureStatus == NULL) oss << ", pCaptureStatus=NULL"; + else { oss << ", pCaptureStatus="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamGetCaptureInfo.pCaptureStatus__val); } + if (data->args.hipStreamGetCaptureInfo.pId == NULL) oss << ", pId=NULL"; + else { oss << ", pId="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamGetCaptureInfo.pId__val); } + oss << ")"; + break; + case HIP_API_ID_hipStreamGetCaptureInfo_v2: + oss << "hipStreamGetCaptureInfo_v2("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamGetCaptureInfo_v2.stream); + if (data->args.hipStreamGetCaptureInfo_v2.captureStatus_out == NULL) oss << ", captureStatus_out=NULL"; + else { oss << ", captureStatus_out="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamGetCaptureInfo_v2.captureStatus_out__val); } + if (data->args.hipStreamGetCaptureInfo_v2.id_out == NULL) oss << ", id_out=NULL"; + else { oss << ", id_out="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamGetCaptureInfo_v2.id_out__val); } + if (data->args.hipStreamGetCaptureInfo_v2.graph_out == NULL) oss << ", graph_out=NULL"; + else { oss << ", graph_out="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamGetCaptureInfo_v2.graph_out__val); } + if (data->args.hipStreamGetCaptureInfo_v2.dependencies_out == NULL) oss << ", dependencies_out=NULL"; + else { oss << ", dependencies_out="; roctracer::hip_support::detail::operator<<(oss, (void*)data->args.hipStreamGetCaptureInfo_v2.dependencies_out__val); } + if (data->args.hipStreamGetCaptureInfo_v2.numDependencies_out == NULL) oss << ", numDependencies_out=NULL"; + else { oss << ", numDependencies_out="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamGetCaptureInfo_v2.numDependencies_out__val); } + oss << ")"; + break; + case HIP_API_ID_hipStreamGetDevice: + oss << "hipStreamGetDevice("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamGetDevice.stream); + if (data->args.hipStreamGetDevice.device == NULL) oss << ", device=NULL"; + else { oss << ", device="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamGetDevice.device__val); } + oss << ")"; + break; + case HIP_API_ID_hipStreamGetFlags: + oss << "hipStreamGetFlags("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamGetFlags.stream); + if (data->args.hipStreamGetFlags.flags == NULL) oss << ", flags=NULL"; + else { oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamGetFlags.flags__val); } + oss << ")"; + break; + case HIP_API_ID_hipStreamGetPriority: + oss << "hipStreamGetPriority("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamGetPriority.stream); + if (data->args.hipStreamGetPriority.priority == NULL) oss << ", priority=NULL"; + else { oss << ", priority="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamGetPriority.priority__val); } + oss << ")"; + break; + case HIP_API_ID_hipStreamIsCapturing: + oss << "hipStreamIsCapturing("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamIsCapturing.stream); + if (data->args.hipStreamIsCapturing.pCaptureStatus == NULL) oss << ", pCaptureStatus=NULL"; + else { oss << ", pCaptureStatus="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamIsCapturing.pCaptureStatus__val); } + oss << ")"; + break; + case HIP_API_ID_hipStreamQuery: + oss << "hipStreamQuery("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamQuery.stream); + oss << ")"; + break; + case HIP_API_ID_hipStreamSynchronize: + oss << "hipStreamSynchronize("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamSynchronize.stream); + oss << ")"; + break; + case HIP_API_ID_hipStreamUpdateCaptureDependencies: + oss << "hipStreamUpdateCaptureDependencies("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamUpdateCaptureDependencies.stream); + if (data->args.hipStreamUpdateCaptureDependencies.dependencies == NULL) oss << ", dependencies=NULL"; + else { oss << ", dependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamUpdateCaptureDependencies.dependencies__val); } + oss << ", numDependencies="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamUpdateCaptureDependencies.numDependencies); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamUpdateCaptureDependencies.flags); + oss << ")"; + break; + case HIP_API_ID_hipStreamWaitEvent: + oss << "hipStreamWaitEvent("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWaitEvent.stream); + oss << ", event="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWaitEvent.event); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWaitEvent.flags); + oss << ")"; + break; + case HIP_API_ID_hipStreamWaitValue32: + oss << "hipStreamWaitValue32("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWaitValue32.stream); + oss << ", ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWaitValue32.ptr); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWaitValue32.value); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWaitValue32.flags); + oss << ", mask="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWaitValue32.mask); + oss << ")"; + break; + case HIP_API_ID_hipStreamWaitValue64: + oss << "hipStreamWaitValue64("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWaitValue64.stream); + oss << ", ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWaitValue64.ptr); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWaitValue64.value); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWaitValue64.flags); + oss << ", mask="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWaitValue64.mask); + oss << ")"; + break; + case HIP_API_ID_hipStreamWriteValue32: + oss << "hipStreamWriteValue32("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWriteValue32.stream); + oss << ", ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWriteValue32.ptr); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWriteValue32.value); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWriteValue32.flags); + oss << ")"; + break; + case HIP_API_ID_hipStreamWriteValue64: + oss << "hipStreamWriteValue64("; + oss << "stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWriteValue64.stream); + oss << ", ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWriteValue64.ptr); + oss << ", value="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWriteValue64.value); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipStreamWriteValue64.flags); + oss << ")"; + break; + case HIP_API_ID_hipTexRefGetAddress: + oss << "hipTexRefGetAddress("; + if (data->args.hipTexRefGetAddress.dev_ptr == NULL) oss << "dev_ptr=NULL"; + else { oss << "dev_ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetAddress.dev_ptr__val); } + if (data->args.hipTexRefGetAddress.texRef == NULL) oss << ", texRef=NULL"; + else { oss << ", texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetAddress.texRef__val); } + oss << ")"; + break; + case HIP_API_ID_hipTexRefGetArray: + oss << "hipTexRefGetArray("; + if (data->args.hipTexRefGetArray.pArray == NULL) oss << "pArray=NULL"; + else { oss << "pArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetArray.pArray__val); } + if (data->args.hipTexRefGetArray.texRef == NULL) oss << ", texRef=NULL"; + else { oss << ", texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetArray.texRef__val); } + oss << ")"; + break; + case HIP_API_ID_hipTexRefGetBorderColor: + oss << "hipTexRefGetBorderColor("; + if (data->args.hipTexRefGetBorderColor.pBorderColor == NULL) oss << "pBorderColor=NULL"; + else { oss << "pBorderColor="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetBorderColor.pBorderColor__val); } + if (data->args.hipTexRefGetBorderColor.texRef == NULL) oss << ", texRef=NULL"; + else { oss << ", texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetBorderColor.texRef__val); } + oss << ")"; + break; + case HIP_API_ID_hipTexRefGetFlags: + oss << "hipTexRefGetFlags("; + if (data->args.hipTexRefGetFlags.pFlags == NULL) oss << "pFlags=NULL"; + else { oss << "pFlags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetFlags.pFlags__val); } + if (data->args.hipTexRefGetFlags.texRef == NULL) oss << ", texRef=NULL"; + else { oss << ", texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetFlags.texRef__val); } + oss << ")"; + break; + case HIP_API_ID_hipTexRefGetFormat: + oss << "hipTexRefGetFormat("; + if (data->args.hipTexRefGetFormat.pFormat == NULL) oss << "pFormat=NULL"; + else { oss << "pFormat="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetFormat.pFormat__val); } + if (data->args.hipTexRefGetFormat.pNumChannels == NULL) oss << ", pNumChannels=NULL"; + else { oss << ", pNumChannels="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetFormat.pNumChannels__val); } + if (data->args.hipTexRefGetFormat.texRef == NULL) oss << ", texRef=NULL"; + else { oss << ", texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetFormat.texRef__val); } + oss << ")"; + break; + case HIP_API_ID_hipTexRefGetMaxAnisotropy: + oss << "hipTexRefGetMaxAnisotropy("; + if (data->args.hipTexRefGetMaxAnisotropy.pmaxAnsio == NULL) oss << "pmaxAnsio=NULL"; + else { oss << "pmaxAnsio="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetMaxAnisotropy.pmaxAnsio__val); } + if (data->args.hipTexRefGetMaxAnisotropy.texRef == NULL) oss << ", texRef=NULL"; + else { oss << ", texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetMaxAnisotropy.texRef__val); } + oss << ")"; + break; + case HIP_API_ID_hipTexRefGetMipMappedArray: + oss << "hipTexRefGetMipMappedArray("; + if (data->args.hipTexRefGetMipMappedArray.pArray == NULL) oss << "pArray=NULL"; + else { oss << "pArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetMipMappedArray.pArray__val); } + if (data->args.hipTexRefGetMipMappedArray.texRef == NULL) oss << ", texRef=NULL"; + else { oss << ", texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetMipMappedArray.texRef__val); } + oss << ")"; + break; + case HIP_API_ID_hipTexRefGetMipmapLevelBias: + oss << "hipTexRefGetMipmapLevelBias("; + if (data->args.hipTexRefGetMipmapLevelBias.pbias == NULL) oss << "pbias=NULL"; + else { oss << "pbias="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetMipmapLevelBias.pbias__val); } + if (data->args.hipTexRefGetMipmapLevelBias.texRef == NULL) oss << ", texRef=NULL"; + else { oss << ", texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetMipmapLevelBias.texRef__val); } + oss << ")"; + break; + case HIP_API_ID_hipTexRefGetMipmapLevelClamp: + oss << "hipTexRefGetMipmapLevelClamp("; + if (data->args.hipTexRefGetMipmapLevelClamp.pminMipmapLevelClamp == NULL) oss << "pminMipmapLevelClamp=NULL"; + else { oss << "pminMipmapLevelClamp="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetMipmapLevelClamp.pminMipmapLevelClamp__val); } + if (data->args.hipTexRefGetMipmapLevelClamp.pmaxMipmapLevelClamp == NULL) oss << ", pmaxMipmapLevelClamp=NULL"; + else { oss << ", pmaxMipmapLevelClamp="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetMipmapLevelClamp.pmaxMipmapLevelClamp__val); } + if (data->args.hipTexRefGetMipmapLevelClamp.texRef == NULL) oss << ", texRef=NULL"; + else { oss << ", texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefGetMipmapLevelClamp.texRef__val); } + oss << ")"; + break; + case HIP_API_ID_hipTexRefSetAddress: + oss << "hipTexRefSetAddress("; + if (data->args.hipTexRefSetAddress.ByteOffset == NULL) oss << "ByteOffset=NULL"; + else { oss << "ByteOffset="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetAddress.ByteOffset__val); } + if (data->args.hipTexRefSetAddress.texRef == NULL) oss << ", texRef=NULL"; + else { oss << ", texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetAddress.texRef__val); } + oss << ", dptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetAddress.dptr); + oss << ", bytes="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetAddress.bytes); + oss << ")"; + break; + case HIP_API_ID_hipTexRefSetAddress2D: + oss << "hipTexRefSetAddress2D("; + if (data->args.hipTexRefSetAddress2D.texRef == NULL) oss << "texRef=NULL"; + else { oss << "texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetAddress2D.texRef__val); } + if (data->args.hipTexRefSetAddress2D.desc == NULL) oss << ", desc=NULL"; + else { oss << ", desc="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetAddress2D.desc__val); } + oss << ", dptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetAddress2D.dptr); + oss << ", Pitch="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetAddress2D.Pitch); + oss << ")"; + break; + case HIP_API_ID_hipTexRefSetArray: + oss << "hipTexRefSetArray("; + if (data->args.hipTexRefSetArray.tex == NULL) oss << "tex=NULL"; + else { oss << "tex="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetArray.tex__val); } + oss << ", array="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetArray.array); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetArray.flags); + oss << ")"; + break; + case HIP_API_ID_hipTexRefSetBorderColor: + oss << "hipTexRefSetBorderColor("; + if (data->args.hipTexRefSetBorderColor.texRef == NULL) oss << "texRef=NULL"; + else { oss << "texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetBorderColor.texRef__val); } + if (data->args.hipTexRefSetBorderColor.pBorderColor == NULL) oss << ", pBorderColor=NULL"; + else { oss << ", pBorderColor="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetBorderColor.pBorderColor__val); } + oss << ")"; + break; + case HIP_API_ID_hipTexRefSetFlags: + oss << "hipTexRefSetFlags("; + if (data->args.hipTexRefSetFlags.texRef == NULL) oss << "texRef=NULL"; + else { oss << "texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetFlags.texRef__val); } + oss << ", Flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetFlags.Flags); + oss << ")"; + break; + case HIP_API_ID_hipTexRefSetFormat: + oss << "hipTexRefSetFormat("; + if (data->args.hipTexRefSetFormat.texRef == NULL) oss << "texRef=NULL"; + else { oss << "texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetFormat.texRef__val); } + oss << ", fmt="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetFormat.fmt); + oss << ", NumPackedComponents="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetFormat.NumPackedComponents); + oss << ")"; + break; + case HIP_API_ID_hipTexRefSetMaxAnisotropy: + oss << "hipTexRefSetMaxAnisotropy("; + if (data->args.hipTexRefSetMaxAnisotropy.texRef == NULL) oss << "texRef=NULL"; + else { oss << "texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetMaxAnisotropy.texRef__val); } + oss << ", maxAniso="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetMaxAnisotropy.maxAniso); + oss << ")"; + break; + case HIP_API_ID_hipTexRefSetMipmapLevelBias: + oss << "hipTexRefSetMipmapLevelBias("; + if (data->args.hipTexRefSetMipmapLevelBias.texRef == NULL) oss << "texRef=NULL"; + else { oss << "texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetMipmapLevelBias.texRef__val); } + oss << ", bias="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetMipmapLevelBias.bias); + oss << ")"; + break; + case HIP_API_ID_hipTexRefSetMipmapLevelClamp: + oss << "hipTexRefSetMipmapLevelClamp("; + if (data->args.hipTexRefSetMipmapLevelClamp.texRef == NULL) oss << "texRef=NULL"; + else { oss << "texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetMipmapLevelClamp.texRef__val); } + oss << ", minMipMapLevelClamp="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetMipmapLevelClamp.minMipMapLevelClamp); + oss << ", maxMipMapLevelClamp="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetMipmapLevelClamp.maxMipMapLevelClamp); + oss << ")"; + break; + case HIP_API_ID_hipTexRefSetMipmappedArray: + oss << "hipTexRefSetMipmappedArray("; + if (data->args.hipTexRefSetMipmappedArray.texRef == NULL) oss << "texRef=NULL"; + else { oss << "texRef="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetMipmappedArray.texRef__val); } + if (data->args.hipTexRefSetMipmappedArray.mipmappedArray == NULL) oss << ", mipmappedArray=NULL"; + else { oss << ", mipmappedArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetMipmappedArray.mipmappedArray__val); } + oss << ", Flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipTexRefSetMipmappedArray.Flags); + oss << ")"; + break; + case HIP_API_ID_hipThreadExchangeStreamCaptureMode: + oss << "hipThreadExchangeStreamCaptureMode("; + if (data->args.hipThreadExchangeStreamCaptureMode.mode == NULL) oss << "mode=NULL"; + else { oss << "mode="; roctracer::hip_support::detail::operator<<(oss, data->args.hipThreadExchangeStreamCaptureMode.mode__val); } + oss << ")"; + break; + case HIP_API_ID_hipUserObjectCreate: + oss << "hipUserObjectCreate("; + if (data->args.hipUserObjectCreate.object_out == NULL) oss << "object_out=NULL"; + else { oss << "object_out="; roctracer::hip_support::detail::operator<<(oss, data->args.hipUserObjectCreate.object_out__val); } + oss << ", ptr="; roctracer::hip_support::detail::operator<<(oss, data->args.hipUserObjectCreate.ptr); + oss << ", destroy="; roctracer::hip_support::detail::operator<<(oss, data->args.hipUserObjectCreate.destroy); + oss << ", initialRefcount="; roctracer::hip_support::detail::operator<<(oss, data->args.hipUserObjectCreate.initialRefcount); + oss << ", flags="; roctracer::hip_support::detail::operator<<(oss, data->args.hipUserObjectCreate.flags); + oss << ")"; + break; + case HIP_API_ID_hipUserObjectRelease: + oss << "hipUserObjectRelease("; + oss << "object="; roctracer::hip_support::detail::operator<<(oss, data->args.hipUserObjectRelease.object); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipUserObjectRelease.count); + oss << ")"; + break; + case HIP_API_ID_hipUserObjectRetain: + oss << "hipUserObjectRetain("; + oss << "object="; roctracer::hip_support::detail::operator<<(oss, data->args.hipUserObjectRetain.object); + oss << ", count="; roctracer::hip_support::detail::operator<<(oss, data->args.hipUserObjectRetain.count); + oss << ")"; + break; + case HIP_API_ID_hipWaitExternalSemaphoresAsync: + oss << "hipWaitExternalSemaphoresAsync("; + if (data->args.hipWaitExternalSemaphoresAsync.extSemArray == NULL) oss << "extSemArray=NULL"; + else { oss << "extSemArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipWaitExternalSemaphoresAsync.extSemArray__val); } + if (data->args.hipWaitExternalSemaphoresAsync.paramsArray == NULL) oss << ", paramsArray=NULL"; + else { oss << ", paramsArray="; roctracer::hip_support::detail::operator<<(oss, data->args.hipWaitExternalSemaphoresAsync.paramsArray__val); } + oss << ", numExtSems="; roctracer::hip_support::detail::operator<<(oss, data->args.hipWaitExternalSemaphoresAsync.numExtSems); + oss << ", stream="; roctracer::hip_support::detail::operator<<(oss, data->args.hipWaitExternalSemaphoresAsync.stream); + oss << ")"; + break; + default: oss << "unknown"; + }; + return strdup(oss.str().c_str()); +} +#endif // HIP_PROF_HIP_API_STRING +#endif // _HIP_PROF_STR_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_runtime_prof.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_runtime_prof.h new file mode 100644 index 0000000000000000000000000000000000000000..307e75c21e76bb6545746e64d9cba9e6b06a56d6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hip_runtime_prof.h @@ -0,0 +1,78 @@ +/* +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_RUNTIME_PROF_H +#define HIP_INCLUDE_HIP_AMD_DETAIL_HIP_RUNTIME_PROF_H + +// HIP ROCclr Op IDs enumeration +enum HipVdiOpId { + kHipVdiOpIdDispatch = 0, + kHipVdiOpIdCopy = 1, + kHipVdiOpIdBarrier = 2, + kHipVdiOpIdNumber = 3 +}; + +// Types of ROCclr commands +enum HipVdiCommandKind { + kHipVdiCommandKernel = 0x11F0, + kHipVdiCommandTask = 0x11F1, + kHipVdiMemcpyDeviceToHost = 0x11F3, + kHipHipVdiMemcpyHostToDevice = 0x11F4, + kHipVdiMemcpyDeviceToDevice = 0x11F5, + kHipVidMemcpyDeviceToHostRect = 0x1201, + kHipVdiMemcpyHostToDeviceRect = 0x1202, + kHipVdiMemcpyDeviceToDeviceRect = 0x1203, + kHipVdiFillMemory = 0x1207, +}; + +/** + * @brief Initializes activity callback + * + * @param [input] id_callback Event ID callback function + * @param [input] op_callback Event operation callback function + * @param [input] arg Arguments passed into callback + * + * @returns None + */ +void hipInitActivityCallback(void* id_callback, void* op_callback, void* arg); + +/** + * @brief Enables activity callback + * + * @param [input] op Operation, which will trigger a callback (@see HipVdiOpId) + * @param [input] enable Enable state for the callback + * + * @returns True if successful + */ +bool hipEnableActivityCallback(uint32_t op, bool enable); + +/** + * @brief Returns the description string for the operation kind + * + * @param [input] id Command kind id (@see HipVdiCommandKind) + * + * @returns A pointer to a const string with the command description + */ +const char* hipGetCmdName(uint32_t id); + +#endif // HIP_INCLUDE_HIP_AMD_DETAIL_HIP_RUNTIME_PROF_H + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/host_defines.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/host_defines.h new file mode 100644 index 0000000000000000000000000000000000000000..e7e8364969f76f124be31c974762a42d53ee9532 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/host_defines.h @@ -0,0 +1,184 @@ +/* +Copyright (c) 2015 - 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 amd_detail/host_defines.h + * @brief TODO-doc + */ + +#ifndef HIP_INCLUDE_HIP_AMD_DETAIL_HOST_DEFINES_H +#define HIP_INCLUDE_HIP_AMD_DETAIL_HOST_DEFINES_H + +// Add guard to Generic Grid Launch method +#ifndef GENERIC_GRID_LAUNCH +#define GENERIC_GRID_LAUNCH 1 +#endif + +#if defined(__clang__) && defined(__HIP__) + +namespace __hip_internal { +typedef unsigned char uint8_t; +typedef unsigned short uint16_t; +typedef unsigned int uint32_t; +typedef unsigned long long uint64_t; +typedef signed char int8_t; +typedef signed short int16_t; +typedef signed int int32_t; +typedef signed long long int64_t; + +template struct integral_constant { + static constexpr const _Tp value = __v; + typedef _Tp value_type; + typedef integral_constant type; + constexpr operator value_type() const { return value; } + constexpr value_type operator()() const { return value; } +}; +template constexpr const _Tp integral_constant<_Tp, __v>::value; + +typedef integral_constant true_type; +typedef integral_constant false_type; + +template using bool_constant = integral_constant; +typedef bool_constant true_type; +typedef bool_constant false_type; + +template struct enable_if {}; +template struct enable_if { typedef __T type; }; + +template struct true_or_false_type : public false_type {}; +template<> struct true_or_false_type : public true_type {}; + +template struct is_integral : public false_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; +template <> struct is_integral : public true_type {}; + +template struct is_arithmetic : public false_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; +template <> struct is_arithmetic : public true_type {}; + +template struct is_floating_point : public false_type {}; +template<> struct is_floating_point : public true_type {}; +template<> struct is_floating_point : public true_type {}; +template<> struct is_floating_point : public true_type {}; + +template struct is_same : public false_type {}; +template struct is_same<__T, __T> : public true_type {}; + +template::value> + struct is_signed : public false_type {}; +template + struct is_signed<_Tp, true> : public true_or_false_type<_Tp(-1) < _Tp(0)> {}; + +template struct char_traits; +template> class basic_istream; +template> class basic_ostream; +typedef basic_istream istream; +typedef basic_ostream ostream; + +template + struct is_standard_layout + : public integral_constant + { }; + +template + struct is_trivial + : public integral_constant + { }; + + +template struct conditional { using type = T; }; +template struct conditional { using type = F; }; +} +typedef __hip_internal::uint8_t __hip_uint8_t; +typedef __hip_internal::uint16_t __hip_uint16_t; +typedef __hip_internal::uint32_t __hip_uint32_t; +typedef __hip_internal::uint64_t __hip_uint64_t; +typedef __hip_internal::int8_t __hip_int8_t; +typedef __hip_internal::int16_t __hip_int16_t; +typedef __hip_internal::int32_t __hip_int32_t; +typedef __hip_internal::int64_t __hip_int64_t; + +#if !__CLANG_HIP_RUNTIME_WRAPPER_INCLUDED__ +#define __host__ __attribute__((host)) +#define __device__ __attribute__((device)) +#define __global__ __attribute__((global)) +#define __shared__ __attribute__((shared)) +#define __constant__ __attribute__((constant)) +#endif // !__CLANG_HIP_RUNTIME_WRAPPER_INCLUDED__ + +#if !defined(__has_feature) || !__has_feature(cuda_noinline_keyword) +#define __noinline__ __attribute__((noinline)) +#endif + +#define __forceinline__ inline __attribute__((always_inline)) + +#if __HIP_NO_IMAGE_SUPPORT +#define __hip_img_chk__ __attribute__((unavailable("The image/texture API not supported on the device"))) +#else +#define __hip_img_chk__ +#endif + +#else + +// Non-HCC compiler +/** + * Function and kernel markers + */ +#define __host__ +#define __device__ + +#define __global__ + +#define __noinline__ +#define __forceinline__ inline + +#define __shared__ +#define __constant__ + +#define __hip_img_chk__ +#endif + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hsa_helpers.hpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hsa_helpers.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0c1708502219abcafef174f434c3be20d61f6e96 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/hsa_helpers.hpp @@ -0,0 +1,102 @@ +/* +Copyright (c) 2015 - 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. +*/ +#pragma once + +#include + +#include +#include +#include + +namespace hip_impl { +inline void* address(hsa_executable_symbol_t x) { + void* r = nullptr; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ADDRESS, &r); + + return r; +} + +inline hsa_agent_t agent(hsa_executable_symbol_t x) { + hsa_agent_t r = {}; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_AGENT, &r); + + return r; +} + +inline std::uint32_t group_size(hsa_executable_symbol_t x) { + std::uint32_t r = 0u; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_GROUP_SEGMENT_SIZE, &r); + + return r; +} + +inline hsa_isa_t isa(hsa_agent_t x) { + hsa_isa_t r = {}; + hsa_agent_iterate_isas(x, + [](hsa_isa_t i, void* o) { + *static_cast(o) = i; // Pick the first. + + return HSA_STATUS_INFO_BREAK; + }, + &r); + + return r; +} + +inline std::uint64_t kernel_object(hsa_executable_symbol_t x) { + std::uint64_t r = 0u; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_OBJECT, &r); + + return r; +} + +inline std::string name(hsa_executable_symbol_t x) { + std::uint32_t sz = 0u; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_NAME_LENGTH, &sz); + + std::string r(sz, '\0'); + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_NAME, &r.front()); + + return r; +} + +inline std::uint32_t private_size(hsa_executable_symbol_t x) { + std::uint32_t r = 0u; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_PRIVATE_SEGMENT_SIZE, &r); + + return r; +} + +inline std::uint32_t size(hsa_executable_symbol_t x) { + std::uint32_t r = 0; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_SIZE, &r); + + return r; +} + +inline hsa_symbol_kind_t type(hsa_executable_symbol_t x) { + hsa_symbol_kind_t r = {}; + hsa_executable_symbol_get_info(x, HSA_EXECUTABLE_SYMBOL_INFO_TYPE, &r); + + return r; +} +} // namespace hip_impl \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/macro_based_grid_launch.hpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/macro_based_grid_launch.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d631e4d5cff57a650efa242829b82edb601f9b5e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/macro_based_grid_launch.hpp @@ -0,0 +1,798 @@ +/* +Copyright (c) 2015 - 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. +*/ + +#pragma once + +#include "concepts.hpp" +#include "helpers.hpp" + +#include "hc.hpp" +#include "hip/hip_ext.h" +#include "hip_runtime.h" + +#include +#include +#include +#include +#include + +namespace hip_impl { +namespace { +struct New_grid_launch_tag {}; +struct Old_grid_launch_tag {}; + +template +class RAII_guard { + D dtor_; + + public: + RAII_guard() = default; + + RAII_guard(const C& ctor, D dtor) : dtor_{std::move(dtor)} { ctor(); } + + RAII_guard(const RAII_guard&) = default; + RAII_guard(RAII_guard&&) = default; + + RAII_guard& operator=(const RAII_guard&) = default; + RAII_guard& operator=(RAII_guard&&) = default; + + ~RAII_guard() { dtor_(); } +}; + +template +RAII_guard make_RAII_guard(const C& ctor, D dtor) { + return RAII_guard{ctor, std::move(dtor)}; +} + +template +using is_new_grid_launch_t = typename std::conditional{}, New_grid_launch_tag, + Old_grid_launch_tag>::type; +} // namespace + +// TODO: - dispatch rank should be derived from the domain dimensions passed +// in, and not always assumed to be 3; + +template +requires(Domain == + {Ts...}) inline void grid_launch_hip_impl_(New_grid_launch_tag, dim3 num_blocks, + dim3 dim_blocks, int group_mem_bytes, + const hc::accelerator_view& acc_v, K k) { + const auto d = + hc::extent<3>{num_blocks.z * dim_blocks.z, num_blocks.y * dim_blocks.y, + num_blocks.x * dim_blocks.x} + .tile_with_dynamic(dim_blocks.z, dim_blocks.y, dim_blocks.x, group_mem_bytes); + + try { + hc::parallel_for_each(acc_v, d, k); + } catch (std::exception& ex) { + std::cerr << "Failed in " << __func__ << ", with exception: " << ex.what() << std::endl; + hip_throw(ex); + } +} + +// TODO: these are workarounds, they should be removed. + +hc::accelerator_view lock_stream_hip_(hipStream_t&, void*&); +void print_prelaunch_trace_(const char*, dim3, dim3, int, hipStream_t); +void unlock_stream_hip_(hipStream_t, void*, const char*, hc::accelerator_view*); + +template +requires(Domain == {Ts...}) inline void grid_launch_hip_impl_(New_grid_launch_tag, + dim3 num_blocks, dim3 dim_blocks, + int group_mem_bytes, + hipStream_t stream, + const char* kernel_name, K k) { + void* lck_stream = nullptr; + auto acc_v = lock_stream_hip_(stream, lck_stream); + auto stream_guard = + make_RAII_guard(std::bind(print_prelaunch_trace_, kernel_name, num_blocks, dim_blocks, + group_mem_bytes, stream), + std::bind(unlock_stream_hip_, stream, lck_stream, kernel_name, &acc_v)); + + try { + grid_launch_hip_impl_(New_grid_launch_tag{}, std::move(num_blocks), std::move(dim_blocks), + group_mem_bytes, acc_v, std::move(k)); + } catch (std::exception& ex) { + std::cerr << "Failed in " << __func__ << ", with exception: " << ex.what() << std::endl; + hip_throw(ex); + } +} + +template +requires(Domain == + {hipLaunchParm, Ts...}) inline void grid_launch_hip_impl_(Old_grid_launch_tag, + dim3 num_blocks, dim3 dim_blocks, + int group_mem_bytes, + hipStream_t stream, K k) { + grid_launch_hip_impl_(New_grid_launch_tag{}, std::move(num_blocks), std::move(dim_blocks), + group_mem_bytes, std::move(stream), std::move(k)); +} + +template +requires(Domain == {hipLaunchParm, Ts...}) inline void grid_launch_hip_impl_( + Old_grid_launch_tag, dim3 num_blocks, dim3 dim_blocks, int group_mem_bytes, hipStream_t stream, + const char* kernel_name, K k) { + grid_launch_hip_impl_(New_grid_launch_tag{}, std::move(num_blocks), std::move(dim_blocks), + group_mem_bytes, std::move(stream), kernel_name, std::move(k)); +} + +template +requires(Domain == {Ts...}) inline std::enable_if_t< + !std::is_function::value> grid_launch_hip_(dim3 num_blocks, dim3 dim_blocks, + int group_mem_bytes, hipStream_t stream, + const char* kernel_name, K k) { + grid_launch_hip_impl_(is_new_grid_launch_t{}, std::move(num_blocks), + std::move(dim_blocks), group_mem_bytes, std::move(stream), kernel_name, + std::move(k)); +} + +template +requires(Domain == {Ts...}) inline std::enable_if_t< + !std::is_function::value> grid_launch_hip_(dim3 num_blocks, dim3 dim_blocks, + int group_mem_bytes, hipStream_t stream, K k) { + grid_launch_hip_impl_(is_new_grid_launch_t{}, std::move(num_blocks), + std::move(dim_blocks), group_mem_bytes, std::move(stream), std::move(k)); +} + +// TODO: these are temporary and purposefully noisy and disruptive. +#define make_kernel_name_hip(k, n) \ + HIP_kernel_functor_name_begin##_##k##_##HIP_kernel_functor_name_end##_##n + +#define make_kernel_functor_hip_30(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, \ + p22, p23, p24, p25, p26, p27) \ + struct make_kernel_name_hip(function_name, 28) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + std::decay_t _p13_; \ + std::decay_t _p14_; \ + std::decay_t _p15_; \ + std::decay_t _p16_; \ + std::decay_t _p17_; \ + std::decay_t _p18_; \ + std::decay_t _p19_; \ + std::decay_t _p20_; \ + std::decay_t _p21_; \ + std::decay_t _p22_; \ + std::decay_t _p23_; \ + std::decay_t _p24_; \ + std::decay_t _p25_; \ + std::decay_t _p26_; \ + std::decay_t _p27_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_, _p13_, _p14_, _p15_, _p16_, _p17_, _p18_, _p19_, _p20_, _p21_, \ + _p22_, _p23_, _p24_, _p25_, _p26_, _p27_); \ + } \ + } +#define make_kernel_functor_hip_29(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, \ + p22, p23, p24, p25, p26) \ + struct make_kernel_name_hip(function_name, 27) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + std::decay_t _p13_; \ + std::decay_t _p14_; \ + std::decay_t _p15_; \ + std::decay_t _p16_; \ + std::decay_t _p17_; \ + std::decay_t _p18_; \ + std::decay_t _p19_; \ + std::decay_t _p20_; \ + std::decay_t _p21_; \ + std::decay_t _p22_; \ + std::decay_t _p23_; \ + std::decay_t _p24_; \ + std::decay_t _p25_; \ + std::decay_t _p26_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_, _p13_, _p14_, _p15_, _p16_, _p17_, _p18_, _p19_, _p20_, _p21_, \ + _p22_, _p23_, _p24_, _p25_, _p26_); \ + } \ + } +#define make_kernel_functor_hip_28(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, \ + p22, p23, p24, p25) \ + struct make_kernel_name_hip(function_name, 26) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + std::decay_t _p13_; \ + std::decay_t _p14_; \ + std::decay_t _p15_; \ + std::decay_t _p16_; \ + std::decay_t _p17_; \ + std::decay_t _p18_; \ + std::decay_t _p19_; \ + std::decay_t _p20_; \ + std::decay_t _p21_; \ + std::decay_t _p22_; \ + std::decay_t _p23_; \ + std::decay_t _p24_; \ + std::decay_t _p25_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_, _p13_, _p14_, _p15_, _p16_, _p17_, _p18_, _p19_, _p20_, _p21_, \ + _p22_, _p23_, _p24_, _p25_); \ + } \ + } +#define make_kernel_functor_hip_27(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, \ + p22, p23, p24) \ + struct make_kernel_name_hip(function_name, 25) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + std::decay_t _p13_; \ + std::decay_t _p14_; \ + std::decay_t _p15_; \ + std::decay_t _p16_; \ + std::decay_t _p17_; \ + std::decay_t _p18_; \ + std::decay_t _p19_; \ + std::decay_t _p20_; \ + std::decay_t _p21_; \ + std::decay_t _p22_; \ + std::decay_t _p23_; \ + std::decay_t _p24_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_, _p13_, _p14_, _p15_, _p16_, _p17_, _p18_, _p19_, _p20_, _p21_, \ + _p22_, _p23_, _p24_); \ + } \ + } +#define make_kernel_functor_hip_26(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, \ + p22, p23) \ + struct make_kernel_name_hip(function_name, 24) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + std::decay_t _p13_; \ + std::decay_t _p14_; \ + std::decay_t _p15_; \ + std::decay_t _p16_; \ + std::decay_t _p17_; \ + std::decay_t _p18_; \ + std::decay_t _p19_; \ + std::decay_t _p20_; \ + std::decay_t _p21_; \ + std::decay_t _p22_; \ + std::decay_t _p23_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_, _p13_, _p14_, _p15_, _p16_, _p17_, _p18_, _p19_, _p20_, _p21_, \ + _p22_, _p23_); \ + } \ + } +#define make_kernel_functor_hip_25(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, \ + p22) \ + struct make_kernel_name_hip(function_name, 23) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + std::decay_t _p13_; \ + std::decay_t _p14_; \ + std::decay_t _p15_; \ + std::decay_t _p16_; \ + std::decay_t _p17_; \ + std::decay_t _p18_; \ + std::decay_t _p19_; \ + std::decay_t _p20_; \ + std::decay_t _p21_; \ + std::decay_t _p22_; \ + __attribute__((used, flatten)) void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_, _p13_, _p14_, _p15_, _p16_, _p17_, _p18_, _p19_, _p20_, _p21_, \ + _p22_); \ + } \ + } +#define make_kernel_functor_hip_24(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21) \ + struct make_kernel_name_hip(function_name, 22) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + std::decay_t _p13_; \ + std::decay_t _p14_; \ + std::decay_t _p15_; \ + std::decay_t _p16_; \ + std::decay_t _p17_; \ + std::decay_t _p18_; \ + std::decay_t _p19_; \ + std::decay_t _p20_; \ + std::decay_t _p21_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_, _p13_, _p14_, _p15_, _p16_, _p17_, _p18_, _p19_, _p20_, _p21_); \ + } \ + } +#define make_kernel_functor_hip_23(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20) \ + struct make_kernel_name_hip(function_name, 21) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + std::decay_t _p13_; \ + std::decay_t _p14_; \ + std::decay_t _p15_; \ + std::decay_t _p16_; \ + std::decay_t _p17_; \ + std::decay_t _p18_; \ + std::decay_t _p19_; \ + std::decay_t _p20_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_, _p13_, _p14_, _p15_, _p16_, _p17_, _p18_, _p19_, _p20_); \ + } \ + } +#define make_kernel_functor_hip_22(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19) \ + struct make_kernel_name_hip(function_name, 20) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + std::decay_t _p13_; \ + std::decay_t _p14_; \ + std::decay_t _p15_; \ + std::decay_t _p16_; \ + std::decay_t _p17_; \ + std::decay_t _p18_; \ + std::decay_t _p19_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_, _p13_, _p14_, _p15_, _p16_, _p17_, _p18_, _p19_); \ + } \ + } +#define make_kernel_functor_hip_21(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12, p13, p14, p15, p16, p17, p18) \ + struct make_kernel_name_hip(function_name, 19) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + std::decay_t _p13_; \ + std::decay_t _p14_; \ + std::decay_t _p15_; \ + std::decay_t _p16_; \ + std::decay_t _p17_; \ + std::decay_t _p18_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_, _p13_, _p14_, _p15_, _p16_, _p17_, _p18_); \ + } \ + } +#define make_kernel_functor_hip_20(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12, p13, p14, p15, p16, p17) \ + struct make_kernel_name_hip(function_name, 18) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + std::decay_t _p13_; \ + std::decay_t _p14_; \ + std::decay_t _p15_; \ + std::decay_t _p16_; \ + std::decay_t _p17_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_, _p13_, _p14_, _p15_, _p16_, _p17_); \ + } \ + } +#define make_kernel_functor_hip_19(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12, p13, p14, p15, p16) \ + struct make_kernel_name_hip(function_name, 17) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + std::decay_t _p13_; \ + std::decay_t _p14_; \ + std::decay_t _p15_; \ + std::decay_t _p16_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_, _p13_, _p14_, _p15_, _p16_); \ + } \ + } +#define make_kernel_functor_hip_18(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12, p13, p14, p15) \ + struct make_kernel_name_hip(function_name, 16) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + std::decay_t _p13_; \ + std::decay_t _p14_; \ + std::decay_t _p15_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_, _p13_, _p14_, _p15_); \ + } \ + } +#define make_kernel_functor_hip_17(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12, p13, p14) \ + struct make_kernel_name_hip(function_name, 15) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + std::decay_t _p13_; \ + std::decay_t _p14_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_, _p13_, _p14_); \ + } \ + } +#define make_kernel_functor_hip_16(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12, p13) \ + struct make_kernel_name_hip(function_name, 14) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + std::decay_t _p13_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_, _p13_); \ + } \ + } +#define make_kernel_functor_hip_15(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11, p12) \ + struct make_kernel_name_hip(function_name, 13) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + std::decay_t _p12_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_, \ + _p12_); \ + } \ + } +#define make_kernel_functor_hip_14(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10, p11) \ + struct make_kernel_name_hip(function_name, 12) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + std::decay_t _p11_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_, _p11_); \ + } \ + } +#define make_kernel_functor_hip_13(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9, p10) \ + struct make_kernel_name_hip(function_name, 11) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + std::decay_t _p10_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { \ + kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_, _p10_); \ + } \ + } +#define make_kernel_functor_hip_12(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8, \ + p9) \ + struct make_kernel_name_hip(function_name, 10) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + std::decay_t _p9_; \ + void operator()(const hc::tiled_index<3>&) const \ + [[hc]] { kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_, _p9_); } \ + } +#define make_kernel_functor_hip_11(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7, p8) \ + struct make_kernel_name_hip(function_name, 9) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + std::decay_t _p8_; \ + void operator()(const hc::tiled_index<3>&) const \ + [[hc]] { kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_, _p8_); } \ + } +#define make_kernel_functor_hip_10(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6, p7) \ + struct make_kernel_name_hip(function_name, 8) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + std::decay_t _p7_; \ + void operator()(const hc::tiled_index<3>&) const \ + [[hc]] { kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_, _p7_); } \ + } +#define make_kernel_functor_hip_9(function_name, kernel_name, p0, p1, p2, p3, p4, p5, p6) \ + struct make_kernel_name_hip(function_name, 7) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + std::decay_t _p6_; \ + void operator()(const hc::tiled_index<3>&) const \ + [[hc]] { kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_, _p6_); } \ + } +#define make_kernel_functor_hip_8(function_name, kernel_name, p0, p1, p2, p3, p4, p5) \ + struct make_kernel_name_hip(function_name, 6) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + std::decay_t _p5_; \ + void operator()(const hc::tiled_index<3>&) const \ + [[hc]] { kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_, _p5_); } \ + } +#define make_kernel_functor_hip_7(function_name, kernel_name, p0, p1, p2, p3, p4) \ + struct make_kernel_name_hip(function_name, 5) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + std::decay_t _p4_; \ + void operator()(const hc::tiled_index<3>&) const \ + [[hc]] { kernel_name(_p0_, _p1_, _p2_, _p3_, _p4_); } \ + } +#define make_kernel_functor_hip_6(function_name, kernel_name, p0, p1, p2, p3) \ + struct make_kernel_name_hip(function_name, 4) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + std::decay_t _p3_; \ + void operator()(const hc::tiled_index<3>&) const \ + [[hc]] { kernel_name(_p0_, _p1_, _p2_, _p3_); } \ + } +#define make_kernel_functor_hip_5(function_name, kernel_name, p0, p1, p2) \ + struct make_kernel_name_hip(function_name, 3) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + std::decay_t _p2_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { kernel_name(_p0_, _p1_, _p2_); } \ + } +#define make_kernel_functor_hip_4(function_name, kernel_name, p0, p1) \ + struct make_kernel_name_hip(function_name, 2) { \ + std::decay_t _p0_; \ + std::decay_t _p1_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { kernel_name(_p0_, _p1_); } \ + } +#define fofo(f, n) kernel_prefix_hip##f##kernel_suffix_hip##n +#define make_kernel_functor_hip_3(function_name, kernel_name, p0) \ + struct make_kernel_name_hip(function_name, 1) { \ + std::decay_t _p0_; \ + void operator()(const hc::tiled_index<3>&) const [[hc]] { kernel_name(_p0_); } \ + } +#define make_kernel_functor_hip_2(function_name, kernel_name) \ + struct make_kernel_name_hip(function_name, 0) { \ + void operator()(const hc::tiled_index<3>&)[[hc]] { return kernel_name(hipLaunchParm{}); } \ + } +#define make_kernel_functor_hip_1(...) +#define make_kernel_functor_hip_0(...) +#define make_kernel_functor_hip_(...) overload_macro_hip_(make_kernel_functor_hip_, __VA_ARGS__) + + +#define hipLaunchNamedKernelGGL(function_name, kernel_name, num_blocks, dim_blocks, \ + group_mem_bytes, stream, ...) \ + do { \ + make_kernel_functor_hip_(function_name, kernel_name, __VA_ARGS__) \ + hip_kernel_functor_impl_{__VA_ARGS__}; \ + hip_impl::grid_launch_hip_(num_blocks, dim_blocks, group_mem_bytes, stream, #kernel_name, \ + hip_kernel_functor_impl_); \ + } while (0) + +#define hipLaunchKernelGGL(kernel_name, num_blocks, dim_blocks, group_mem_bytes, stream, ...) \ + do { \ + hipLaunchNamedKernelGGL(unnamed, kernel_name, num_blocks, dim_blocks, group_mem_bytes, \ + stream, ##__VA_ARGS__); \ + } while (0) + +#define hipLaunchKernel(kernel_name, num_blocks, dim_blocks, group_mem_bytes, stream, ...) \ + do { \ + hipLaunchKernelGGL(kernel_name, num_blocks, dim_blocks, group_mem_bytes, stream, \ + hipLaunchParm{}, ##__VA_ARGS__); \ + } while (0) +} // namespace hip_impl diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/math_fwd.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/math_fwd.h new file mode 100644 index 0000000000000000000000000000000000000000..9951f8fc34d041a2b6873e1f9453483f1bd5e206 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/math_fwd.h @@ -0,0 +1,698 @@ +/* +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. +*/ + +#pragma once + +#if !defined(__HIPCC_RTC__) +#include "host_defines.h" +#include "amd_hip_vector_types.h" // For Native_vec_ +#endif + +#if defined(__cplusplus) + extern "C" { +#endif + +// DOT FUNCTIONS +#if defined(__clang__) && defined(__HIP__) +__device__ +__attribute__((const)) +int __ockl_sdot2( + HIP_vector_base::Native_vec_, + HIP_vector_base::Native_vec_, + int, bool); + +__device__ +__attribute__((const)) +unsigned int __ockl_udot2( + HIP_vector_base::Native_vec_, + HIP_vector_base::Native_vec_, + unsigned int, bool); + +__device__ +__attribute__((const)) +int __ockl_sdot4( + HIP_vector_base::Native_vec_, + HIP_vector_base::Native_vec_, + int, bool); + +__device__ +__attribute__((const)) +unsigned int __ockl_udot4( + HIP_vector_base::Native_vec_, + HIP_vector_base::Native_vec_, + unsigned int, bool); + +__device__ +__attribute__((const)) +int __ockl_sdot8(int, int, int, bool); + +__device__ +__attribute__((const)) +unsigned int __ockl_udot8(unsigned int, unsigned int, unsigned int, bool); +#endif + +#if !__CLANG_HIP_RUNTIME_WRAPPER_INCLUDED__ +// BEGIN FLOAT +__device__ +__attribute__((const)) +float __ocml_acos_f32(float); +__device__ +__attribute__((pure)) +float __ocml_acosh_f32(float); +__device__ +__attribute__((const)) +float __ocml_asin_f32(float); +__device__ +__attribute__((pure)) +float __ocml_asinh_f32(float); +__device__ +__attribute__((const)) +float __ocml_atan2_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_atan_f32(float); +__device__ +__attribute__((pure)) +float __ocml_atanh_f32(float); +__device__ +__attribute__((pure)) +float __ocml_cbrt_f32(float); +__device__ +__attribute__((const)) +float __ocml_ceil_f32(float); +__device__ +__attribute__((const)) +__device__ +float __ocml_copysign_f32(float, float); +__device__ +float __ocml_cos_f32(float); +__device__ +float __ocml_native_cos_f32(float); +__device__ +__attribute__((pure)) +__device__ +float __ocml_cosh_f32(float); +__device__ +float __ocml_cospi_f32(float); +__device__ +float __ocml_i0_f32(float); +__device__ +float __ocml_i1_f32(float); +__device__ +__attribute__((pure)) +float __ocml_erfc_f32(float); +__device__ +__attribute__((pure)) +float __ocml_erfcinv_f32(float); +__device__ +__attribute__((pure)) +float __ocml_erfcx_f32(float); +__device__ +__attribute__((pure)) +float __ocml_erf_f32(float); +__device__ +__attribute__((pure)) +float __ocml_erfinv_f32(float); +__device__ +__attribute__((pure)) +float __ocml_exp10_f32(float); +__device__ +__attribute__((pure)) +float __ocml_native_exp10_f32(float); +__device__ +__attribute__((pure)) +float __ocml_exp2_f32(float); +__device__ +__attribute__((pure)) +float __ocml_exp_f32(float); +__device__ +__attribute__((pure)) +float __ocml_native_exp_f32(float); +__device__ +__attribute__((pure)) +float __ocml_expm1_f32(float); +__device__ +__attribute__((const)) +float __ocml_fabs_f32(float); +__device__ +__attribute__((const)) +float __ocml_fdim_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_floor_f32(float); +__device__ +__attribute__((const)) +float __ocml_fma_f32(float, float, float); +__device__ +__attribute__((const)) +float __ocml_fmax_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_fmin_f32(float, float); +__device__ +__attribute__((const)) +__device__ +float __ocml_fmod_f32(float, float); +__device__ +float __ocml_frexp_f32(float, __attribute__((address_space(5))) int*); +__device__ +__attribute__((const)) +float __ocml_hypot_f32(float, float); +__device__ +__attribute__((const)) +int __ocml_ilogb_f32(float); +__device__ +__attribute__((const)) +int __ocml_isfinite_f32(float); +__device__ +__attribute__((const)) +int __ocml_isinf_f32(float); +__device__ +__attribute__((const)) +int __ocml_isnan_f32(float); +__device__ +float __ocml_j0_f32(float); +__device__ +float __ocml_j1_f32(float); +__device__ +__attribute__((const)) +float __ocml_ldexp_f32(float, int); +__device__ +float __ocml_lgamma_f32(float); +__device__ +__attribute__((pure)) +float __ocml_log10_f32(float); +__device__ +__attribute__((pure)) +float __ocml_native_log10_f32(float); +__device__ +__attribute__((pure)) +float __ocml_log1p_f32(float); +__device__ +__attribute__((pure)) +float __ocml_log2_f32(float); +__device__ +__attribute__((pure)) +float __ocml_native_log2_f32(float); +__device__ +__attribute__((const)) +float __ocml_logb_f32(float); +__device__ +__attribute__((pure)) +float __ocml_log_f32(float); +__device__ +__attribute__((pure)) +float __ocml_native_log_f32(float); +__device__ +float __ocml_modf_f32(float, __attribute__((address_space(5))) float*); +__device__ +__attribute__((const)) +float __ocml_nearbyint_f32(float); +__device__ +__attribute__((const)) +float __ocml_nextafter_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_len3_f32(float, float, float); +__device__ +__attribute__((const)) +float __ocml_len4_f32(float, float, float, float); +__device__ +__attribute__((pure)) +float __ocml_ncdf_f32(float); +__device__ +__attribute__((pure)) +float __ocml_ncdfinv_f32(float); +__device__ +__attribute__((pure)) +float __ocml_pow_f32(float, float); +__device__ +__attribute__((pure)) +float __ocml_pown_f32(float, int); +__device__ +__attribute__((pure)) +float __ocml_rcbrt_f32(float); +__device__ +__attribute__((const)) +float __ocml_remainder_f32(float, float); +__device__ +float __ocml_remquo_f32(float, float, __attribute__((address_space(5))) int*); +__device__ +__attribute__((const)) +float __ocml_rhypot_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_rint_f32(float); +__device__ +__attribute__((const)) +float __ocml_rlen3_f32(float, float, float); +__device__ +__attribute__((const)) +float __ocml_rlen4_f32(float, float, float, float); +__device__ +__attribute__((const)) +float __ocml_round_f32(float); +__device__ +__attribute__((pure)) +float __ocml_rsqrt_f32(float); +__device__ +__attribute__((const)) +float __ocml_scalb_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_scalbn_f32(float, int); +__device__ +__attribute__((const)) +int __ocml_signbit_f32(float); +__device__ +float __ocml_sincos_f32(float, __attribute__((address_space(5))) float*); +__device__ +float __ocml_sincospi_f32(float, __attribute__((address_space(5))) float*); +__device__ +float __ocml_sin_f32(float); +__device__ +float __ocml_native_sin_f32(float); +__device__ +__attribute__((pure)) +float __ocml_sinh_f32(float); +__device__ +float __ocml_sinpi_f32(float); +__device__ +__attribute__((const)) +float __ocml_sqrt_f32(float); +__device__ +__attribute__((const)) +float __ocml_native_sqrt_f32(float); +__device__ +float __ocml_tan_f32(float); +__device__ +__attribute__((pure)) +float __ocml_tanh_f32(float); +__device__ +float __ocml_tgamma_f32(float); +__device__ +__attribute__((const)) +float __ocml_trunc_f32(float); +__device__ +float __ocml_y0_f32(float); +__device__ +float __ocml_y1_f32(float); + +// BEGIN INTRINSICS +__device__ +__attribute__((const)) +float __ocml_add_rte_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_add_rtn_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_add_rtp_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_add_rtz_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_sub_rte_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_sub_rtn_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_sub_rtp_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_sub_rtz_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_mul_rte_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_mul_rtn_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_mul_rtp_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_mul_rtz_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_div_rte_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_div_rtn_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_div_rtp_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_div_rtz_f32(float, float); +__device__ +__attribute__((const)) +float __ocml_sqrt_rte_f32(float); +__device__ +__attribute__((const)) +float __ocml_sqrt_rtn_f32(float); +__device__ +__attribute__((const)) +float __ocml_sqrt_rtp_f32(float); +__device__ +__attribute__((const)) +float __ocml_sqrt_rtz_f32(float); +__device__ +__attribute__((const)) +float __ocml_fma_rte_f32(float, float, float); +__device__ +__attribute__((const)) +float __ocml_fma_rtn_f32(float, float, float); +__device__ +__attribute__((const)) +float __ocml_fma_rtp_f32(float, float, float); +__device__ +__attribute__((const)) +float __ocml_fma_rtz_f32(float, float, float); +// END INTRINSICS +// END FLOAT + +// BEGIN DOUBLE +__device__ +__attribute__((const)) +double __ocml_acos_f64(double); +__device__ +__attribute__((pure)) +double __ocml_acosh_f64(double); +__device__ +__attribute__((const)) +double __ocml_asin_f64(double); +__device__ +__attribute__((pure)) +double __ocml_asinh_f64(double); +__device__ +__attribute__((const)) +double __ocml_atan2_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_atan_f64(double); +__device__ +__attribute__((pure)) +double __ocml_atanh_f64(double); +__device__ +__attribute__((pure)) +double __ocml_cbrt_f64(double); +__device__ +__attribute__((const)) +double __ocml_ceil_f64(double); +__device__ +__attribute__((const)) +double __ocml_copysign_f64(double, double); +__device__ +double __ocml_cos_f64(double); +__device__ +__attribute__((pure)) +double __ocml_cosh_f64(double); +__device__ +double __ocml_cospi_f64(double); +__device__ +double __ocml_i0_f64(double); +__device__ +double __ocml_i1_f64(double); +__device__ +__attribute__((pure)) +double __ocml_erfc_f64(double); +__device__ +__attribute__((pure)) +double __ocml_erfcinv_f64(double); +__device__ +__attribute__((pure)) +double __ocml_erfcx_f64(double); +__device__ +__attribute__((pure)) +double __ocml_erf_f64(double); +__device__ +__attribute__((pure)) +double __ocml_erfinv_f64(double); +__device__ +__attribute__((pure)) +double __ocml_exp10_f64(double); +__device__ +__attribute__((pure)) +double __ocml_exp2_f64(double); +__device__ +__attribute__((pure)) +double __ocml_exp_f64(double); +__device__ +__attribute__((pure)) +double __ocml_expm1_f64(double); +__device__ +__attribute__((const)) +double __ocml_fabs_f64(double); +__device__ +__attribute__((const)) +double __ocml_fdim_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_floor_f64(double); +__device__ +__attribute__((const)) +double __ocml_fma_f64(double, double, double); +__device__ +__attribute__((const)) +double __ocml_fmax_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_fmin_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_fmod_f64(double, double); +__device__ +double __ocml_frexp_f64(double, __attribute__((address_space(5))) int*); +__device__ +__attribute__((const)) +double __ocml_hypot_f64(double, double); +__device__ +__attribute__((const)) +int __ocml_ilogb_f64(double); +__device__ +__attribute__((const)) +int __ocml_isfinite_f64(double); +__device__ +__attribute__((const)) +int __ocml_isinf_f64(double); +__device__ +__attribute__((const)) +int __ocml_isnan_f64(double); +__device__ +double __ocml_j0_f64(double); +__device__ +double __ocml_j1_f64(double); +__device__ +__attribute__((const)) +double __ocml_ldexp_f64(double, int); +__device__ +double __ocml_lgamma_f64(double); +__device__ +__attribute__((pure)) +double __ocml_log10_f64(double); +__device__ +__attribute__((pure)) +double __ocml_log1p_f64(double); +__device__ +__attribute__((pure)) +double __ocml_log2_f64(double); +__device__ +__attribute__((const)) +double __ocml_logb_f64(double); +__device__ +__attribute__((pure)) +double __ocml_log_f64(double); +__device__ +double __ocml_modf_f64(double, __attribute__((address_space(5))) double*); +__device__ +__attribute__((const)) +double __ocml_nearbyint_f64(double); +__device__ +__attribute__((const)) +double __ocml_nextafter_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_len3_f64(double, double, double); +__device__ +__attribute__((const)) +double __ocml_len4_f64(double, double, double, double); +__device__ +__attribute__((pure)) +double __ocml_ncdf_f64(double); +__device__ +__attribute__((pure)) +double __ocml_ncdfinv_f64(double); +__device__ +__attribute__((pure)) +double __ocml_pow_f64(double, double); +__device__ +__attribute__((pure)) +double __ocml_pown_f64(double, int); +__device__ +__attribute__((pure)) +double __ocml_rcbrt_f64(double); +__device__ +__attribute__((const)) +double __ocml_remainder_f64(double, double); +__device__ +double __ocml_remquo_f64( + double, double, __attribute__((address_space(5))) int*); +__device__ +__attribute__((const)) +double __ocml_rhypot_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_rint_f64(double); +__device__ +__attribute__((const)) +double __ocml_rlen3_f64(double, double, double); +__device__ +__attribute__((const)) +double __ocml_rlen4_f64(double, double, double, double); +__device__ +__attribute__((const)) +double __ocml_round_f64(double); +__device__ +__attribute__((pure)) +double __ocml_rsqrt_f64(double); +__device__ +__attribute__((const)) +double __ocml_scalb_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_scalbn_f64(double, int); +__device__ +__attribute__((const)) +int __ocml_signbit_f64(double); +__device__ +double __ocml_sincos_f64(double, __attribute__((address_space(5))) double*); +__device__ +double __ocml_sincospi_f64(double, __attribute__((address_space(5))) double*); +__device__ +double __ocml_sin_f64(double); +__device__ +__attribute__((pure)) +double __ocml_sinh_f64(double); +__device__ +double __ocml_sinpi_f64(double); +__device__ +__attribute__((const)) +double __ocml_sqrt_f64(double); +__device__ +double __ocml_tan_f64(double); +__device__ +__attribute__((pure)) +double __ocml_tanh_f64(double); +__device__ +double __ocml_tgamma_f64(double); +__device__ +__attribute__((const)) +double __ocml_trunc_f64(double); +__device__ +double __ocml_y0_f64(double); +__device__ +double __ocml_y1_f64(double); + +// BEGIN INTRINSICS +__device__ +__attribute__((const)) +double __ocml_add_rte_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_add_rtn_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_add_rtp_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_add_rtz_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_sub_rte_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_sub_rtn_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_sub_rtp_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_sub_rtz_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_mul_rte_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_mul_rtn_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_mul_rtp_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_mul_rtz_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_div_rte_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_div_rtn_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_div_rtp_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_div_rtz_f64(double, double); +__device__ +__attribute__((const)) +double __ocml_sqrt_rte_f64(double); +__device__ +__attribute__((const)) +double __ocml_sqrt_rtn_f64(double); +__device__ +__attribute__((const)) +double __ocml_sqrt_rtp_f64(double); +__device__ +__attribute__((const)) +double __ocml_sqrt_rtz_f64(double); +__device__ +__attribute__((const)) +double __ocml_fma_rte_f64(double, double, double); +__device__ +__attribute__((const)) +double __ocml_fma_rtn_f64(double, double, double); +__device__ +__attribute__((const)) +double __ocml_fma_rtp_f64(double, double, double); +__device__ +__attribute__((const)) +double __ocml_fma_rtz_f64(double, double, double); +// END INTRINSICS +// END DOUBLE + +#endif // !__CLANG_HIP_RUNTIME_WRAPPER_INCLUDED__ + +#if defined(__cplusplus) + } // extern "C" +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/ockl_image.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/ockl_image.h new file mode 100644 index 0000000000000000000000000000000000000000..50223add4ffc30f6cad200f9e3cd134e11996825 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/ockl_image.h @@ -0,0 +1,177 @@ +/* +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. +*/ + +#pragma once + +#if !defined(__HIPCC_RTC__) +#include +#endif + +extern "C" { + +#define ADDRESS_SPACE_CONSTANT __attribute__((address_space(4))) + +__device__ float4::Native_vec_ __ockl_image_load_1D(unsigned int ADDRESS_SPACE_CONSTANT*i, int c); + +__device__ float4::Native_vec_ __ockl_image_load_1Db(unsigned int ADDRESS_SPACE_CONSTANT*i, int c); + +__device__ float4::Native_vec_ __ockl_image_load_1Da(unsigned int ADDRESS_SPACE_CONSTANT*i, int2::Native_vec_ c); + +__device__ float4::Native_vec_ __ockl_image_load_2D(unsigned int ADDRESS_SPACE_CONSTANT*i, int2::Native_vec_ c); + +__device__ float4::Native_vec_ __ockl_image_load_2Da(unsigned int ADDRESS_SPACE_CONSTANT*i, int4::Native_vec_ c); + +__device__ float4::Native_vec_ __ockl_image_load_3D(unsigned int ADDRESS_SPACE_CONSTANT*i, int4::Native_vec_ c); + +__device__ float4::Native_vec_ __ockl_image_load_CM(unsigned int ADDRESS_SPACE_CONSTANT*i, int2::Native_vec_ c, int f); + +__device__ float4::Native_vec_ __ockl_image_load_CMa(unsigned int ADDRESS_SPACE_CONSTANT*i, int4::Native_vec_ c, int f); + +__device__ float4::Native_vec_ __ockl_image_load_lod_1D(unsigned int ADDRESS_SPACE_CONSTANT*i, int c, int l); + +__device__ float4::Native_vec_ __ockl_image_load_lod_1Da(unsigned int ADDRESS_SPACE_CONSTANT*i, int2::Native_vec_ c, int l); + +__device__ float4::Native_vec_ __ockl_image_load_lod_2D(unsigned int ADDRESS_SPACE_CONSTANT*i, int2::Native_vec_ c, int l); + +__device__ float4::Native_vec_ __ockl_image_load_lod_2Da(unsigned int ADDRESS_SPACE_CONSTANT*i, int4::Native_vec_ c, int l); + +__device__ float4::Native_vec_ __ockl_image_load_lod_3D(unsigned int ADDRESS_SPACE_CONSTANT*i, int4::Native_vec_ c, int l); + +__device__ float4::Native_vec_ __ockl_image_load_lod_CM(unsigned int ADDRESS_SPACE_CONSTANT*i, int2::Native_vec_ c, int f, int l); + +__device__ float4::Native_vec_ __ockl_image_load_lod_CMa(unsigned int ADDRESS_SPACE_CONSTANT*i, int4::Native_vec_ c, int f, int l); + +__device__ void __ockl_image_store_1D(unsigned int ADDRESS_SPACE_CONSTANT*i, int c, float4::Native_vec_ p); + +__device__ void __ockl_image_store_1Da(unsigned int ADDRESS_SPACE_CONSTANT*i, int2::Native_vec_ c, float4::Native_vec_ p); + +__device__ void __ockl_image_store_2D(unsigned int ADDRESS_SPACE_CONSTANT*i, int2::Native_vec_ c, float4::Native_vec_ p); + +__device__ void __ockl_image_store_2Da(unsigned int ADDRESS_SPACE_CONSTANT*i, int4::Native_vec_ c, float4::Native_vec_ p); + +__device__ void __ockl_image_store_3D(unsigned int ADDRESS_SPACE_CONSTANT*i, int4::Native_vec_ c, float4::Native_vec_ p); + +__device__ void __ockl_image_store_CM(unsigned int ADDRESS_SPACE_CONSTANT*i, int2::Native_vec_ c, int f, float4::Native_vec_ p); + +__device__ void __ockl_image_store_CMa(unsigned int ADDRESS_SPACE_CONSTANT*i, int4::Native_vec_ c, int f, float4::Native_vec_ p); + +__device__ void __ockl_image_store_lod_1D(unsigned int ADDRESS_SPACE_CONSTANT*i, int c, int l, float4::Native_vec_ p); + +__device__ void __ockl_image_store_lod_1Da(unsigned int ADDRESS_SPACE_CONSTANT*i, int2::Native_vec_ c, int l, float4::Native_vec_ p); + +__device__ void __ockl_image_store_lod_2D(unsigned int ADDRESS_SPACE_CONSTANT*i, int2::Native_vec_ c, int l, float4::Native_vec_ p); + +__device__ void __ockl_image_store_lod_2Da(unsigned int ADDRESS_SPACE_CONSTANT*i, int4::Native_vec_ c, int l, float4::Native_vec_ p); + +__device__ void __ockl_image_store_lod_3D(unsigned int ADDRESS_SPACE_CONSTANT*i, int4::Native_vec_ c, int l, float4::Native_vec_ p); + +__device__ void __ockl_image_store_lod_CM(unsigned int ADDRESS_SPACE_CONSTANT*i, int2::Native_vec_ c, int f, int l, float4::Native_vec_ p); + +__device__ void __ockl_image_store_lod_CMa(unsigned int ADDRESS_SPACE_CONSTANT*i, int4::Native_vec_ c, int f, int l, float4::Native_vec_ p); + +__device__ float4::Native_vec_ __ockl_image_sample_1D(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float c); + +__device__ float4::Native_vec_ __ockl_image_sample_1Da(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float2::Native_vec_ c); + +__device__ float4::Native_vec_ __ockl_image_sample_2D(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float2::Native_vec_ c); + +__device__ float4::Native_vec_ __ockl_image_sample_2Da(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float4::Native_vec_ c); + +__device__ float4::Native_vec_ __ockl_image_sample_3D(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float4::Native_vec_ c); + +__device__ float4::Native_vec_ __ockl_image_sample_CM(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float4::Native_vec_ c); + +__device__ float4::Native_vec_ __ockl_image_sample_CMa(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float4::Native_vec_ c); + +__device__ float4::Native_vec_ __ockl_image_sample_grad_1D(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float c, float dx, float dy); + +__device__ float4::Native_vec_ __ockl_image_sample_grad_1Da(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float2::Native_vec_ c, float dx, float dy); + +__device__ float4::Native_vec_ __ockl_image_sample_grad_2D(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float2::Native_vec_ c, float2::Native_vec_ dx, float2::Native_vec_ dy); + +__device__ float4::Native_vec_ __ockl_image_sample_grad_2Da(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float4::Native_vec_ c, float2::Native_vec_ dx, float2::Native_vec_ dy); + +__device__ float4::Native_vec_ __ockl_image_sample_grad_3D(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float4::Native_vec_ c, float4::Native_vec_ dx, float4::Native_vec_ dy); + +__device__ float4::Native_vec_ __ockl_image_sample_lod_1D(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float c, float l); + +__device__ float4::Native_vec_ __ockl_image_sample_lod_1Da(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float2::Native_vec_ c, float l); + +__device__ float4::Native_vec_ __ockl_image_sample_lod_2D(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float2::Native_vec_ c, float l); + +__device__ float4::Native_vec_ __ockl_image_sample_lod_2Da(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float4::Native_vec_ c, float l); + +__device__ float4::Native_vec_ __ockl_image_sample_lod_3D(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float4::Native_vec_ c, float l); + +__device__ float4::Native_vec_ __ockl_image_sample_lod_CM(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float4::Native_vec_ c, float l); + +__device__ float4::Native_vec_ __ockl_image_sample_lod_CMa(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float4::Native_vec_ c, float l); + +__device__ float4::Native_vec_ __ockl_image_gather4r_2D(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float2::Native_vec_ c); + +__device__ float4::Native_vec_ __ockl_image_gather4g_2D(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float2::Native_vec_ c); + +__device__ float4::Native_vec_ __ockl_image_gather4b_2D(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float2::Native_vec_ c); + +__device__ float4::Native_vec_ __ockl_image_gather4a_2D(unsigned int ADDRESS_SPACE_CONSTANT*i, unsigned int ADDRESS_SPACE_CONSTANT*s, float2::Native_vec_ c); + +__device__ int __ockl_image_channel_data_type_1D(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_data_type_1Da(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_data_type_1Db(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_data_type_2D(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_data_type_2Da(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_data_type_2Dad(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_data_type_2Dd(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_data_type_3D(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_data_type_CM(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_data_type_CMa(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_order_1D(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_order_1Da(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_order_1Db(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_order_2D(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_order_2Da(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_order_2Dad(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_order_2Dd(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_order_3D(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_order_CM(unsigned int ADDRESS_SPACE_CONSTANT* i); + +__device__ int __ockl_image_channel_order_CMa(unsigned int ADDRESS_SPACE_CONSTANT* i); + +} diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/program_state.hpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/program_state.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e06504f71174002e571e5e0e8ee7f815553b04be --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/program_state.hpp @@ -0,0 +1,107 @@ +/* +Copyright (c) 2015 - 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. +*/ + +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +#include + +struct ihipModuleSymbol_t; +using hipFunction_t = ihipModuleSymbol_t*; + +namespace hip_impl { + +// This section contains internal APIs that +// needs to be exported +#ifdef __GNUC__ +#pragma GCC visibility push (default) +#endif + +struct kernarg_impl; +class kernarg { +public: + kernarg(); + kernarg(kernarg&&); + ~kernarg(); + std::uint8_t* data(); + std::size_t size(); + void reserve(std::size_t); + void resize(std::size_t); +private: + kernarg_impl* impl; +}; + +class kernargs_size_align; +class program_state_impl; +class program_state { +public: + program_state(); + ~program_state(); + program_state(const program_state&) = delete; + + hipFunction_t kernel_descriptor(std::uintptr_t, + hsa_agent_t); + + kernargs_size_align get_kernargs_size_align(std::uintptr_t); + hsa_executable_t load_executable(const char*, const size_t, + hsa_executable_t, + hsa_agent_t); + hsa_executable_t load_executable_no_copy(const char*, const size_t, + hsa_executable_t, + hsa_agent_t); + + void* global_addr_by_name(const char* name); + +private: + friend class agent_globals_impl; + program_state_impl* impl; +}; + +class kernargs_size_align { +public: + std::size_t size(std::size_t n) const; + std::size_t alignment(std::size_t n) const; + const void* getHandle() const {return handle;}; +private: + const void* handle; + friend kernargs_size_align program_state::get_kernargs_size_align(std::uintptr_t); +}; + +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + +inline +__attribute__((visibility("hidden"))) +program_state& get_program_state() { + static program_state ps; + return ps; +} +} // Namespace hip_impl. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/texture_fetch_functions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/texture_fetch_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..c4dcbe78d82d533427d5b10e8c864710ddb10ede --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/texture_fetch_functions.h @@ -0,0 +1,491 @@ +/* +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. +*/ + +#pragma once + +#if defined(__cplusplus) + +#if !defined(__HIPCC_RTC__) +#include +#include +#include +#include +#endif // !defined(__HIPCC_RTC__) + +#define TEXTURE_PARAMETERS_INIT \ + unsigned int ADDRESS_SPACE_CONSTANT* i = (unsigned int ADDRESS_SPACE_CONSTANT*)t.textureObject; \ + unsigned int ADDRESS_SPACE_CONSTANT* s = i + HIP_SAMPLER_OBJECT_OFFSET_DWORD; + +template +struct __hip_is_tex_surf_scalar_channel_type +{ + static constexpr bool value = + std::is_same::value || + std::is_same::value || + std::is_same::value || + std::is_same::value || + std::is_same::value || + std::is_same::value || + std::is_same::value; +}; + +template +struct __hip_is_tex_surf_channel_type +{ + static constexpr bool value = + __hip_is_tex_surf_scalar_channel_type::value; +}; + +template< + typename T, + unsigned int rank> +struct __hip_is_tex_surf_channel_type> +{ + static constexpr bool value = + __hip_is_tex_surf_scalar_channel_type::value && + ((rank == 1) || + (rank == 2) || + (rank == 4)); +}; + +template +struct __hip_is_tex_normalized_channel_type +{ + static constexpr bool value = + std::is_same::value || + std::is_same::value || + std::is_same::value || + std::is_same::value; +}; + +template< + typename T, + unsigned int rank> +struct __hip_is_tex_normalized_channel_type> +{ + static constexpr bool value = + __hip_is_tex_normalized_channel_type::value && + ((rank == 1) || + (rank == 2) || + (rank == 4)); +}; + +template < + typename T, + hipTextureReadMode readMode, + typename Enable = void> +struct __hip_tex_ret +{ + static_assert(std::is_same::value, "Invalid channel type!"); +}; + +/* + * Map from device function return U to scalar texture type T + */ +template +__forceinline__ __device__ +typename std::enable_if< + __hip_is_tex_surf_scalar_channel_type::value, const T>::type +__hipMapFrom(const U &u) { + if constexpr (sizeof(T) < sizeof(float)) { + union { + U u; + int i; + } d = { u }; + return static_cast(d.i); + } else { // sizeof(T) == sizeof(float) + union { + U u; + T t; + } d = { u }; + return d.t; + } +} + +/* + * Map from device function return U to vector texture type T + */ +template +__forceinline__ __device__ +typename std::enable_if< + __hip_is_tex_surf_scalar_channel_type::value, const T>::type +__hipMapFrom(const U &u) { + if constexpr (sizeof(typename T::value_type) < sizeof(float)) { + union { + U u; + int4 i4; + } d = { u }; + return __hipMapVector(d.i4); + } else { // sizeof(typename T::value_type) == sizeof(float) + union { + U u; + T t; + } d = { u }; + return d.t; + } +} + +/* + * Map from scalar texture type T to device function input U + */ +template +__forceinline__ __device__ +typename std::enable_if< +__hip_is_tex_surf_scalar_channel_type::value, const U>::type +__hipMapTo(const T &t) { + if constexpr (sizeof(T) < sizeof(float)) { + union { + U u; + int i; + } d = { 0 }; + d.i = static_cast(t); + return d.u; + } else { // sizeof(T) == sizeof(float) + union { + U u; + T t; + } d = { 0 }; + d.t = t; + return d.u; + } +} + +/* + * Map from vector texture type T to device function input U + */ +template +__forceinline__ __device__ +typename std::enable_if< + __hip_is_tex_surf_scalar_channel_type::value, const U>::type +__hipMapTo(const T &t) { + if constexpr (sizeof(typename T::value_type) < sizeof(float)) { + union { + U u; + int4 i4; + } d = { 0 }; + d.i4 = __hipMapVector(t); + return d.u; + } else { // sizeof(typename T::value_type) == sizeof(float) + union { + U u; + T t; + } d = { 0 }; + d.t = t; + return d.u; + } +} + +template < + typename T, + hipTextureReadMode readMode> +using __hip_tex_ret_t = typename __hip_tex_ret::type; + +template +struct __hip_tex_ret< + T, + hipReadModeElementType, + typename std::enable_if<__hip_is_tex_surf_channel_type::value, bool>::type> +{ + using type = T; +}; + +template< + typename T, + unsigned int rank> +struct __hip_tex_ret< + HIP_vector_type, + hipReadModeElementType, + typename std::enable_if<__hip_is_tex_surf_channel_type>::value, bool>::type> +{ + using type = HIP_vector_type<__hip_tex_ret_t, rank>; +}; + +template +struct __hip_tex_ret< + T, + hipReadModeNormalizedFloat, + typename std::enable_if<__hip_is_tex_normalized_channel_type::value, bool>::type> +{ + using type = float; +}; + +template< + typename T, + unsigned int rank> +struct __hip_tex_ret< + HIP_vector_type, + hipReadModeNormalizedFloat, + typename std::enable_if<__hip_is_tex_normalized_channel_type>::value, bool>::type> +{ + using type = HIP_vector_type<__hip_tex_ret_t, rank>; +}; + + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex1Dfetch(texture t, int x) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_load_1Db(i, x); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex1D(texture t, float x) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_1D(i, s, x); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex2D(texture t, float x, float y) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_2D(i, s, float2(x, y).data); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex1DLayered(texture t, float x, int layer) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_1Da(i, s, float2(x, layer).data); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex2DLayered(texture t, float x, float y, int layer) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_2Da(i, s, float4(x, y, layer, 0.0f).data); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex3D(texture t, float x, float y, float z) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_3D(i, s, float4(x, y, z, 0.0f).data); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t texCubemap(texture t, float x, float y, float z) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_CM(i, s, float4(x, y, z, 0.0f).data); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex1DLod(texture t, float x, float level) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_lod_1D(i, s, x, level); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex2DLod(texture t, float x, float y, float level) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_lod_2D(i, s, float2(x, y).data, level); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex1DLayeredLod(texture t, float x, int layer, float level) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_lod_1Da(i, s, float2(x, layer).data, level); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex2DLayeredLod(texture t, float x, float y, int layer, float level) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_lod_2Da(i, s, float4(x, y, layer, 0.0f).data, level); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex3DLod(texture t, float x, float y, float z, float level) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_lod_3D(i, s, float4(x, y, z, 0.0f).data, level); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t texCubemapLod(texture t, float x, float y, float z, float level) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_lod_CM(i, s, float4(x, y, z, 0.0f).data, level); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t texCubemapLayered(texture t, float x, float y, float z, int layer) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_CMa(i, s, float4(x, y, z, layer).data); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t texCubemapLayeredLod(texture t, float x, float y, float z, int layer, float level) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_lod_CMa(i, s, float4(x, y, z, layer).data, level); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t texCubemapGrad(texture t, float x, float y, float z, float4 dPdx, float4 dPdy) +{ + TEXTURE_PARAMETERS_INIT; + // TODO missing in device libs. + // auto tmp = __ockl_image_sample_grad_CM(i, s, float4(x, y, z, 0.0f).data, float4(dPdx.x, dPdx.y, dPdx.z, 0.0f).data, float4(dPdy.x, dPdy.y, dPdy.z, 0.0f).data); + // return __hipMapFrom<__hip_tex_ret_t>(tmp); + return {}; +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t texCubemapLayeredGrad(texture t, float x, float y, float z, int layer, float4 dPdx, float4 dPdy) +{ + TEXTURE_PARAMETERS_INIT; + // TODO missing in device libs. + // auto tmp = __ockl_image_sample_grad_CMa(i, s, float4(x, y, z, layer).data, float4(dPdx.x, dPdx.y, dPdx.z, 0.0f).data, float4(dPdy.x, dPdy.y, dPdy.z, 0.0f).data); + // return __hipMapFrom<__hip_tex_ret_t>(tmp); + return {}; +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex1DGrad(texture t, float x, float dPdx, float dPdy) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_grad_1D(i, s, x, dPdx, dPdy); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex2DGrad(texture t, float x, float y, float2 dPdx, float2 dPdy) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_grad_2D(i, s, float2(x, y).data, float2(dPdx.x, dPdx.y).data, float2(dPdy.x, dPdy.y).data); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex1DLayeredGrad(texture t, float x, int layer, float dPdx, float dPdy) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_grad_1Da(i, s, float2(x, layer).data, dPdx, dPdy); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex2DLayeredGrad(texture t, float x, float y, int layer, float2 dPdx, float2 dPdy) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_grad_2Da(i, s, float4(x, y, layer, 0.0f).data, float2(dPdx.x, dPdx.y).data, float2(dPdy.x, dPdy.y).data); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex_ret_t tex3DGrad(texture t, float x, float y, float z, float4 dPdx, float4 dPdy) +{ + TEXTURE_PARAMETERS_INIT; + auto tmp = __ockl_image_sample_grad_3D(i, s, float4(x, y, z, 0.0f).data, float4(dPdx.x, dPdx.y, dPdx.z, 0.0f).data, float4(dPdy.x, dPdy.y, dPdy.z, 0.0f).data); + return __hipMapFrom<__hip_tex_ret_t>(tmp); +} + +template < + typename T, + hipTextureReadMode readMode, + typename Enable = void> +struct __hip_tex2dgather_ret +{ + static_assert(std::is_same::value, "Invalid channel type!"); +}; + +template < + typename T, + hipTextureReadMode readMode> +using __hip_tex2dgather_ret_t = typename __hip_tex2dgather_ret::type; + +template +struct __hip_tex2dgather_ret< + T, + hipReadModeElementType, + typename std::enable_if<__hip_is_tex_surf_channel_type::value, bool>::type> +{ + using type = HIP_vector_type; +}; + +template< + typename T, + unsigned int rank> +struct __hip_tex2dgather_ret< + HIP_vector_type, + hipReadModeElementType, + typename std::enable_if<__hip_is_tex_surf_channel_type>::value, bool>::type> +{ + using type = HIP_vector_type; +}; + +template +struct __hip_tex2dgather_ret< + T, + hipReadModeNormalizedFloat, + typename std::enable_if<__hip_is_tex_normalized_channel_type::value, bool>::type> +{ + using type = float4; +}; + +template +static __forceinline__ __device__ __hip_img_chk__ __hip_tex2dgather_ret_t tex2Dgather(texture t, float x, float y, int comp=0) +{ + TEXTURE_PARAMETERS_INIT; + switch (comp) { + case 1: { + auto tmp = __ockl_image_gather4g_2D(i, s, float2(x, y).data); + return __hipMapFrom<__hip_tex2dgather_ret_t>(tmp); + } + case 2: { + auto tmp = __ockl_image_gather4b_2D(i, s, float2(x, y).data); + return __hipMapFrom<__hip_tex2dgather_ret_t>(tmp); + } + case 3: { + auto tmp = __ockl_image_gather4a_2D(i, s, float2(x, y).data); + return __hipMapFrom<__hip_tex2dgather_ret_t>(tmp); + } + default: { + auto tmp = __ockl_image_gather4r_2D(i, s, float2(x, y).data); + return __hipMapFrom<__hip_tex2dgather_ret_t>(tmp); + } + } + return {}; +} + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/texture_indirect_functions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/texture_indirect_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..1e435018dfae6c23e6026ae90a18842f65a48261 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/texture_indirect_functions.h @@ -0,0 +1,478 @@ +/* +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. +*/ + +#pragma once + +#if defined(__cplusplus) + +#if !defined(__HIPCC_RTC__) +#include +#include +#include +#include +#include +#endif // !defined(__HIPCC_RTC__) + +#define TEXTURE_OBJECT_PARAMETERS_INIT \ + unsigned int ADDRESS_SPACE_CONSTANT* i = (unsigned int ADDRESS_SPACE_CONSTANT*)textureObject; \ + unsigned int ADDRESS_SPACE_CONSTANT* s = i + HIP_SAMPLER_OBJECT_OFFSET_DWORD; + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex1Dfetch(hipTextureObject_t textureObject, int x) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_load_1Db(i, x); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex1Dfetch(T *ptr, hipTextureObject_t textureObject, int x) +{ + *ptr = tex1Dfetch(textureObject, x); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex1D(hipTextureObject_t textureObject, float x) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_1D(i, s, x); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex1D(T *ptr, hipTextureObject_t textureObject, float x) +{ + *ptr = tex1D(textureObject, x); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex2D(hipTextureObject_t textureObject, float x, float y) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_2D(i, s, float2(x, y).data); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex2D(T *ptr, hipTextureObject_t textureObject, float x, float y) +{ + *ptr = tex2D(textureObject, x, y); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex3D(hipTextureObject_t textureObject, float x, float y, float z) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_3D(i, s, float4(x, y, z, 0.0f).data); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex3D(T *ptr, hipTextureObject_t textureObject, float x, float y, float z) +{ + *ptr = tex3D(textureObject, x, y, z); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex1DLayered(hipTextureObject_t textureObject, float x, int layer) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_1Da(i, s, float2(x, layer).data); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex1DLayered(T *ptr, hipTextureObject_t textureObject, float x, int layer) +{ + *ptr = tex1DLayered(textureObject, x, layer); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex2DLayered(hipTextureObject_t textureObject, float x, float y, int layer) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_2Da(i, s, float4(x, y, layer, 0.0f).data); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex2DLayered(T *ptr, hipTextureObject_t textureObject, float x, float y, int layer) +{ + *ptr = tex1DLayered(textureObject, x, y, layer); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T texCubemap(hipTextureObject_t textureObject, float x, float y, float z) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_CM(i, s, float4(x, y, z, 0.0f).data); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void texCubemap(T *ptr, hipTextureObject_t textureObject, float x, float y, float z) +{ + *ptr = texCubemap(textureObject, x, y, z); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T texCubemapLayered(hipTextureObject_t textureObject, float x, float y, float z, int layer) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_CMa(i, s, float4(x, y, z, layer).data); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void texCubemapLayered(T *ptr, hipTextureObject_t textureObject, float x, float y, float z, int layer) +{ + *ptr = texCubemapLayered(textureObject, x, y, z, layer); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex2Dgather(hipTextureObject_t textureObject, float x, float y, int comp = 0) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + switch (comp) { + case 1: { + auto tmp = __ockl_image_gather4r_2D(i, s, float2(x, y).data); + return __hipMapFrom(tmp); + break; + } + case 2: { + auto tmp = __ockl_image_gather4g_2D(i, s, float2(x, y).data); + return __hipMapFrom(tmp); + break; + } + case 3: { + auto tmp = __ockl_image_gather4b_2D(i, s, float2(x, y).data); + return __hipMapFrom(tmp); + break; + } + default: { + auto tmp = __ockl_image_gather4a_2D(i, s, float2(x, y).data); + return __hipMapFrom(tmp); + break; + } + } + return {}; +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex2Dgather(T *ptr, hipTextureObject_t textureObject, float x, float y, int comp = 0) +{ + *ptr = texCubemapLayered(textureObject, x, y, comp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex1DLod(hipTextureObject_t textureObject, float x, float level) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_lod_1D(i, s, x, level); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex1DLod(T *ptr, hipTextureObject_t textureObject, float x, float level) +{ + *ptr = tex1DLod(textureObject, x, level); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex2DLod(hipTextureObject_t textureObject, float x, float y, float level) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_lod_2D(i, s, float2(x, y).data, level); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex2DLod(T *ptr, hipTextureObject_t textureObject, float x, float y, float level) +{ + *ptr = tex2DLod(textureObject, x, y, level); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex3DLod(hipTextureObject_t textureObject, float x, float y, float z, float level) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_lod_3D(i, s, float4(x, y, z, 0.0f).data, level); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex3DLod(T *ptr, hipTextureObject_t textureObject, float x, float y, float z, float level) +{ + *ptr = tex3DLod(textureObject, x, y, z, level); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex1DLayeredLod(hipTextureObject_t textureObject, float x, int layer, float level) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_1Da(i, s, float2(x, layer).data); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex1DLayeredLod(T *ptr, hipTextureObject_t textureObject, float x, int layer, float level) +{ + *ptr = tex1DLayeredLod(textureObject, x, layer, level); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex2DLayeredLod(hipTextureObject_t textureObject, float x, float y, int layer, float level) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_2Da(i, s, float4(x, y, layer, 0.0f).data); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex2DLayeredLod(T *ptr, hipTextureObject_t textureObject, float x, float y, int layer, float level) +{ + *ptr = tex2DLayeredLod(textureObject, x, y, layer, level); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T texCubemapLod(hipTextureObject_t textureObject, float x, float y, float z, float level) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_lod_CM(i, s, float4(x, y, z, 0.0f).data, level); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void texCubemapLod(T *ptr, hipTextureObject_t textureObject, float x, float y, float z, float level) +{ + *ptr = texCubemapLod(textureObject, x, y, z, level); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T texCubemapGrad(hipTextureObject_t textureObject, float x, float y, float z, float4 dPdx, float4 dPdy) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + // TODO missing in device libs. + // auto tmp = __ockl_image_sample_grad_CM(i, s, float4(x, y, z, 0.0f).data, float4(dPdx.x, dPdx.y, dPdx.z, 0.0f).data, float4(dPdy.x, dPdy.y, dPdy.z, 0.0f).data); + // return __hipMapFrom(tmp); + return {}; +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void texCubemapGrad(T *ptr, hipTextureObject_t textureObject, float x, float y, float z, float4 dPdx, float4 dPdy) +{ + *ptr = texCubemapGrad(textureObject, x, y, z, dPdx, dPdy); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T texCubemapLayeredLod(hipTextureObject_t textureObject, float x, float y, float z, int layer, float level) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_lod_CMa(i, s, float4(x, y, z, layer).data, level); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void texCubemapLayeredLod(T *ptr, hipTextureObject_t textureObject, float x, float y, float z, int layer, float level) +{ + *ptr = texCubemapLayeredLod(textureObject, x, y, z, layer, level); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex1DGrad(hipTextureObject_t textureObject, float x, float dPdx, float dPdy) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_grad_1D(i, s, x, dPdx, dPdy); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex1DGrad(T *ptr, hipTextureObject_t textureObject, float x, float dPdx, float dPdy) +{ + *ptr = tex1DGrad(textureObject, x, dPdx, dPdy); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex2DGrad(hipTextureObject_t textureObject, float x, float y, float2 dPdx, float2 dPdy) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_grad_2D(i, s, float2(x, y).data, float2(dPdx.x, dPdx.y).data, float2(dPdy.x, dPdy.y).data); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex2DGrad(T *ptr, hipTextureObject_t textureObject, float x, float y, float2 dPdx, float2 dPdy) +{ + *ptr = tex2DGrad(textureObject, x, y, dPdx, dPdy); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex3DGrad(hipTextureObject_t textureObject, float x, float y, float z, float4 dPdx, float4 dPdy) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_grad_3D(i, s, float4(x, y, z, 0.0f).data, float4(dPdx.x, dPdx.y, dPdx.z, 0.0f).data, float4(dPdy.x, dPdy.y, dPdy.z, 0.0f).data); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex3DGrad(T *ptr, hipTextureObject_t textureObject, float x, float y, float z, float4 dPdx, float4 dPdy) +{ + *ptr = tex3DGrad(textureObject, x, y, z, dPdx, dPdy); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex1DLayeredGrad(hipTextureObject_t textureObject, float x, int layer, float dPdx, float dPdy) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_grad_1Da(i, s, float2(x, layer).data, dPdx, dPdy); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex1DLayeredGrad(T *ptr, hipTextureObject_t textureObject, float x, int layer, float dPdx, float dPdy) +{ + *ptr = tex1DLayeredGrad(textureObject, x, layer, dPdx, dPdy); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T tex2DLayeredGrad(hipTextureObject_t textureObject, float x, float y, int layer, float2 dPdx, float2 dPdy) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + auto tmp = __ockl_image_sample_grad_2Da(i, s, float4(x, y, layer, 0.0f).data, float2(dPdx.x, dPdx.y).data, float2(dPdy.x, dPdy.y).data); + return __hipMapFrom(tmp); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void tex2DLayeredGrad(T *ptr, hipTextureObject_t textureObject, float x, float y, int layer, float2 dPdx, float2 dPdy) +{ + *ptr = tex2DLayeredGrad(textureObject, x, y, layer, dPdx, dPdy); +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ T texCubemapLayeredGrad(hipTextureObject_t textureObject, float x, float y, float z, int layer, float4 dPdx, float4 dPdy) +{ + TEXTURE_OBJECT_PARAMETERS_INIT + // TODO missing in device libs. + // auto tmp = __ockl_image_sample_grad_CMa(i, s, float4(x, y, z, layer).data, float4(dPdx.x, dPdx.y, dPdx.z, 0.0f).data, float4(dPdy.x, dPdy.y, dPdy.z, 0.0f).data); + // return __hipMapFrom(tmp); + return {}; +} + +template < + typename T, + typename std::enable_if<__hip_is_tex_surf_channel_type::value>::type* = nullptr> +static __device__ __hip_img_chk__ void texCubemapLayeredGrad(T *ptr, hipTextureObject_t textureObject, float x, float y, float z, int layer, float4 dPdx, float4 dPdy) +{ + *ptr = texCubemapLayeredGrad(textureObject, x, y, z, layer, dPdx, dPdy); +} + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/channel_descriptor.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/channel_descriptor.h new file mode 100644 index 0000000000000000000000000000000000000000..d8b7d7d796bb2cd5cc704820ee705cdb142c0dad --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/channel_descriptor.h @@ -0,0 +1,39 @@ +/* +Copyright (c) 2015 - 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_CHANNEL_DESCRIPTOR_H +#define HIP_INCLUDE_HIP_CHANNEL_DESCRIPTOR_H + +// Some standard header files, these are included by hc.hpp and so want to make them avail on both +// paths to provide a consistent include env and avoid "missing symbol" errors that only appears +// on NVCC path: + + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +#include +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/device_functions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/device_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..9a86171e45acbf896b4c44dd5fb7447285ffc957 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/device_functions.h @@ -0,0 +1,38 @@ +/* +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_DEVICE_FUNCTIONS_H +#define HIP_INCLUDE_HIP_DEVICE_FUNCTIONS_H + +#if !defined(__HIPCC_RTC__) +#include +#endif + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +#include +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/driver_types.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/driver_types.h new file mode 100644 index 0000000000000000000000000000000000000000..3551f9d5961048a2f79feaa33dcc46cd2166bf53 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/driver_types.h @@ -0,0 +1,468 @@ +/* +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_DRIVER_TYPES_H +#define HIP_INCLUDE_HIP_DRIVER_TYPES_H + +#if !defined(__HIPCC_RTC__) +#include +#endif + +#if !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include "driver_types.h" +#elif defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) + +#if !defined(__HIPCC_RTC__) +#ifndef __cplusplus +#include +#endif +#endif // !defined(__HIPCC_RTC__) +typedef void* hipDeviceptr_t; +typedef enum hipChannelFormatKind { + hipChannelFormatKindSigned = 0, + hipChannelFormatKindUnsigned = 1, + hipChannelFormatKindFloat = 2, + hipChannelFormatKindNone = 3 +}hipChannelFormatKind; +typedef struct hipChannelFormatDesc { + int x; + int y; + int z; + int w; + enum hipChannelFormatKind f; +}hipChannelFormatDesc; +#define HIP_TRSA_OVERRIDE_FORMAT 0x01 +#define HIP_TRSF_READ_AS_INTEGER 0x01 +#define HIP_TRSF_NORMALIZED_COORDINATES 0x02 +#define HIP_TRSF_SRGB 0x10 + +typedef struct hipArray* hipArray_t; +typedef const struct hipArray* hipArray_const_t; +typedef enum hipArray_Format { + HIP_AD_FORMAT_UNSIGNED_INT8 = 0x01, + HIP_AD_FORMAT_UNSIGNED_INT16 = 0x02, + HIP_AD_FORMAT_UNSIGNED_INT32 = 0x03, + HIP_AD_FORMAT_SIGNED_INT8 = 0x08, + HIP_AD_FORMAT_SIGNED_INT16 = 0x09, + HIP_AD_FORMAT_SIGNED_INT32 = 0x0a, + HIP_AD_FORMAT_HALF = 0x10, + HIP_AD_FORMAT_FLOAT = 0x20 +}hipArray_Format; +typedef struct HIP_ARRAY_DESCRIPTOR { + size_t Width; + size_t Height; + enum hipArray_Format Format; + unsigned int NumChannels; +}HIP_ARRAY_DESCRIPTOR; +typedef struct HIP_ARRAY3D_DESCRIPTOR { + size_t Width; + size_t Height; + size_t Depth; + enum hipArray_Format Format; + unsigned int NumChannels; + unsigned int Flags; +}HIP_ARRAY3D_DESCRIPTOR; +#if !defined(__HIPCC_RTC__) +typedef struct hip_Memcpy2D { + size_t srcXInBytes; + size_t srcY; + hipMemoryType srcMemoryType; + const void* srcHost; + hipDeviceptr_t srcDevice; + hipArray_t srcArray; + size_t srcPitch; + size_t dstXInBytes; + size_t dstY; + hipMemoryType dstMemoryType; + void* dstHost; + hipDeviceptr_t dstDevice; + hipArray_t dstArray; + size_t dstPitch; + size_t WidthInBytes; + size_t Height; +} hip_Memcpy2D; +#endif // !defined(__HIPCC_RTC__) +typedef struct hipMipmappedArray { + void* data; + struct hipChannelFormatDesc desc; + unsigned int type; + unsigned int width; + unsigned int height; + unsigned int depth; + unsigned int min_mipmap_level; + unsigned int max_mipmap_level; + unsigned int flags; + enum hipArray_Format format; + unsigned int num_channels; +} hipMipmappedArray; +typedef struct hipMipmappedArray* hipMipmappedArray_t; +typedef hipMipmappedArray_t hipmipmappedArray; +typedef const struct hipMipmappedArray* hipMipmappedArray_const_t; +/** + * hip resource types + */ +typedef enum hipResourceType { + hipResourceTypeArray = 0x00, + hipResourceTypeMipmappedArray = 0x01, + hipResourceTypeLinear = 0x02, + hipResourceTypePitch2D = 0x03 +}hipResourceType; +typedef enum HIPresourcetype_enum { + HIP_RESOURCE_TYPE_ARRAY = 0x00, /**< Array resoure */ + HIP_RESOURCE_TYPE_MIPMAPPED_ARRAY = 0x01, /**< Mipmapped array resource */ + HIP_RESOURCE_TYPE_LINEAR = 0x02, /**< Linear resource */ + HIP_RESOURCE_TYPE_PITCH2D = 0x03 /**< Pitch 2D resource */ +} HIPresourcetype, hipResourcetype; +/** + * hip address modes + */ +typedef enum HIPaddress_mode_enum { + HIP_TR_ADDRESS_MODE_WRAP = 0, + HIP_TR_ADDRESS_MODE_CLAMP = 1, + HIP_TR_ADDRESS_MODE_MIRROR = 2, + HIP_TR_ADDRESS_MODE_BORDER = 3 +} HIPaddress_mode; +/** + * hip filter modes + */ +typedef enum HIPfilter_mode_enum { + HIP_TR_FILTER_MODE_POINT = 0, + HIP_TR_FILTER_MODE_LINEAR = 1 +} HIPfilter_mode; +/** + * Texture descriptor + */ +typedef struct HIP_TEXTURE_DESC_st { + HIPaddress_mode addressMode[3]; /**< Address modes */ + HIPfilter_mode filterMode; /**< Filter mode */ + unsigned int flags; /**< Flags */ + unsigned int maxAnisotropy; /**< Maximum anisotropy ratio */ + HIPfilter_mode mipmapFilterMode; /**< Mipmap filter mode */ + float mipmapLevelBias; /**< Mipmap level bias */ + float minMipmapLevelClamp; /**< Mipmap minimum level clamp */ + float maxMipmapLevelClamp; /**< Mipmap maximum level clamp */ + float borderColor[4]; /**< Border Color */ + int reserved[12]; +} HIP_TEXTURE_DESC; +/** + * hip texture resource view formats + */ +typedef enum hipResourceViewFormat { + hipResViewFormatNone = 0x00, + hipResViewFormatUnsignedChar1 = 0x01, + hipResViewFormatUnsignedChar2 = 0x02, + hipResViewFormatUnsignedChar4 = 0x03, + hipResViewFormatSignedChar1 = 0x04, + hipResViewFormatSignedChar2 = 0x05, + hipResViewFormatSignedChar4 = 0x06, + hipResViewFormatUnsignedShort1 = 0x07, + hipResViewFormatUnsignedShort2 = 0x08, + hipResViewFormatUnsignedShort4 = 0x09, + hipResViewFormatSignedShort1 = 0x0a, + hipResViewFormatSignedShort2 = 0x0b, + hipResViewFormatSignedShort4 = 0x0c, + hipResViewFormatUnsignedInt1 = 0x0d, + hipResViewFormatUnsignedInt2 = 0x0e, + hipResViewFormatUnsignedInt4 = 0x0f, + hipResViewFormatSignedInt1 = 0x10, + hipResViewFormatSignedInt2 = 0x11, + hipResViewFormatSignedInt4 = 0x12, + hipResViewFormatHalf1 = 0x13, + hipResViewFormatHalf2 = 0x14, + hipResViewFormatHalf4 = 0x15, + hipResViewFormatFloat1 = 0x16, + hipResViewFormatFloat2 = 0x17, + hipResViewFormatFloat4 = 0x18, + hipResViewFormatUnsignedBlockCompressed1 = 0x19, + hipResViewFormatUnsignedBlockCompressed2 = 0x1a, + hipResViewFormatUnsignedBlockCompressed3 = 0x1b, + hipResViewFormatUnsignedBlockCompressed4 = 0x1c, + hipResViewFormatSignedBlockCompressed4 = 0x1d, + hipResViewFormatUnsignedBlockCompressed5 = 0x1e, + hipResViewFormatSignedBlockCompressed5 = 0x1f, + hipResViewFormatUnsignedBlockCompressed6H = 0x20, + hipResViewFormatSignedBlockCompressed6H = 0x21, + hipResViewFormatUnsignedBlockCompressed7 = 0x22 +}hipResourceViewFormat; +typedef enum HIPresourceViewFormat_enum +{ + HIP_RES_VIEW_FORMAT_NONE = 0x00, /**< No resource view format (use underlying resource format) */ + HIP_RES_VIEW_FORMAT_UINT_1X8 = 0x01, /**< 1 channel unsigned 8-bit integers */ + HIP_RES_VIEW_FORMAT_UINT_2X8 = 0x02, /**< 2 channel unsigned 8-bit integers */ + HIP_RES_VIEW_FORMAT_UINT_4X8 = 0x03, /**< 4 channel unsigned 8-bit integers */ + HIP_RES_VIEW_FORMAT_SINT_1X8 = 0x04, /**< 1 channel signed 8-bit integers */ + HIP_RES_VIEW_FORMAT_SINT_2X8 = 0x05, /**< 2 channel signed 8-bit integers */ + HIP_RES_VIEW_FORMAT_SINT_4X8 = 0x06, /**< 4 channel signed 8-bit integers */ + HIP_RES_VIEW_FORMAT_UINT_1X16 = 0x07, /**< 1 channel unsigned 16-bit integers */ + HIP_RES_VIEW_FORMAT_UINT_2X16 = 0x08, /**< 2 channel unsigned 16-bit integers */ + HIP_RES_VIEW_FORMAT_UINT_4X16 = 0x09, /**< 4 channel unsigned 16-bit integers */ + HIP_RES_VIEW_FORMAT_SINT_1X16 = 0x0a, /**< 1 channel signed 16-bit integers */ + HIP_RES_VIEW_FORMAT_SINT_2X16 = 0x0b, /**< 2 channel signed 16-bit integers */ + HIP_RES_VIEW_FORMAT_SINT_4X16 = 0x0c, /**< 4 channel signed 16-bit integers */ + HIP_RES_VIEW_FORMAT_UINT_1X32 = 0x0d, /**< 1 channel unsigned 32-bit integers */ + HIP_RES_VIEW_FORMAT_UINT_2X32 = 0x0e, /**< 2 channel unsigned 32-bit integers */ + HIP_RES_VIEW_FORMAT_UINT_4X32 = 0x0f, /**< 4 channel unsigned 32-bit integers */ + HIP_RES_VIEW_FORMAT_SINT_1X32 = 0x10, /**< 1 channel signed 32-bit integers */ + HIP_RES_VIEW_FORMAT_SINT_2X32 = 0x11, /**< 2 channel signed 32-bit integers */ + HIP_RES_VIEW_FORMAT_SINT_4X32 = 0x12, /**< 4 channel signed 32-bit integers */ + HIP_RES_VIEW_FORMAT_FLOAT_1X16 = 0x13, /**< 1 channel 16-bit floating point */ + HIP_RES_VIEW_FORMAT_FLOAT_2X16 = 0x14, /**< 2 channel 16-bit floating point */ + HIP_RES_VIEW_FORMAT_FLOAT_4X16 = 0x15, /**< 4 channel 16-bit floating point */ + HIP_RES_VIEW_FORMAT_FLOAT_1X32 = 0x16, /**< 1 channel 32-bit floating point */ + HIP_RES_VIEW_FORMAT_FLOAT_2X32 = 0x17, /**< 2 channel 32-bit floating point */ + HIP_RES_VIEW_FORMAT_FLOAT_4X32 = 0x18, /**< 4 channel 32-bit floating point */ + HIP_RES_VIEW_FORMAT_UNSIGNED_BC1 = 0x19, /**< Block compressed 1 */ + HIP_RES_VIEW_FORMAT_UNSIGNED_BC2 = 0x1a, /**< Block compressed 2 */ + HIP_RES_VIEW_FORMAT_UNSIGNED_BC3 = 0x1b, /**< Block compressed 3 */ + HIP_RES_VIEW_FORMAT_UNSIGNED_BC4 = 0x1c, /**< Block compressed 4 unsigned */ + HIP_RES_VIEW_FORMAT_SIGNED_BC4 = 0x1d, /**< Block compressed 4 signed */ + HIP_RES_VIEW_FORMAT_UNSIGNED_BC5 = 0x1e, /**< Block compressed 5 unsigned */ + HIP_RES_VIEW_FORMAT_SIGNED_BC5 = 0x1f, /**< Block compressed 5 signed */ + HIP_RES_VIEW_FORMAT_UNSIGNED_BC6H = 0x20, /**< Block compressed 6 unsigned half-float */ + HIP_RES_VIEW_FORMAT_SIGNED_BC6H = 0x21, /**< Block compressed 6 signed half-float */ + HIP_RES_VIEW_FORMAT_UNSIGNED_BC7 = 0x22 /**< Block compressed 7 */ +} HIPresourceViewFormat; +/** + * HIP resource descriptor + */ +typedef struct hipResourceDesc { + enum hipResourceType resType; + union { + struct { + hipArray_t array; + } array; + struct { + hipMipmappedArray_t mipmap; + } mipmap; + struct { + void* devPtr; + struct hipChannelFormatDesc desc; + size_t sizeInBytes; + } linear; + struct { + void* devPtr; + struct hipChannelFormatDesc desc; + size_t width; + size_t height; + size_t pitchInBytes; + } pitch2D; + } res; +}hipResourceDesc; +typedef struct HIP_RESOURCE_DESC_st +{ + HIPresourcetype resType; /**< Resource type */ + union { + struct { + hipArray_t hArray; /**< HIP array */ + } array; + struct { + hipMipmappedArray_t hMipmappedArray; /**< HIP mipmapped array */ + } mipmap; + struct { + hipDeviceptr_t devPtr; /**< Device pointer */ + hipArray_Format format; /**< Array format */ + unsigned int numChannels; /**< Channels per array element */ + size_t sizeInBytes; /**< Size in bytes */ + } linear; + struct { + hipDeviceptr_t devPtr; /**< Device pointer */ + hipArray_Format format; /**< Array format */ + unsigned int numChannels; /**< Channels per array element */ + size_t width; /**< Width of the array in elements */ + size_t height; /**< Height of the array in elements */ + size_t pitchInBytes; /**< Pitch between two rows in bytes */ + } pitch2D; + struct { + int reserved[32]; + } reserved; + } res; + unsigned int flags; /**< Flags (must be zero) */ +} HIP_RESOURCE_DESC; +/** + * hip resource view descriptor + */ +struct hipResourceViewDesc { + enum hipResourceViewFormat format; + size_t width; + size_t height; + size_t depth; + unsigned int firstMipmapLevel; + unsigned int lastMipmapLevel; + unsigned int firstLayer; + unsigned int lastLayer; +}; +/** + * Resource view descriptor + */ +typedef struct HIP_RESOURCE_VIEW_DESC_st +{ + HIPresourceViewFormat format; /**< Resource view format */ + size_t width; /**< Width of the resource view */ + size_t height; /**< Height of the resource view */ + size_t depth; /**< Depth of the resource view */ + unsigned int firstMipmapLevel; /**< First defined mipmap level */ + unsigned int lastMipmapLevel; /**< Last defined mipmap level */ + unsigned int firstLayer; /**< First layer index */ + unsigned int lastLayer; /**< Last layer index */ + unsigned int reserved[16]; +} HIP_RESOURCE_VIEW_DESC; +/** + * Memory copy types + * + */ +#if !defined(__HIPCC_RTC__) +typedef enum hipMemcpyKind { + hipMemcpyHostToHost = 0, ///< Host-to-Host Copy + hipMemcpyHostToDevice = 1, ///< Host-to-Device Copy + hipMemcpyDeviceToHost = 2, ///< Device-to-Host Copy + hipMemcpyDeviceToDevice = 3, ///< Device-to-Device Copy + hipMemcpyDefault = 4, ///< Runtime will automatically determine + /// + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +#include +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif + +#endif // HIP_INCLUDE_HIP_HIP_BF16_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_bfloat16.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_bfloat16.h new file mode 100644 index 0000000000000000000000000000000000000000..988f793ebcaf9bf235e91980b6f6eee70ab001d5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_bfloat16.h @@ -0,0 +1,44 @@ +/** + * 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_BFLOAT16_H_ +#define _HIP_BFLOAT16_H_ + +#if !defined(__HIPCC_RTC__) +#include +#endif + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +#include +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#warning "hip_bfloat16.h is not supported on nvidia platform" +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif + +#endif // _HIP_BFLOAT16_H_ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_common.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_common.h new file mode 100644 index 0000000000000000000000000000000000000000..a1e000d8ce6597d55d0bb51fbdc572d4939d5c6a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_common.h @@ -0,0 +1,100 @@ +/* +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_HIP_COMMON_H +#define HIP_INCLUDE_HIP_HIP_COMMON_H + +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreserved-macro-identifier" +#endif +// Common code included at start of every hip file. +// Auto enable __HIP_PLATFORM_AMD__ if compiling on AMD platform +// Other compiler (GCC,ICC,etc) need to set one of these macros explicitly +#if defined(__clang__) && defined(__HIP__) +#ifndef __HIP_PLATFORM_AMD__ +#define __HIP_PLATFORM_AMD__ +#endif +#endif // defined(__clang__) && defined(__HIP__) + +// Auto enable __HIP_PLATFORM_NVIDIA__ if compiling with NVIDIA platform +#if defined(__NVCC__) || (defined(__clang__) && defined(__CUDA__) && !defined(__HIP__)) +#ifndef __HIP_PLATFORM_NVIDIA__ +#define __HIP_PLATFORM_NVIDIA__ +#endif + +#ifdef __CUDACC__ +#define __HIPCC__ +#endif + +#endif //__NVCC__ + +// Auto enable __HIP_DEVICE_COMPILE__ if compiled in HCC or NVCC device path +#if (defined(__HCC_ACCELERATOR__) && __HCC_ACCELERATOR__ != 0) || \ + (defined(__CUDA_ARCH__) && __CUDA_ARCH__ != 0) +#define __HIP_DEVICE_COMPILE__ 1 +#endif + +#ifdef __GNUC__ +#define HIP_PUBLIC_API __attribute__ ((visibility ("default"))) +#define HIP_INTERNAL_EXPORTED_API __attribute__ ((visibility ("default"))) +#else +#define HIP_PUBLIC_API +#define HIP_INTERNAL_EXPORTED_API +#endif + +#if __HIP_DEVICE_COMPILE__ == 0 +// 32-bit Atomics +#define __HIP_ARCH_HAS_GLOBAL_INT32_ATOMICS__ (0) +#define __HIP_ARCH_HAS_GLOBAL_FLOAT_ATOMIC_EXCH__ (0) +#define __HIP_ARCH_HAS_SHARED_INT32_ATOMICS__ (0) +#define __HIP_ARCH_HAS_SHARED_FLOAT_ATOMIC_EXCH__ (0) +#define __HIP_ARCH_HAS_FLOAT_ATOMIC_ADD__ (0) + +// 64-bit Atomics +#define __HIP_ARCH_HAS_GLOBAL_INT64_ATOMICS__ (0) +#define __HIP_ARCH_HAS_SHARED_INT64_ATOMICS__ (0) + +// Doubles +#define __HIP_ARCH_HAS_DOUBLES__ (0) + +// Warp cross-lane operations +#define __HIP_ARCH_HAS_WARP_VOTE__ (0) +#define __HIP_ARCH_HAS_WARP_BALLOT__ (0) +#define __HIP_ARCH_HAS_WARP_SHUFFLE__ (0) +#define __HIP_ARCH_HAS_WARP_FUNNEL_SHIFT__ (0) + +// Sync +#define __HIP_ARCH_HAS_THREAD_FENCE_SYSTEM__ (0) +#define __HIP_ARCH_HAS_SYNC_THREAD_EXT__ (0) + +// Misc +#define __HIP_ARCH_HAS_SURFACE_FUNCS__ (0) +#define __HIP_ARCH_HAS_3DGRID__ (0) +#define __HIP_ARCH_HAS_DYNAMIC_PARALLEL__ (0) +#endif + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_complex.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_complex.h new file mode 100644 index 0000000000000000000000000000000000000000..a8d1b6ee617a0618ff2c5788d4454ef0a86258ae --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_complex.h @@ -0,0 +1,38 @@ +/* +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_HIP_COMPLEX_H +#define HIP_INCLUDE_HIP_HIP_COMPLEX_H + +#if !defined(__HIPCC_RTC__) +#include +#endif + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +#include +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_cooperative_groups.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_cooperative_groups.h new file mode 100644 index 0000000000000000000000000000000000000000..4baff6812012524e02cf18016e55f5a721b0a2b2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_cooperative_groups.h @@ -0,0 +1,46 @@ +/* +Copyright (c) 2015 - 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. +*/ + +/** + * @file hip_cooperative_groups.h + * + * @brief Defines new types and device API wrappers for `Cooperative Group` + * feature. + */ + +#ifndef HIP_INCLUDE_HIP_HIP_COOPERATIVE_GROUP_H +#define HIP_INCLUDE_HIP_HIP_COOPERATIVE_GROUP_H + +#include +#include + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +#if __cplusplus && defined(__clang__) && defined(__HIP__) +#include +#endif +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif + +#endif // HIP_INCLUDE_HIP_HIP_COOPERATIVE_GROUP_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_deprecated.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_deprecated.h new file mode 100644 index 0000000000000000000000000000000000000000..5cc578321ef2c2f6a0ecef03c091fb268b6a705d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_deprecated.h @@ -0,0 +1,95 @@ +#pragma once + +// This file will add older hip functions used in the versioning system +// Find the deprecated functions and structs in hip_device.cpp + +// This struct is also kept in hip_device.cpp +typedef struct hipDeviceProp_tR0000 { + char name[256]; ///< Device name. + size_t totalGlobalMem; ///< Size of global memory region (in bytes). + size_t sharedMemPerBlock; ///< Size of shared memory region (in bytes). + int regsPerBlock; ///< Registers per block. + int warpSize; ///< Warp size. + int maxThreadsPerBlock; ///< Max work items per work group or workgroup max size. + int maxThreadsDim[3]; ///< Max number of threads in each dimension (XYZ) of a block. + int maxGridSize[3]; ///< Max grid dimensions (XYZ). + int clockRate; ///< Max clock frequency of the multiProcessors in khz. + int memoryClockRate; ///< Max global memory clock frequency in khz. + int memoryBusWidth; ///< Global memory bus width in bits. + size_t totalConstMem; ///< Size of shared memory region (in bytes). + int major; ///< Major compute capability. On HCC, this is an approximation and features may + ///< differ from CUDA CC. See the arch feature flags for portable ways to query + ///< feature caps. + int minor; ///< Minor compute capability. On HCC, this is an approximation and features may + ///< differ from CUDA CC. See the arch feature flags for portable ways to query + ///< feature caps. + int multiProcessorCount; ///< Number of multi-processors (compute units). + int l2CacheSize; ///< L2 cache size. + int maxThreadsPerMultiProcessor; ///< Maximum resident threads per multi-processor. + int computeMode; ///< Compute mode. + int clockInstructionRate; ///< Frequency in khz of the timer used by the device-side "clock*" + ///< instructions. New for HIP. + hipDeviceArch_t arch; ///< Architectural feature flags. New for HIP. + int concurrentKernels; ///< Device can possibly execute multiple kernels concurrently. + int pciDomainID; ///< PCI Domain ID + int pciBusID; ///< PCI Bus ID. + int pciDeviceID; ///< PCI Device ID. + size_t maxSharedMemoryPerMultiProcessor; ///< Maximum Shared Memory Per Multiprocessor. + int isMultiGpuBoard; ///< 1 if device is on a multi-GPU board, 0 if not. + int canMapHostMemory; ///< Check whether HIP can map host memory + int gcnArch; ///< DEPRECATED: use gcnArchName instead + char gcnArchName[256]; ///< AMD GCN Arch Name. + int integrated; ///< APU vs dGPU + int cooperativeLaunch; ///< HIP device supports cooperative launch + int cooperativeMultiDeviceLaunch; ///< HIP device supports cooperative launch on multiple + ///< devices + int maxTexture1DLinear; ///< Maximum size for 1D textures bound to linear memory + int maxTexture1D; ///< Maximum number of elements in 1D images + int maxTexture2D[2]; ///< Maximum dimensions (width, height) of 2D images, in image elements + int maxTexture3D[3]; ///< Maximum dimensions (width, height, depth) of 3D images, in image + ///< elements + unsigned int* hdpMemFlushCntl; ///< Addres of HDP_MEM_COHERENCY_FLUSH_CNTL register + unsigned int* hdpRegFlushCntl; ///< Addres of HDP_REG_COHERENCY_FLUSH_CNTL register + size_t memPitch; ///< Maximum pitch in bytes allowed by memory copies + size_t textureAlignment; ///< Alignment requirement for textures + size_t texturePitchAlignment; ///< Pitch alignment requirement for texture references bound to + ///< pitched memory + int kernelExecTimeoutEnabled; ///< Run time limit for kernels executed on the device + int ECCEnabled; ///< Device has ECC support enabled + int tccDriver; ///< 1:If device is Tesla device using TCC driver, else 0 + int cooperativeMultiDeviceUnmatchedFunc; ///< HIP device supports cooperative launch on + ///< multiple + /// devices with unmatched functions + int cooperativeMultiDeviceUnmatchedGridDim; ///< HIP device supports cooperative launch on + ///< multiple + /// devices with unmatched grid dimensions + int cooperativeMultiDeviceUnmatchedBlockDim; ///< HIP device supports cooperative launch on + ///< multiple + /// devices with unmatched block dimensions + int cooperativeMultiDeviceUnmatchedSharedMem; ///< HIP device supports cooperative launch on + ///< multiple + /// devices with unmatched shared memories + int isLargeBar; ///< 1: if it is a large PCI bar device, else 0 + int asicRevision; ///< Revision of the GPU in this device + int managedMemory; ///< Device supports allocating managed memory on this system + int directManagedMemAccessFromHost; ///< Host can directly access managed memory on the device + ///< without migration + int concurrentManagedAccess; ///< Device can coherently access managed memory concurrently with + ///< the CPU + int pageableMemoryAccess; ///< Device supports coherently accessing pageable memory + ///< without calling hipHostRegister on it + int pageableMemoryAccessUsesHostPageTables; ///< Device accesses pageable memory via the host's + ///< page tables +} hipDeviceProp_tR0000; + + +#ifdef __cplusplus +extern "C" { +#endif + +hipError_t hipGetDevicePropertiesR0000(hipDeviceProp_tR0000* prop, int device); +hipError_t hipChooseDeviceR0000(int* device, const hipDeviceProp_tR0000* prop); + +#ifdef __cplusplus +} +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_ext.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_ext.h new file mode 100644 index 0000000000000000000000000000000000000000..319f5694d0213b342b5f53948c615350d4c20d2c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_ext.h @@ -0,0 +1,161 @@ +/* +Copyright (c) 2015 - 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_HIP_EXT_H +#define HIP_INCLUDE_HIP_HIP_EXT_H +#include "hip/hip_runtime.h" +#if defined(__cplusplus) +#include +#include +#endif +/** @addtogroup Module Module Management + * @{ + */ + +/** + * @brief Launches kernel with parameters and shared memory on stream with arguments passed + * to kernel params or extra arguments. + * + * @param [in] f Kernel to launch. + * @param [in] globalWorkSizeX X grid dimension specified in work-items. + * @param [in] globalWorkSizeY Y grid dimension specified in work-items. + * @param [in] globalWorkSizeZ Z grid dimension specified in work-items. + * @param [in] localWorkSizeX X block dimension specified in work-items. + * @param [in] localWorkSizeY Y block dimension specified in work-items. + * @param [in] localWorkSizeZ Z block dimension specified in work-items. + * @param [in] sharedMemBytes Amount of dynamic shared memory to allocate for this kernel. + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] hStream Stream where the kernel should be dispatched. + * May be 0, in which case the default stream is used with associated synchronization rules. + * @param [in] kernelParams pointer to kernel parameters. + * @param [in] extra Pointer to kernel arguments. These are passed directly to the kernel and + * must be in the memory layout and alignment expected by the kernel. + * All passed arguments must be naturally aligned according to their type. The memory address of each + * argument should be a multiple of its size in bytes. Please refer to hip_porting_driver_api.md + * for sample usage. + * @param [in] startEvent If non-null, specified event will be updated to track the start time of + * the kernel launch. The event must be created before calling this API. + * @param [in] stopEvent If non-null, specified event will be updated to track the stop time of + * the kernel launch. The event must be created before calling this API. + * @param [in] flags The value of hipExtAnyOrderLaunch, signifies if kernel can be + * launched in any order. + * @returns #hipSuccess, #hipInvalidDeviceId, #hipErrorNotInitialized, #hipErrorInvalidValue. + * + * HIP/ROCm actually updates the start event when the associated kernel completes. + * Currently, timing between startEvent and stopEvent does not include the time it takes to perform + * a system scope release/cache flush - only the time it takes to issues writes to cache. + * + * @note For this HIP API, the flag 'hipExtAnyOrderLaunch' is not supported on AMD GFX9xx boards. + * + */ +HIP_PUBLIC_API + extern "C" hipError_t hipExtModuleLaunchKernel(hipFunction_t f, uint32_t globalWorkSizeX, + uint32_t globalWorkSizeY, uint32_t globalWorkSizeZ, + uint32_t localWorkSizeX, uint32_t localWorkSizeY, + uint32_t localWorkSizeZ, size_t sharedMemBytes, + hipStream_t hStream, void** kernelParams, void** extra, + hipEvent_t startEvent __dparm(NULL), + hipEvent_t stopEvent __dparm(NULL), + uint32_t flags __dparm(0)); +/** + * @brief This HIP API is deprecated, please use hipExtModuleLaunchKernel() instead. + * + */ +DEPRECATED("use hipExtModuleLaunchKernel instead") +HIP_PUBLIC_API +extern "C" hipError_t hipHccModuleLaunchKernel(hipFunction_t f, uint32_t globalWorkSizeX, + uint32_t globalWorkSizeY, uint32_t globalWorkSizeZ, + uint32_t localWorkSizeX, uint32_t localWorkSizeY, + uint32_t localWorkSizeZ, size_t sharedMemBytes, + hipStream_t hStream, void** kernelParams, void** extra, + hipEvent_t startEvent __dparm(NULL), + hipEvent_t stopEvent __dparm(NULL)); + +#if defined(__cplusplus) + +/** + * @brief Launches kernel from the pointer address, with arguments and shared memory on stream. + * + * @param [in] function_address pointer to the Kernel to launch. + * @param [in] numBlocks number of blocks. + * @param [in] dimBlocks dimension of a block. + * @param [in] args pointer to kernel arguments. + * @param [in] sharedMemBytes Amount of dynamic shared memory to allocate for this kernel. + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream Stream where the kernel should be dispatched. + * May be 0, in which case the default stream is used with associated synchronization rules. + * @param [in] startEvent If non-null, specified event will be updated to track the start time of + * the kernel launch. The event must be created before calling this API. + * @param [in] stopEvent If non-null, specified event will be updated to track the stop time of + * the kernel launch. The event must be created before calling this API. + * @param [in] flags The value of hipExtAnyOrderLaunch, signifies if kernel can be + * launched in any order. + * @returns #hipSuccess, #hipInvalidDeviceId, #hipErrorNotInitialized, #hipErrorInvalidValue. + * + */ +extern "C" hipError_t hipExtLaunchKernel(const void* function_address, dim3 numBlocks, + dim3 dimBlocks, void** args, size_t sharedMemBytes, + hipStream_t stream, hipEvent_t startEvent, + hipEvent_t stopEvent, int flags); + +/** + * @brief Launches kernel with dimention parameters and shared memory on stream with templated kernel and arguments. + * + * @param [in] kernel Kernel to launch. + * @param [in] numBlocks const number of blocks. + * @param [in] dimBlocks const dimension of a block. + * @param [in] sharedMemBytes Amount of dynamic shared memory to allocate for this kernel. + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream Stream where the kernel should be dispatched. + * May be 0, in which case the default stream is used with associated synchronization rules. + * @param [in] startEvent If non-null, specified event will be updated to track the start time of + * the kernel launch. The event must be created before calling this API. + * @param [in] stopEvent If non-null, specified event will be updated to track the stop time of + * the kernel launch. The event must be created before calling this API. + * @param [in] flags The value of hipExtAnyOrderLaunch, signifies if kernel can be + * launched in any order. + * @param [in] args templated kernel arguments. + * + */ +template +inline void hipExtLaunchKernelGGL(F kernel, const dim3& numBlocks, const dim3& dimBlocks, + std::uint32_t sharedMemBytes, hipStream_t stream, + hipEvent_t startEvent, hipEvent_t stopEvent, std::uint32_t flags, + Args... args) { + constexpr size_t count = sizeof...(Args); + auto tup_ = std::tuple{args...}; + auto tup = validateArgsCountType(kernel, tup_); + void* _Args[count]; + pArgs<0>(tup, _Args); + + auto k = reinterpret_cast(kernel); + hipExtLaunchKernel(k, numBlocks, dimBlocks, _Args, sharedMemBytes, stream, startEvent, + stopEvent, (int)flags); +} + +#endif // defined(__cplusplus) + +// doxygen end AMD-specific features +/** + * @} + */ +#endif // #iidef HIP_INCLUDE_HIP_HIP_EXT_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_fp16.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_fp16.h new file mode 100644 index 0000000000000000000000000000000000000000..67def4ee1aacda39153f9b4e37f319a69d83af5e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_fp16.h @@ -0,0 +1,36 @@ +/* +Copyright (c) 2015 - 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_HIP_FP16_H +#define HIP_INCLUDE_HIP_HIP_FP16_H + +#include + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +#include +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include "cuda_fp16.h" +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_fp8.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_fp8.h new file mode 100644 index 0000000000000000000000000000000000000000..82f47afcba08f02ff35d129a075d57225afb6b94 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_fp8.h @@ -0,0 +1,33 @@ +/* +Copyright (c) 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. +*/ + +#ifndef HIP_INCLUDE_HIP_HIP_FP8_H +#define HIP_INCLUDE_HIP_HIP_FP8_H + +#include + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +// We only have fnuz defs for now, which are not supported by other platforms +#include +#endif + +#endif // HIP_INCLUDE_HIP_HIP_FP8_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_gl_interop.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_gl_interop.h new file mode 100644 index 0000000000000000000000000000000000000000..8af6ec32d195cd3b5d95131779d58916cbb33e59 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_gl_interop.h @@ -0,0 +1,32 @@ +/* +Copyright (c) 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_GL_INTEROP_H +#define HIP_GL_INTEROP_H + +#include + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +#include "hip/amd_detail/amd_hip_gl_interop.h" +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include "hip/nvidia_detail/nvidia_hip_gl_interop.h" +#endif +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_hcc.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_hcc.h new file mode 100644 index 0000000000000000000000000000000000000000..9e0cfada333fbc2ab4baa4655e5bc3b18228b2de --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_hcc.h @@ -0,0 +1,24 @@ +/* +Copyright (c) 2015 - 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_HIP_HCC_H +#define HIP_INCLUDE_HIP_HIP_HCC_H +#warning "hip/hip_hcc.h is deprecated, please use hip/hip_ext.h" +#include "hip/hip_ext.h" +#endif // #ifdef HIP_INCLUDE_HIP_HIP_HCC_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_math_constants.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_math_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..4cce93c0fc55addfebaa6c302df217f4c8ffd1eb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_math_constants.h @@ -0,0 +1,36 @@ +/* +Copyright (c) 2015 - 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. +*/ +#ifndef HIP_MATH_CONSTANTS_H +#define HIP_MATH_CONSTANTS_H + +#if !defined(__HIPCC_RTC__) +#include +#endif + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +#include "hip/amd_detail/amd_hip_math_constants.h" +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include "hip/nvidia_detail/nvidia_hip_math_constants.h" +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_profile.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_profile.h new file mode 100644 index 0000000000000000000000000000000000000000..4fef521d1cfe5f1f3486193f9fd79ed0abbd4af0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_profile.h @@ -0,0 +1,27 @@ +/* +Copyright (c) 2015 - 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_HIP_PROFILE_H +#define HIP_INCLUDE_HIP_HIP_PROFILE_H + +#define HIP_SCOPED_MARKER(markerName, group) +#define HIP_BEGIN_MARKER(markerName, group) +#define HIP_END_MARKER() + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_runtime.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_runtime.h new file mode 100644 index 0000000000000000000000000000000000000000..20dd9703df4e1027ab30bbe12b320aa3178ea3eb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_runtime.h @@ -0,0 +1,75 @@ +/* +Copyright (c) 2015 - 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. +*/ + +//! HIP = Heterogeneous-compute Interface for Portability +//! +//! Define a extremely thin runtime layer that allows source code to be compiled unmodified +//! through either AMD CLANG or NVCC. Key features tend to be in the spirit +//! and terminology of CUDA, but with a portable path to other accelerators as well: +// +//! Both paths support rich C++ features including classes, templates, lambdas, etc. +//! Runtime API is C +//! Memory management is based on pure pointers and resembles malloc/free/copy. +// +//! hip_runtime.h : includes everything in hip_api.h, plus math builtins and kernel launch +//! macros. hip_runtime_api.h : Defines HIP API. This is a C header file and does not use any C++ +//! features. + +#ifndef HIP_INCLUDE_HIP_HIP_RUNTIME_H +#define HIP_INCLUDE_HIP_HIP_RUNTIME_H + +#if __HIP_DEVICE_COMPILE__ && !__GFX7__ && !__GFX8__ && !__GFX9__ && __AMDGCN_WAVEFRONT_SIZE == 64 +#error HIP is not supported on the specified GPU ARCH with wavefront size 64 +#endif + +#if !defined(__HIPCC_RTC__) +// Some standard header files, these are included by hc.hpp and so want to make them avail on both +// paths to provide a consistent include env and avoid "missing symbol" errors that only appears +// on NVCC path: +#include +#include +#include +#include + +#if __cplusplus > 199711L +#include +#endif +#endif // !defined(__HIPCC_RTC__) + +#include +#include + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +#include +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif + +#if !defined(__HIPCC_RTC__) +#include +#include +#endif // !defined(__HIPCC_RTC__) +#include + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_runtime_api.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_runtime_api.h new file mode 100644 index 0000000000000000000000000000000000000000..0e612ee6d9b96cd62db992eca525d292f655dca1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_runtime_api.h @@ -0,0 +1,9261 @@ +/* +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 hip_runtime_api.h + * + * @brief Defines the API signatures for HIP runtime. + * This file can be compiled with a standard compiler. + */ + +#ifndef HIP_INCLUDE_HIP_HIP_RUNTIME_API_H +#define HIP_INCLUDE_HIP_HIP_RUNTIME_API_H + +#include // for getDeviceProp +#include +#include + +enum { + HIP_SUCCESS = 0, + HIP_ERROR_INVALID_VALUE, + HIP_ERROR_NOT_INITIALIZED, + HIP_ERROR_LAUNCH_OUT_OF_RESOURCES +}; +// hack to get these to show up in Doxygen: +/** + * @defgroup GlobalDefs Global enum and defines + * @{ + * + */ +/** + * hipDeviceArch_t + * + */ +typedef struct { + // 32-bit Atomics + unsigned hasGlobalInt32Atomics : 1; ///< 32-bit integer atomics for global memory. + unsigned hasGlobalFloatAtomicExch : 1; ///< 32-bit float atomic exch for global memory. + unsigned hasSharedInt32Atomics : 1; ///< 32-bit integer atomics for shared memory. + unsigned hasSharedFloatAtomicExch : 1; ///< 32-bit float atomic exch for shared memory. + unsigned hasFloatAtomicAdd : 1; ///< 32-bit float atomic add in global and shared memory. + + // 64-bit Atomics + unsigned hasGlobalInt64Atomics : 1; ///< 64-bit integer atomics for global memory. + unsigned hasSharedInt64Atomics : 1; ///< 64-bit integer atomics for shared memory. + + // Doubles + unsigned hasDoubles : 1; ///< Double-precision floating point. + + // Warp cross-lane operations + unsigned hasWarpVote : 1; ///< Warp vote instructions (__any, __all). + unsigned hasWarpBallot : 1; ///< Warp ballot instructions (__ballot). + unsigned hasWarpShuffle : 1; ///< Warp shuffle operations. (__shfl_*). + unsigned hasFunnelShift : 1; ///< Funnel two words into one with shift&mask caps. + + // Sync + unsigned hasThreadFenceSystem : 1; ///< __threadfence_system. + unsigned hasSyncThreadsExt : 1; ///< __syncthreads_count, syncthreads_and, syncthreads_or. + + // Misc + unsigned hasSurfaceFuncs : 1; ///< Surface functions. + unsigned has3dGrid : 1; ///< Grid and group dims are 3D (rather than 2D). + unsigned hasDynamicParallelism : 1; ///< Dynamic parallelism. +} hipDeviceArch_t; + +typedef struct hipUUID_t { + char bytes[16]; +} hipUUID; + +//--- +// Common headers for both NVCC and HCC paths: + +#define hipGetDeviceProperties hipGetDevicePropertiesR0600 +#define hipDeviceProp_t hipDeviceProp_tR0600 +#define hipChooseDevice hipChooseDeviceR0600 + +/** + * hipDeviceProp + * + */ +typedef struct hipDeviceProp_t { + char name[256]; ///< Device name. + hipUUID uuid; ///< UUID of a device + char luid[8]; ///< 8-byte unique identifier. Only valid on windows + unsigned int luidDeviceNodeMask; ///< LUID node mask + size_t totalGlobalMem; ///< Size of global memory region (in bytes). + size_t sharedMemPerBlock; ///< Size of shared memory per block (in bytes). + int regsPerBlock; ///< Registers per block. + int warpSize; ///< Warp size. + size_t memPitch; ///< Maximum pitch in bytes allowed by memory copies + ///< pitched memory + int maxThreadsPerBlock; ///< Max work items per work group or workgroup max size. + int maxThreadsDim[3]; ///< Max number of threads in each dimension (XYZ) of a block. + int maxGridSize[3]; ///< Max grid dimensions (XYZ). + int clockRate; ///< Max clock frequency of the multiProcessors in khz. + size_t totalConstMem; ///< Size of shared constant memory region on the device + ///< (in bytes). + int major; ///< Major compute capability. On HCC, this is an approximation and features may + ///< differ from CUDA CC. See the arch feature flags for portable ways to query + ///< feature caps. + int minor; ///< Minor compute capability. On HCC, this is an approximation and features may + ///< differ from CUDA CC. See the arch feature flags for portable ways to query + ///< feature caps. + size_t textureAlignment; ///< Alignment requirement for textures + size_t texturePitchAlignment; ///< Pitch alignment requirement for texture references bound to + int deviceOverlap; ///< Deprecated. Use asyncEngineCount instead + int multiProcessorCount; ///< Number of multi-processors (compute units). + int kernelExecTimeoutEnabled; ///< Run time limit for kernels executed on the device + int integrated; ///< APU vs dGPU + int canMapHostMemory; ///< Check whether HIP can map host memory + int computeMode; ///< Compute mode. + int maxTexture1D; ///< Maximum number of elements in 1D images + int maxTexture1DMipmap; ///< Maximum 1D mipmap texture size + int maxTexture1DLinear; ///< Maximum size for 1D textures bound to linear memory + int maxTexture2D[2]; ///< Maximum dimensions (width, height) of 2D images, in image elements + int maxTexture2DMipmap[2]; ///< Maximum number of elements in 2D array mipmap of images + int maxTexture2DLinear[3]; ///< Maximum 2D tex dimensions if tex are bound to pitched memory + int maxTexture2DGather[2]; ///< Maximum 2D tex dimensions if gather has to be performed + int maxTexture3D[3]; ///< Maximum dimensions (width, height, depth) of 3D images, in image + ///< elements + int maxTexture3DAlt[3]; ///< Maximum alternate 3D texture dims + int maxTextureCubemap; ///< Maximum cubemap texture dims + int maxTexture1DLayered[2]; ///< Maximum number of elements in 1D array images + int maxTexture2DLayered[3]; ///< Maximum number of elements in 2D array images + int maxTextureCubemapLayered[2]; ///< Maximum cubemaps layered texture dims + int maxSurface1D; ///< Maximum 1D surface size + int maxSurface2D[2]; ///< Maximum 2D surface size + int maxSurface3D[3]; ///< Maximum 3D surface size + int maxSurface1DLayered[2]; ///< Maximum 1D layered surface size + int maxSurface2DLayered[3]; ///< Maximum 2D layared surface size + int maxSurfaceCubemap; ///< Maximum cubemap surface size + int maxSurfaceCubemapLayered[2]; ///< Maximum cubemap layered surface size + size_t surfaceAlignment; ///< Alignment requirement for surface + int concurrentKernels; ///< Device can possibly execute multiple kernels concurrently. + int ECCEnabled; ///< Device has ECC support enabled + int pciBusID; ///< PCI Bus ID. + int pciDeviceID; ///< PCI Device ID. + int pciDomainID; ///< PCI Domain ID + int tccDriver; ///< 1:If device is Tesla device using TCC driver, else 0 + int asyncEngineCount; ///< Number of async engines + int unifiedAddressing; ///< Does device and host share unified address space + int memoryClockRate; ///< Max global memory clock frequency in khz. + int memoryBusWidth; ///< Global memory bus width in bits. + int l2CacheSize; ///< L2 cache size. + int persistingL2CacheMaxSize; ///< Device's max L2 persisting lines in bytes + int maxThreadsPerMultiProcessor; ///< Maximum resident threads per multi-processor. + int streamPrioritiesSupported; ///< Device supports stream priority + int globalL1CacheSupported; ///< Indicates globals are cached in L1 + int localL1CacheSupported; ///< Locals are cahced in L1 + size_t sharedMemPerMultiprocessor; ///< Amount of shared memory available per multiprocessor. + int regsPerMultiprocessor; ///< registers available per multiprocessor + int managedMemory; ///< Device supports allocating managed memory on this system + int isMultiGpuBoard; ///< 1 if device is on a multi-GPU board, 0 if not. + int multiGpuBoardGroupID; ///< Unique identifier for a group of devices on same multiboard GPU + int hostNativeAtomicSupported; ///< Link between host and device supports native atomics + int singleToDoublePrecisionPerfRatio; ///< Deprecated. CUDA only. + int pageableMemoryAccess; ///< Device supports coherently accessing pageable memory + ///< without calling hipHostRegister on it + int concurrentManagedAccess; ///< Device can coherently access managed memory concurrently with + ///< the CPU + int computePreemptionSupported; ///< Is compute preemption supported on the device + int canUseHostPointerForRegisteredMem; ///< Device can access host registered memory with same + ///< address as the host + int cooperativeLaunch; ///< HIP device supports cooperative launch + int cooperativeMultiDeviceLaunch; ///< HIP device supports cooperative launch on multiple + ///< devices + size_t + sharedMemPerBlockOptin; ///< Per device m ax shared mem per block usable by special opt in + int pageableMemoryAccessUsesHostPageTables; ///< Device accesses pageable memory via the host's + ///< page tables + int directManagedMemAccessFromHost; ///< Host can directly access managed memory on the device + ///< without migration + int maxBlocksPerMultiProcessor; ///< Max number of blocks on CU + int accessPolicyMaxWindowSize; ///< Max value of access policy window + size_t reservedSharedMemPerBlock; ///< Shared memory reserved by driver per block + int hostRegisterSupported; ///< Device supports hipHostRegister + int sparseHipArraySupported; ///< Indicates if device supports sparse hip arrays + int hostRegisterReadOnlySupported; ///< Device supports using the hipHostRegisterReadOnly flag + ///< with hipHostRegistger + int timelineSemaphoreInteropSupported; ///< Indicates external timeline semaphore support + int memoryPoolsSupported; ///< Indicates if device supports hipMallocAsync and hipMemPool APIs + int gpuDirectRDMASupported; ///< Indicates device support of RDMA APIs + unsigned int gpuDirectRDMAFlushWritesOptions; ///< Bitmask to be interpreted according to + ///< hipFlushGPUDirectRDMAWritesOptions + int gpuDirectRDMAWritesOrdering; ///< value of hipGPUDirectRDMAWritesOrdering + unsigned int + memoryPoolSupportedHandleTypes; ///< Bitmask of handle types support with mempool based IPC + int deferredMappingHipArraySupported; ///< Device supports deferred mapping HIP arrays and HIP + ///< mipmapped arrays + int ipcEventSupported; ///< Device supports IPC events + int clusterLaunch; ///< Device supports cluster launch + int unifiedFunctionPointers; ///< Indicates device supports unified function pointers + int reserved[63]; ///< CUDA Reserved. + + int hipReserved[32]; ///< Reserved for adding new entries for HIP/CUDA. + + /* HIP Only struct members */ + char gcnArchName[256]; ///< AMD GCN Arch Name. HIP Only. + size_t maxSharedMemoryPerMultiProcessor; ///< Maximum Shared Memory Per CU. HIP Only. + int clockInstructionRate; ///< Frequency in khz of the timer used by the device-side "clock*" + ///< instructions. New for HIP. + hipDeviceArch_t arch; ///< Architectural feature flags. New for HIP. + unsigned int* hdpMemFlushCntl; ///< Addres of HDP_MEM_COHERENCY_FLUSH_CNTL register + unsigned int* hdpRegFlushCntl; ///< Addres of HDP_REG_COHERENCY_FLUSH_CNTL register + int cooperativeMultiDeviceUnmatchedFunc; ///< HIP device supports cooperative launch on + ///< multiple + /// devices with unmatched functions + int cooperativeMultiDeviceUnmatchedGridDim; ///< HIP device supports cooperative launch on + ///< multiple + /// devices with unmatched grid dimensions + int cooperativeMultiDeviceUnmatchedBlockDim; ///< HIP device supports cooperative launch on + ///< multiple + /// devices with unmatched block dimensions + int cooperativeMultiDeviceUnmatchedSharedMem; ///< HIP device supports cooperative launch on + ///< multiple + /// devices with unmatched shared memories + int isLargeBar; ///< 1: if it is a large PCI bar device, else 0 + int asicRevision; ///< Revision of the GPU in this device +} hipDeviceProp_t; + + /** + * hipMemoryType (for pointer attributes) + * + * @note hipMemoryType enum values are combination of cudaMemoryType and cuMemoryType and AMD specific enum values. + * + */ +typedef enum hipMemoryType { + hipMemoryTypeUnregistered = 0, ///< Unregistered memory + hipMemoryTypeHost = 1, ///< Memory is physically located on host + hipMemoryTypeDevice = 2, ///< Memory is physically located on device. (see deviceId for + ///< specific device) + hipMemoryTypeManaged = 3, ///< Managed memory, automaticallly managed by the unified + ///< memory system + ///< place holder for new values. + hipMemoryTypeArray = 10, ///< Array memory, physically located on device. (see deviceId for + ///< specific device) + hipMemoryTypeUnified = 11 ///< unified address space + +} hipMemoryType; + +/** + * Pointer attributes + */ +typedef struct hipPointerAttribute_t { + enum hipMemoryType type; + int device; + void* devicePointer; + void* hostPointer; + int isManaged; + unsigned allocationFlags; /* flags specified when memory was allocated*/ + /* peers? */ +} hipPointerAttribute_t; + +// Ignoring error-code return values from hip APIs is discouraged. On C++17, +// we can make that yield a warning +#if __cplusplus >= 201703L +#define __HIP_NODISCARD [[nodiscard]] +#else +#define __HIP_NODISCARD +#endif + +/** + * HIP error type + * + */ +// Developer note - when updating these, update the hipErrorName and hipErrorString functions in +// NVCC and HCC paths Also update the hipCUDAErrorTohipError function in NVCC path. + +typedef enum __HIP_NODISCARD hipError_t { + hipSuccess = 0, ///< Successful completion. + hipErrorInvalidValue = 1, ///< One or more of the parameters passed to the API call is NULL + ///< or not in an acceptable range. + hipErrorOutOfMemory = 2, ///< out of memory range. + // Deprecated + hipErrorMemoryAllocation = 2, ///< Memory allocation error. + hipErrorNotInitialized = 3, ///< Invalid not initialized + // Deprecated + hipErrorInitializationError = 3, + hipErrorDeinitialized = 4, ///< Deinitialized + hipErrorProfilerDisabled = 5, + hipErrorProfilerNotInitialized = 6, + hipErrorProfilerAlreadyStarted = 7, + hipErrorProfilerAlreadyStopped = 8, + hipErrorInvalidConfiguration = 9, ///< Invalide configuration + hipErrorInvalidPitchValue = 12, ///< Invalid pitch value + hipErrorInvalidSymbol = 13, ///< Invalid symbol + hipErrorInvalidDevicePointer = 17, ///< Invalid Device Pointer + hipErrorInvalidMemcpyDirection = 21, ///< Invalid memory copy direction + hipErrorInsufficientDriver = 35, + hipErrorMissingConfiguration = 52, + hipErrorPriorLaunchFailure = 53, + hipErrorInvalidDeviceFunction = 98, ///< Invalid device function + hipErrorNoDevice = 100, ///< Call to hipGetDeviceCount returned 0 devices + hipErrorInvalidDevice = 101, ///< DeviceID must be in range from 0 to compute-devices. + hipErrorInvalidImage = 200, ///< Invalid image + hipErrorInvalidContext = 201, ///< Produced when input context is invalid. + hipErrorContextAlreadyCurrent = 202, + hipErrorMapFailed = 205, + // Deprecated + hipErrorMapBufferObjectFailed = 205, ///< Produced when the IPC memory attach failed from ROCr. + hipErrorUnmapFailed = 206, + hipErrorArrayIsMapped = 207, + hipErrorAlreadyMapped = 208, + hipErrorNoBinaryForGpu = 209, + hipErrorAlreadyAcquired = 210, + hipErrorNotMapped = 211, + hipErrorNotMappedAsArray = 212, + hipErrorNotMappedAsPointer = 213, + hipErrorECCNotCorrectable = 214, + hipErrorUnsupportedLimit = 215, ///< Unsupported limit + hipErrorContextAlreadyInUse = 216, ///< The context is already in use + hipErrorPeerAccessUnsupported = 217, + hipErrorInvalidKernelFile = 218, ///< In CUDA DRV, it is CUDA_ERROR_INVALID_PTX + hipErrorInvalidGraphicsContext = 219, + hipErrorInvalidSource = 300, ///< Invalid source. + hipErrorFileNotFound = 301, ///< the file is not found. + hipErrorSharedObjectSymbolNotFound = 302, + hipErrorSharedObjectInitFailed = 303, ///< Failed to initialize shared object. + hipErrorOperatingSystem = 304, ///< Not the correct operating system + hipErrorInvalidHandle = 400, ///< Invalide handle + // Deprecated + hipErrorInvalidResourceHandle = 400, ///< Resource handle (hipEvent_t or hipStream_t) invalid. + hipErrorIllegalState = 401, ///< Resource required is not in a valid state to perform operation. + hipErrorNotFound = 500, ///< Not found + hipErrorNotReady = 600, ///< Indicates that asynchronous operations enqueued earlier are not + ///< ready. This is not actually an error, but is used to distinguish + ///< from hipSuccess (which indicates completion). APIs that return + ///< this error include hipEventQuery and hipStreamQuery. + hipErrorIllegalAddress = 700, + hipErrorLaunchOutOfResources = 701, ///< Out of resources error. + hipErrorLaunchTimeOut = 702, ///< Timeout for the launch. + hipErrorPeerAccessAlreadyEnabled = 704, ///< Peer access was already enabled from the current + ///< device. + hipErrorPeerAccessNotEnabled = 705, ///< Peer access was never enabled from the current device. + hipErrorSetOnActiveProcess = 708, ///< The process is active. + hipErrorContextIsDestroyed = 709, ///< The context is already destroyed + hipErrorAssert = 710, ///< Produced when the kernel calls assert. + hipErrorHostMemoryAlreadyRegistered = 712, ///< Produced when trying to lock a page-locked + ///< memory. + hipErrorHostMemoryNotRegistered = 713, ///< Produced when trying to unlock a non-page-locked + ///< memory. + hipErrorLaunchFailure = 719, ///< An exception occurred on the device while executing a kernel. + hipErrorCooperativeLaunchTooLarge = 720, ///< This error indicates that the number of blocks + ///< launched per grid for a kernel that was launched + ///< via cooperative launch APIs exceeds the maximum + ///< number of allowed blocks for the current device. + hipErrorNotSupported = 801, ///< Produced when the hip API is not supported/implemented + hipErrorStreamCaptureUnsupported = 900, ///< The operation is not permitted when the stream + ///< is capturing. + hipErrorStreamCaptureInvalidated = 901, ///< The current capture sequence on the stream + ///< has been invalidated due to a previous error. + hipErrorStreamCaptureMerge = 902, ///< The operation would have resulted in a merge of + ///< two independent capture sequences. + hipErrorStreamCaptureUnmatched = 903, ///< The capture was not initiated in this stream. + hipErrorStreamCaptureUnjoined = 904, ///< The capture sequence contains a fork that was not + ///< joined to the primary stream. + hipErrorStreamCaptureIsolation = 905, ///< A dependency would have been created which crosses + ///< the capture sequence boundary. Only implicit + ///< in-stream ordering dependencies are allowed + ///< to cross the boundary + hipErrorStreamCaptureImplicit = 906, ///< The operation would have resulted in a disallowed + ///< implicit dependency on a current capture sequence + ///< from hipStreamLegacy. + hipErrorCapturedEvent = 907, ///< The operation is not permitted on an event which was last + ///< recorded in a capturing stream. + hipErrorStreamCaptureWrongThread = 908, ///< A stream capture sequence not initiated with + ///< the hipStreamCaptureModeRelaxed argument to + ///< hipStreamBeginCapture was passed to + ///< hipStreamEndCapture in a different thread. + hipErrorGraphExecUpdateFailure = 910, ///< This error indicates that the graph update + ///< not performed because it included changes which + ///< violated constraintsspecific to instantiated graph + ///< update. + hipErrorUnknown = 999, ///< Unknown error. + // HSA Runtime Error Codes start here. + hipErrorRuntimeMemory = 1052, ///< HSA runtime memory call returned error. Typically not seen + ///< in production systems. + hipErrorRuntimeOther = 1053, ///< HSA runtime call other than memory returned error. Typically + ///< not seen in production systems. + hipErrorTbd ///< Marker that more error codes are needed. +} hipError_t; + +#undef __HIP_NODISCARD + +/** + * hipDeviceAttribute_t + * hipDeviceAttributeUnused number: 5 + */ +typedef enum hipDeviceAttribute_t { + hipDeviceAttributeCudaCompatibleBegin = 0, + + hipDeviceAttributeEccEnabled = hipDeviceAttributeCudaCompatibleBegin, ///< Whether ECC support is enabled. + hipDeviceAttributeAccessPolicyMaxWindowSize, ///< Cuda only. The maximum size of the window policy in bytes. + hipDeviceAttributeAsyncEngineCount, ///< Asynchronous engines number. + hipDeviceAttributeCanMapHostMemory, ///< Whether host memory can be mapped into device address space + hipDeviceAttributeCanUseHostPointerForRegisteredMem,///< Device can access host registered memory + ///< at the same virtual address as the CPU + hipDeviceAttributeClockRate, ///< Peak clock frequency in kilohertz. + hipDeviceAttributeComputeMode, ///< Compute mode that device is currently in. + hipDeviceAttributeComputePreemptionSupported, ///< Device supports Compute Preemption. + hipDeviceAttributeConcurrentKernels, ///< Device can possibly execute multiple kernels concurrently. + hipDeviceAttributeConcurrentManagedAccess, ///< Device can coherently access managed memory concurrently with the CPU + hipDeviceAttributeCooperativeLaunch, ///< Support cooperative launch + hipDeviceAttributeCooperativeMultiDeviceLaunch, ///< Support cooperative launch on multiple devices + hipDeviceAttributeDeviceOverlap, ///< Device can concurrently copy memory and execute a kernel. + ///< Deprecated. Use instead asyncEngineCount. + hipDeviceAttributeDirectManagedMemAccessFromHost, ///< Host can directly access managed memory on + ///< the device without migration + hipDeviceAttributeGlobalL1CacheSupported, ///< Device supports caching globals in L1 + hipDeviceAttributeHostNativeAtomicSupported, ///< Link between the device and the host supports native atomic operations + hipDeviceAttributeIntegrated, ///< Device is integrated GPU + hipDeviceAttributeIsMultiGpuBoard, ///< Multiple GPU devices. + hipDeviceAttributeKernelExecTimeout, ///< Run time limit for kernels executed on the device + hipDeviceAttributeL2CacheSize, ///< Size of L2 cache in bytes. 0 if the device doesn't have L2 cache. + hipDeviceAttributeLocalL1CacheSupported, ///< caching locals in L1 is supported + hipDeviceAttributeLuid, ///< 8-byte locally unique identifier in 8 bytes. Undefined on TCC and non-Windows platforms + hipDeviceAttributeLuidDeviceNodeMask, ///< Luid device node mask. Undefined on TCC and non-Windows platforms + hipDeviceAttributeComputeCapabilityMajor, ///< Major compute capability version number. + hipDeviceAttributeManagedMemory, ///< Device supports allocating managed memory on this system + hipDeviceAttributeMaxBlocksPerMultiProcessor, ///< Max block size per multiprocessor + hipDeviceAttributeMaxBlockDimX, ///< Max block size in width. + hipDeviceAttributeMaxBlockDimY, ///< Max block size in height. + hipDeviceAttributeMaxBlockDimZ, ///< Max block size in depth. + hipDeviceAttributeMaxGridDimX, ///< Max grid size in width. + hipDeviceAttributeMaxGridDimY, ///< Max grid size in height. + hipDeviceAttributeMaxGridDimZ, ///< Max grid size in depth. + hipDeviceAttributeMaxSurface1D, ///< Maximum size of 1D surface. + hipDeviceAttributeMaxSurface1DLayered, ///< Cuda only. Maximum dimensions of 1D layered surface. + hipDeviceAttributeMaxSurface2D, ///< Maximum dimension (width, height) of 2D surface. + hipDeviceAttributeMaxSurface2DLayered, ///< Cuda only. Maximum dimensions of 2D layered surface. + hipDeviceAttributeMaxSurface3D, ///< Maximum dimension (width, height, depth) of 3D surface. + hipDeviceAttributeMaxSurfaceCubemap, ///< Cuda only. Maximum dimensions of Cubemap surface. + hipDeviceAttributeMaxSurfaceCubemapLayered, ///< Cuda only. Maximum dimension of Cubemap layered surface. + hipDeviceAttributeMaxTexture1DWidth, ///< Maximum size of 1D texture. + hipDeviceAttributeMaxTexture1DLayered, ///< Maximum dimensions of 1D layered texture. + hipDeviceAttributeMaxTexture1DLinear, ///< Maximum number of elements allocatable in a 1D linear texture. + ///< Use cudaDeviceGetTexture1DLinearMaxWidth() instead on Cuda. + hipDeviceAttributeMaxTexture1DMipmap, ///< Maximum size of 1D mipmapped texture. + hipDeviceAttributeMaxTexture2DWidth, ///< Maximum dimension width of 2D texture. + hipDeviceAttributeMaxTexture2DHeight, ///< Maximum dimension hight of 2D texture. + hipDeviceAttributeMaxTexture2DGather, ///< Maximum dimensions of 2D texture if gather operations performed. + hipDeviceAttributeMaxTexture2DLayered, ///< Maximum dimensions of 2D layered texture. + hipDeviceAttributeMaxTexture2DLinear, ///< Maximum dimensions (width, height, pitch) of 2D textures bound to pitched memory. + hipDeviceAttributeMaxTexture2DMipmap, ///< Maximum dimensions of 2D mipmapped texture. + hipDeviceAttributeMaxTexture3DWidth, ///< Maximum dimension width of 3D texture. + hipDeviceAttributeMaxTexture3DHeight, ///< Maximum dimension height of 3D texture. + hipDeviceAttributeMaxTexture3DDepth, ///< Maximum dimension depth of 3D texture. + hipDeviceAttributeMaxTexture3DAlt, ///< Maximum dimensions of alternate 3D texture. + hipDeviceAttributeMaxTextureCubemap, ///< Maximum dimensions of Cubemap texture + hipDeviceAttributeMaxTextureCubemapLayered, ///< Maximum dimensions of Cubemap layered texture. + hipDeviceAttributeMaxThreadsDim, ///< Maximum dimension of a block + hipDeviceAttributeMaxThreadsPerBlock, ///< Maximum number of threads per block. + hipDeviceAttributeMaxThreadsPerMultiProcessor, ///< Maximum resident threads per multiprocessor. + hipDeviceAttributeMaxPitch, ///< Maximum pitch in bytes allowed by memory copies + hipDeviceAttributeMemoryBusWidth, ///< Global memory bus width in bits. + hipDeviceAttributeMemoryClockRate, ///< Peak memory clock frequency in kilohertz. + hipDeviceAttributeComputeCapabilityMinor, ///< Minor compute capability version number. + hipDeviceAttributeMultiGpuBoardGroupID, ///< Unique ID of device group on the same multi-GPU board + hipDeviceAttributeMultiprocessorCount, ///< Number of multiprocessors on the device. + hipDeviceAttributeUnused1, ///< Previously hipDeviceAttributeName + hipDeviceAttributePageableMemoryAccess, ///< Device supports coherently accessing pageable memory + ///< without calling hipHostRegister on it + hipDeviceAttributePageableMemoryAccessUsesHostPageTables, ///< Device accesses pageable memory via the host's page tables + hipDeviceAttributePciBusId, ///< PCI Bus ID. + hipDeviceAttributePciDeviceId, ///< PCI Device ID. + hipDeviceAttributePciDomainID, ///< PCI Domain ID. + hipDeviceAttributePersistingL2CacheMaxSize, ///< Maximum l2 persisting lines capacity in bytes + hipDeviceAttributeMaxRegistersPerBlock, ///< 32-bit registers available to a thread block. This number is shared + ///< by all thread blocks simultaneously resident on a multiprocessor. + hipDeviceAttributeMaxRegistersPerMultiprocessor, ///< 32-bit registers available per block. + hipDeviceAttributeReservedSharedMemPerBlock, ///< Shared memory reserved by CUDA driver per block. + hipDeviceAttributeMaxSharedMemoryPerBlock, ///< Maximum shared memory available per block in bytes. + hipDeviceAttributeSharedMemPerBlockOptin, ///< Maximum shared memory per block usable by special opt in. + hipDeviceAttributeSharedMemPerMultiprocessor, ///< Shared memory available per multiprocessor. + hipDeviceAttributeSingleToDoublePrecisionPerfRatio, ///< Cuda only. Performance ratio of single precision to double precision. + hipDeviceAttributeStreamPrioritiesSupported, ///< Whether to support stream priorities. + hipDeviceAttributeSurfaceAlignment, ///< Alignment requirement for surfaces + hipDeviceAttributeTccDriver, ///< Cuda only. Whether device is a Tesla device using TCC driver + hipDeviceAttributeTextureAlignment, ///< Alignment requirement for textures + hipDeviceAttributeTexturePitchAlignment, ///< Pitch alignment requirement for 2D texture references bound to pitched memory; + hipDeviceAttributeTotalConstantMemory, ///< Constant memory size in bytes. + hipDeviceAttributeTotalGlobalMem, ///< Global memory available on devicice. + hipDeviceAttributeUnifiedAddressing, ///< Cuda only. An unified address space shared with the host. + hipDeviceAttributeUnused2, ///< Previously hipDeviceAttributeUuid + hipDeviceAttributeWarpSize, ///< Warp size in threads. + hipDeviceAttributeMemoryPoolsSupported, ///< Device supports HIP Stream Ordered Memory Allocator + hipDeviceAttributeVirtualMemoryManagementSupported, ///< Device supports HIP virtual memory management + hipDeviceAttributeHostRegisterSupported, ///< Can device support host memory registration via hipHostRegister + hipDeviceAttributeMemoryPoolSupportedHandleTypes, ///< Supported handle mask for HIP Stream Ordered Memory Allocator + + hipDeviceAttributeCudaCompatibleEnd = 9999, + hipDeviceAttributeAmdSpecificBegin = 10000, + + hipDeviceAttributeClockInstructionRate = hipDeviceAttributeAmdSpecificBegin, ///< Frequency in khz of the timer used by the device-side "clock*" + hipDeviceAttributeUnused3, ///< Previously hipDeviceAttributeArch + hipDeviceAttributeMaxSharedMemoryPerMultiprocessor, ///< Maximum Shared Memory PerMultiprocessor. + hipDeviceAttributeUnused4, ///< Previously hipDeviceAttributeGcnArch + hipDeviceAttributeUnused5, ///< Previously hipDeviceAttributeGcnArchName + hipDeviceAttributeHdpMemFlushCntl, ///< Address of the HDP_MEM_COHERENCY_FLUSH_CNTL register + hipDeviceAttributeHdpRegFlushCntl, ///< Address of the HDP_REG_COHERENCY_FLUSH_CNTL register + hipDeviceAttributeCooperativeMultiDeviceUnmatchedFunc, ///< Supports cooperative launch on multiple + ///< devices with unmatched functions + hipDeviceAttributeCooperativeMultiDeviceUnmatchedGridDim, ///< Supports cooperative launch on multiple + ///< devices with unmatched grid dimensions + hipDeviceAttributeCooperativeMultiDeviceUnmatchedBlockDim, ///< Supports cooperative launch on multiple + ///< devices with unmatched block dimensions + hipDeviceAttributeCooperativeMultiDeviceUnmatchedSharedMem, ///< Supports cooperative launch on multiple + ///< devices with unmatched shared memories + hipDeviceAttributeIsLargeBar, ///< Whether it is LargeBar + hipDeviceAttributeAsicRevision, ///< Revision of the GPU in this device + hipDeviceAttributeCanUseStreamWaitValue, ///< '1' if Device supports hipStreamWaitValue32() and + ///< hipStreamWaitValue64(), '0' otherwise. + hipDeviceAttributeImageSupport, ///< '1' if Device supports image, '0' otherwise. + hipDeviceAttributePhysicalMultiProcessorCount, ///< All available physical compute + ///< units for the device + hipDeviceAttributeFineGrainSupport, ///< '1' if Device supports fine grain, '0' otherwise + hipDeviceAttributeWallClockRate, ///< Constant frequency of wall clock in kilohertz. + + hipDeviceAttributeAmdSpecificEnd = 19999, + hipDeviceAttributeVendorSpecificBegin = 20000, + // Extended attributes for vendors +} hipDeviceAttribute_t; + +typedef enum hipDriverProcAddressQueryResult { + HIP_GET_PROC_ADDRESS_SUCCESS = 0, + HIP_GET_PROC_ADDRESS_SYMBOL_NOT_FOUND = 1, + HIP_GET_PROC_ADDRESS_VERSION_NOT_SUFFICIENT = 2 +} hipDriverProcAddressQueryResult; + +enum hipComputeMode { + hipComputeModeDefault = 0, + hipComputeModeExclusive = 1, + hipComputeModeProhibited = 2, + hipComputeModeExclusiveProcess = 3 +}; + +enum hipFlushGPUDirectRDMAWritesOptions { + hipFlushGPUDirectRDMAWritesOptionHost = 1 << 0, + hipFlushGPUDirectRDMAWritesOptionMemOps = 1 << 1 +}; + +enum hipGPUDirectRDMAWritesOrdering { + hipGPUDirectRDMAWritesOrderingNone = 0, + hipGPUDirectRDMAWritesOrderingOwner = 100, + hipGPUDirectRDMAWritesOrderingAllDevices = 200 +}; + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) + +#include +#include +#ifndef GENERIC_GRID_LAUNCH +#define GENERIC_GRID_LAUNCH 1 +#endif +#include +#include +#include +#include +#if defined(_MSC_VER) +#define DEPRECATED(msg) __declspec(deprecated(msg)) +#else // !defined(_MSC_VER) +#define DEPRECATED(msg) __attribute__ ((deprecated(msg))) +#endif // !defined(_MSC_VER) +#define DEPRECATED_MSG "This API is marked as deprecated and may not be supported in future releases. For more details please refer https://github.com/ROCm/HIP/blob/develop/docs/reference/deprecated_api_list.md" +#define HIP_LAUNCH_PARAM_BUFFER_POINTER ((void*)0x01) +#define HIP_LAUNCH_PARAM_BUFFER_SIZE ((void*)0x02) +#define HIP_LAUNCH_PARAM_END ((void*)0x03) +#ifdef __cplusplus + #define __dparm(x) \ + = x +#else + #define __dparm(x) +#endif +#ifdef __GNUC__ +#pragma GCC visibility push (default) +#endif +#ifdef __cplusplus +namespace hip_impl { +hipError_t hip_init(); +} // namespace hip_impl +#endif +// Structure definitions: +#ifdef __cplusplus +extern "C" { +#endif +//--- +// API-visible structures +typedef struct ihipCtx_t* hipCtx_t; +// Note many APIs also use integer deviceIds as an alternative to the device pointer: +typedef int hipDevice_t; +typedef enum hipDeviceP2PAttr { + hipDevP2PAttrPerformanceRank = 0, + hipDevP2PAttrAccessSupported, + hipDevP2PAttrNativeAtomicSupported, + hipDevP2PAttrHipArrayAccessSupported +} hipDeviceP2PAttr; +typedef struct ihipStream_t* hipStream_t; +#define hipIpcMemLazyEnablePeerAccess 0x01 +#define HIP_IPC_HANDLE_SIZE 64 +typedef struct hipIpcMemHandle_st { + char reserved[HIP_IPC_HANDLE_SIZE]; +} hipIpcMemHandle_t; +typedef struct hipIpcEventHandle_st { + char reserved[HIP_IPC_HANDLE_SIZE]; +} hipIpcEventHandle_t; +typedef struct ihipModule_t* hipModule_t; +typedef struct ihipModuleSymbol_t* hipFunction_t; +/** + * HIP memory pool + */ +typedef struct ihipMemPoolHandle_t* hipMemPool_t; + +typedef struct hipFuncAttributes { + int binaryVersion; + int cacheModeCA; + size_t constSizeBytes; + size_t localSizeBytes; + int maxDynamicSharedSizeBytes; + int maxThreadsPerBlock; + int numRegs; + int preferredShmemCarveout; + int ptxVersion; + size_t sharedSizeBytes; +} hipFuncAttributes; +typedef struct ihipEvent_t* hipEvent_t; + +/** + * hipLimit + * + * @note In HIP device limit-related APIs, any input limit value other than those defined in the + * enum is treated as "UnsupportedLimit" by default. + */ +enum hipLimit_t { + hipLimitStackSize = 0x0, ///< Limit of stack size in bytes on the current device, per + ///< thread. The size is in units of 256 dwords, up to the + ///< limit of (128K - 16) + hipLimitPrintfFifoSize = 0x01, ///< Size limit in bytes of fifo used by printf call on the + ///< device. Currently not supported + hipLimitMallocHeapSize = 0x02, ///< Limit of heap size in bytes on the current device, should + ///< be less than the global memory size on the device + hipLimitRange ///< Supported limit range +}; +/** + * Flags that can be used with hipStreamCreateWithFlags. + */ +//Flags that can be used with hipStreamCreateWithFlags. +/** Default stream creation flags. These are used with hipStreamCreate().*/ +#define hipStreamDefault 0x00 + +/** Stream does not implicitly synchronize with null stream.*/ +#define hipStreamNonBlocking 0x01 + +//Flags that can be used with hipEventCreateWithFlags. +/** Default flags.*/ +#define hipEventDefault 0x0 + +/** Waiting will yield CPU. Power-friendly and usage-friendly but may increase latency.*/ +#define hipEventBlockingSync 0x1 + +/** Disable event's capability to record timing information. May improve performance.*/ +#define hipEventDisableTiming 0x2 + +/** Event can support IPC. hipEventDisableTiming also must be set.*/ +#define hipEventInterprocess 0x4 + +/** Disable performing a system scope sequentially consistent memory fence when the event + * transitions from recording to recorded. This can be used for events that are only being + * used to measure timing, and do not require the event inspection operations + * (see ::hipEventSynchronize, ::hipEventQuery, and ::hipEventElapsedTime) to synchronize-with + * the work on which the recorded event (see ::hipEventRecord) is waiting. + * On some AMD GPU devices this can improve the accuracy of timing measurements by avoiding the + * cost of cache writeback and invalidation, and the performance impact of those actions on the + * execution of following work. */ +#define hipEventDisableSystemFence 0x20000000 + +/** Use a device-scope release when recording this event. This flag is useful to obtain more + * precise timings of commands between events. The flag is a no-op on CUDA platforms.*/ +#define hipEventReleaseToDevice 0x40000000 + +/** Use a system-scope release when recording this event. This flag is useful to make + * non-coherent host memory visible to the host. The flag is a no-op on CUDA platforms.*/ +#define hipEventReleaseToSystem 0x80000000 + +//Flags that can be used with hipHostMalloc. +/** Default pinned memory allocation on the host.*/ +#define hipHostMallocDefault 0x0 + +/** Memory is considered allocated by all contexts.*/ +#define hipHostMallocPortable 0x1 + +/** Map the allocation into the address space for the current device. The device pointer + * can be obtained with #hipHostGetDevicePointer.*/ +#define hipHostMallocMapped 0x2 + +/** Allocates the memory as write-combined. On some system configurations, write-combined allocation + * may be transferred faster across the PCI Express bus, however, could have low read efficiency by + * most CPUs. It's a good option for data tranfer from host to device via mapped pinned memory.*/ +#define hipHostMallocWriteCombined 0x4 + +/** +* Host memory allocation will follow numa policy set by user. +* @note This numa allocation flag is applicable on Linux, under development on Windows. +*/ +#define hipHostMallocNumaUser 0x20000000 + +/** Allocate coherent memory. Overrides HIP_COHERENT_HOST_ALLOC for specific allocation.*/ +#define hipHostMallocCoherent 0x40000000 + +/** Allocate non-coherent memory. Overrides HIP_COHERENT_HOST_ALLOC for specific allocation.*/ +#define hipHostMallocNonCoherent 0x80000000 + +/** Memory can be accessed by any stream on any device*/ +#define hipMemAttachGlobal 0x01 + +/** Memory cannot be accessed by any stream on any device.*/ +#define hipMemAttachHost 0x02 + +/** Memory can only be accessed by a single stream on the associated device.*/ +#define hipMemAttachSingle 0x04 + +#define hipDeviceMallocDefault 0x0 + +/** Memory is allocated in fine grained region of device.*/ +#define hipDeviceMallocFinegrained 0x1 + +/** Memory represents a HSA signal.*/ +#define hipMallocSignalMemory 0x2 + +/** Memory allocated will be uncached. */ +#define hipDeviceMallocUncached 0x3 + +/** Memory allocated will be contiguous. */ +#define hipDeviceMallocContiguous 0x4 + +//Flags that can be used with hipHostRegister. +/** Memory is Mapped and Portable.*/ +#define hipHostRegisterDefault 0x0 + +/** Memory is considered registered by all contexts.*/ +#define hipHostRegisterPortable 0x1 + +/** Map the allocation into the address space for the current device. The device pointer + * can be obtained with #hipHostGetDevicePointer.*/ +#define hipHostRegisterMapped 0x2 + +/** Not supported.*/ +#define hipHostRegisterIoMemory 0x4 + +/** This flag is ignored On AMD devices.*/ +#define hipHostRegisterReadOnly 0x08 + +/** Coarse Grained host memory lock.*/ +#define hipExtHostRegisterCoarseGrained 0x8 + +/** Automatically select between Spin and Yield.*/ +#define hipDeviceScheduleAuto 0x0 + +/** Dedicate a CPU core to spin-wait. Provides lowest latency, but burns a CPU core and may + * consume more power.*/ +#define hipDeviceScheduleSpin 0x1 + +/** Yield the CPU to the operating system when waiting. May increase latency, but lowers power + * and is friendlier to other threads in the system.*/ +#define hipDeviceScheduleYield 0x2 +#define hipDeviceScheduleBlockingSync 0x4 +#define hipDeviceScheduleMask 0x7 +#define hipDeviceMapHost 0x8 +#define hipDeviceLmemResizeToMax 0x10 +/** Default HIP array allocation flag.*/ +#define hipArrayDefault 0x00 +#define hipArrayLayered 0x01 +#define hipArraySurfaceLoadStore 0x02 +#define hipArrayCubemap 0x04 +#define hipArrayTextureGather 0x08 +#define hipOccupancyDefault 0x00 +#define hipOccupancyDisableCachingOverride 0x01 +#define hipCooperativeLaunchMultiDeviceNoPreSync 0x01 +#define hipCooperativeLaunchMultiDeviceNoPostSync 0x02 +#define hipCpuDeviceId ((int)-1) +#define hipInvalidDeviceId ((int)-2) +//Flags that can be used with hipExtLaunch Set of APIs. +/** AnyOrderLaunch of kernels.*/ +#define hipExtAnyOrderLaunch 0x01 +// Flags to be used with hipStreamWaitValue32 and hipStreamWaitValue64. +#define hipStreamWaitValueGte 0x0 +#define hipStreamWaitValueEq 0x1 +#define hipStreamWaitValueAnd 0x2 +#define hipStreamWaitValueNor 0x3 +// Stream per thread +/** Implicit stream per application thread.*/ +#define hipStreamPerThread ((hipStream_t)2) + +#define hipStreamLegacy ((hipStream_t)1) + +// Indicates that the external memory object is a dedicated resource +#define hipExternalMemoryDedicated 0x1 +/** + * HIP Memory Advise values + * + * @note This memory advise enumeration is used on Linux, not Windows. + */ +typedef enum hipMemoryAdvise { + hipMemAdviseSetReadMostly = 1, ///< Data will mostly be read and only occassionally + ///< be written to + hipMemAdviseUnsetReadMostly = 2, ///< Undo the effect of hipMemAdviseSetReadMostly + hipMemAdviseSetPreferredLocation = 3, ///< Set the preferred location for the data as + ///< the specified device + hipMemAdviseUnsetPreferredLocation = 4, ///< Clear the preferred location for the data + hipMemAdviseSetAccessedBy = 5, ///< Data will be accessed by the specified device + ///< so prevent page faults as much as possible + hipMemAdviseUnsetAccessedBy = 6, ///< Let HIP to decide on the page faulting policy + ///< for the specified device + hipMemAdviseSetCoarseGrain = 100, ///< The default memory model is fine-grain. That allows + ///< coherent operations between host and device, while + ///< executing kernels. The coarse-grain can be used + ///< for data that only needs to be coherent at dispatch + ///< boundaries for better performance + hipMemAdviseUnsetCoarseGrain = 101 ///< Restores cache coherency policy back to fine-grain +} hipMemoryAdvise; +/** + * HIP Coherency Mode + */ +typedef enum hipMemRangeCoherencyMode { + hipMemRangeCoherencyModeFineGrain = 0, ///< Updates to memory with this attribute can be + ///< done coherently from all devices + hipMemRangeCoherencyModeCoarseGrain = 1, ///< Writes to memory with this attribute can be + ///< performed by a single device at a time + hipMemRangeCoherencyModeIndeterminate = 2 ///< Memory region queried contains subregions with + ///< both hipMemRangeCoherencyModeFineGrain and + ///< hipMemRangeCoherencyModeCoarseGrain attributes +} hipMemRangeCoherencyMode; +/** + * HIP range attributes + */ +typedef enum hipMemRangeAttribute { + hipMemRangeAttributeReadMostly = 1, ///< Whether the range will mostly be read and + ///< only occassionally be written to + hipMemRangeAttributePreferredLocation = 2, ///< The preferred location of the range + hipMemRangeAttributeAccessedBy = 3, ///< Memory range has hipMemAdviseSetAccessedBy + ///< set for the specified device + hipMemRangeAttributeLastPrefetchLocation = 4,///< The last location to where the range was + ///< prefetched + hipMemRangeAttributeCoherencyMode = 100, ///< Returns coherency mode + ///< @ref hipMemRangeCoherencyMode for the range +} hipMemRangeAttribute; + +/** + * HIP memory pool attributes + */ +typedef enum hipMemPoolAttr +{ + /** + * (value type = int) + * Allow @p hipMemAllocAsync to use memory asynchronously freed + * in another streams as long as a stream ordering dependency + * of the allocating stream on the free action exists. + * hip events and null stream interactions can create the required + * stream ordered dependencies. (default enabled) + */ + hipMemPoolReuseFollowEventDependencies = 0x1, + /** + * (value type = int) + * Allow reuse of already completed frees when there is no dependency + * between the free and allocation. (default enabled) + */ + hipMemPoolReuseAllowOpportunistic = 0x2, + /** + * (value type = int) + * Allow @p hipMemAllocAsync to insert new stream dependencies + * in order to establish the stream ordering required to reuse + * a piece of memory released by cuFreeAsync (default enabled). + */ + hipMemPoolReuseAllowInternalDependencies = 0x3, + /** + * (value type = uint64_t) + * Amount of reserved memory in bytes to hold onto before trying + * to release memory back to the OS. When more than the release + * threshold bytes of memory are held by the memory pool, the + * allocator will try to release memory back to the OS on the + * next call to stream, event or context synchronize. (default 0) + */ + hipMemPoolAttrReleaseThreshold = 0x4, + /** + * (value type = uint64_t) + * Amount of backing memory currently allocated for the mempool. + */ + hipMemPoolAttrReservedMemCurrent = 0x5, + /** + * (value type = uint64_t) + * High watermark of backing memory allocated for the mempool since the + * last time it was reset. High watermark can only be reset to zero. + */ + hipMemPoolAttrReservedMemHigh = 0x6, + /** + * (value type = uint64_t) + * Amount of memory from the pool that is currently in use by the application. + */ + hipMemPoolAttrUsedMemCurrent = 0x7, + /** + * (value type = uint64_t) + * High watermark of the amount of memory from the pool that was in use by the application since + * the last time it was reset. High watermark can only be reset to zero. + */ + hipMemPoolAttrUsedMemHigh = 0x8 +} hipMemPoolAttr; +/** + * Specifies the type of location + */ + typedef enum hipMemLocationType { + hipMemLocationTypeInvalid = 0, + hipMemLocationTypeDevice = 1 ///< Device location, thus its HIP device ID +} hipMemLocationType; +/** + * Specifies a memory location. + * + * To specify a gpu, set type = @p hipMemLocationTypeDevice and set id = the gpu's device ID + */ +typedef struct hipMemLocation { + hipMemLocationType type; ///< Specifies the location type, which describes the meaning of id + int id; ///< Identifier for the provided location type @p hipMemLocationType +} hipMemLocation; +/** + * Specifies the memory protection flags for mapping + * + */ +typedef enum hipMemAccessFlags { + hipMemAccessFlagsProtNone = 0, ///< Default, make the address range not accessible + hipMemAccessFlagsProtRead = 1, ///< Set the address range read accessible + hipMemAccessFlagsProtReadWrite = 3 ///< Set the address range read-write accessible +} hipMemAccessFlags; +/** + * Memory access descriptor + */ +typedef struct hipMemAccessDesc { + hipMemLocation location; ///< Location on which the accessibility has to change + hipMemAccessFlags flags; ///< Accessibility flags to set +} hipMemAccessDesc; +/** + * Defines the allocation types + */ +typedef enum hipMemAllocationType { + hipMemAllocationTypeInvalid = 0x0, + /** This allocation type is 'pinned', i.e. cannot migrate from its current + * location while the application is actively using it + */ + hipMemAllocationTypePinned = 0x1, + hipMemAllocationTypeMax = 0x7FFFFFFF +} hipMemAllocationType; +/** + * Flags for specifying handle types for memory pool allocations + * + */ +typedef enum hipMemAllocationHandleType { + hipMemHandleTypeNone = 0x0, ///< Does not allow any export mechanism + hipMemHandleTypePosixFileDescriptor = 0x1, ///< Allows a file descriptor for exporting. Permitted only on POSIX systems + hipMemHandleTypeWin32 = 0x2, ///< Allows a Win32 NT handle for exporting. (HANDLE) + hipMemHandleTypeWin32Kmt = 0x4 ///< Allows a Win32 KMT handle for exporting. (D3DKMT_HANDLE) +} hipMemAllocationHandleType; +/** + * Specifies the properties of allocations made from the pool. + */ +typedef struct hipMemPoolProps { + hipMemAllocationType allocType; ///< Allocation type. Currently must be specified as @p hipMemAllocationTypePinned + hipMemAllocationHandleType handleTypes; ///< Handle types that will be supported by allocations from the pool + hipMemLocation location; ///< Location where allocations should reside + /** + * Windows-specific LPSECURITYATTRIBUTES required when @p hipMemHandleTypeWin32 is specified + */ + void* win32SecurityAttributes; + size_t maxSize; ///< Maximum pool size. When set to 0, defaults to a system dependent value + unsigned char reserved[56]; ///< Reserved for future use, must be 0 +} hipMemPoolProps; +/** + * Opaque data structure for exporting a pool allocation + */ +typedef struct hipMemPoolPtrExportData { + unsigned char reserved[64]; +} hipMemPoolPtrExportData; + +/** + * hipJitOption + */ +typedef enum hipJitOption { + hipJitOptionMaxRegisters = 0, + hipJitOptionThreadsPerBlock, + hipJitOptionWallTime, + hipJitOptionInfoLogBuffer, + hipJitOptionInfoLogBufferSizeBytes, + hipJitOptionErrorLogBuffer, + hipJitOptionErrorLogBufferSizeBytes, + hipJitOptionOptimizationLevel, + hipJitOptionTargetFromContext, + hipJitOptionTarget, + hipJitOptionFallbackStrategy, + hipJitOptionGenerateDebugInfo, + hipJitOptionLogVerbose, + hipJitOptionGenerateLineInfo, + hipJitOptionCacheMode, + hipJitOptionSm3xOpt, + hipJitOptionFastCompile, + hipJitOptionNumOptions +} hipJitOption; +/** + * @warning On AMD devices and some Nvidia devices, these hints and controls are ignored. + */ +typedef enum hipFuncAttribute { + hipFuncAttributeMaxDynamicSharedMemorySize = 8, + hipFuncAttributePreferredSharedMemoryCarveout = 9, + hipFuncAttributeMax +} hipFuncAttribute; +/** + * @warning On AMD devices and some Nvidia devices, these hints and controls are ignored. + */ +typedef enum hipFuncCache_t { + hipFuncCachePreferNone, ///< no preference for shared memory or L1 (default) + hipFuncCachePreferShared, ///< prefer larger shared memory and smaller L1 cache + hipFuncCachePreferL1, ///< prefer larger L1 cache and smaller shared memory + hipFuncCachePreferEqual, ///< prefer equal size L1 cache and shared memory +} hipFuncCache_t; +/** + * @warning On AMD devices and some Nvidia devices, these hints and controls are ignored. + */ +typedef enum hipSharedMemConfig { + hipSharedMemBankSizeDefault, ///< The compiler selects a device-specific value for the banking. + hipSharedMemBankSizeFourByte, ///< Shared mem is banked at 4-bytes intervals and performs best + ///< when adjacent threads access data 4 bytes apart. + hipSharedMemBankSizeEightByte ///< Shared mem is banked at 8-byte intervals and performs best + ///< when adjacent threads access data 4 bytes apart. +} hipSharedMemConfig; +/** + * Struct for data in 3D + */ +typedef struct dim3 { + uint32_t x; ///< x + uint32_t y; ///< y + uint32_t z; ///< z +#ifdef __cplusplus + constexpr __host__ __device__ dim3(uint32_t _x = 1, uint32_t _y = 1, uint32_t _z = 1) : x(_x), y(_y), z(_z){}; +#endif +} dim3; +/** + * struct hipLaunchParams_t + */ +typedef struct hipLaunchParams_t { + void* func; ///< Device function symbol + dim3 gridDim; ///< Grid dimentions + dim3 blockDim; ///< Block dimentions + void **args; ///< Arguments + size_t sharedMem; ///< Shared memory + hipStream_t stream; ///< Stream identifier +} hipLaunchParams; +/** + * struct hipFunctionLaunchParams_t + */ +typedef struct hipFunctionLaunchParams_t { + hipFunction_t function; ///< Kernel to launch + unsigned int gridDimX; ///< Width(X) of grid in blocks + unsigned int gridDimY; ///< Height(Y) of grid in blocks + unsigned int gridDimZ; ///< Depth(Z) of grid in blocks + unsigned int blockDimX; ///< X dimension of each thread block + unsigned int blockDimY; ///< Y dimension of each thread block + unsigned int blockDimZ; ///< Z dimension of each thread block + unsigned int sharedMemBytes; ///< Shared memory + hipStream_t hStream; ///< Stream identifier + void **kernelParams; ///< Kernel parameters +} hipFunctionLaunchParams; +typedef enum hipExternalMemoryHandleType_enum { + hipExternalMemoryHandleTypeOpaqueFd = 1, + hipExternalMemoryHandleTypeOpaqueWin32 = 2, + hipExternalMemoryHandleTypeOpaqueWin32Kmt = 3, + hipExternalMemoryHandleTypeD3D12Heap = 4, + hipExternalMemoryHandleTypeD3D12Resource = 5, + hipExternalMemoryHandleTypeD3D11Resource = 6, + hipExternalMemoryHandleTypeD3D11ResourceKmt = 7, + hipExternalMemoryHandleTypeNvSciBuf = 8 +} hipExternalMemoryHandleType; +typedef struct hipExternalMemoryHandleDesc_st { + hipExternalMemoryHandleType type; + union { + int fd; + struct { + void *handle; + const void *name; + } win32; + const void *nvSciBufObject; + } handle; + unsigned long long size; + unsigned int flags; + unsigned int reserved[16]; +} hipExternalMemoryHandleDesc; +typedef struct hipExternalMemoryBufferDesc_st { + unsigned long long offset; + unsigned long long size; + unsigned int flags; + unsigned int reserved[16]; +} hipExternalMemoryBufferDesc; +typedef struct hipExternalMemoryMipmappedArrayDesc_st { + unsigned long long offset; + hipChannelFormatDesc formatDesc; + hipExtent extent; + unsigned int flags; + unsigned int numLevels; +} hipExternalMemoryMipmappedArrayDesc; +typedef void* hipExternalMemory_t; +typedef enum hipExternalSemaphoreHandleType_enum { + hipExternalSemaphoreHandleTypeOpaqueFd = 1, + hipExternalSemaphoreHandleTypeOpaqueWin32 = 2, + hipExternalSemaphoreHandleTypeOpaqueWin32Kmt = 3, + hipExternalSemaphoreHandleTypeD3D12Fence = 4, + hipExternalSemaphoreHandleTypeD3D11Fence = 5, + hipExternalSemaphoreHandleTypeNvSciSync = 6, + hipExternalSemaphoreHandleTypeKeyedMutex = 7, + hipExternalSemaphoreHandleTypeKeyedMutexKmt = 8, + hipExternalSemaphoreHandleTypeTimelineSemaphoreFd = 9, + hipExternalSemaphoreHandleTypeTimelineSemaphoreWin32 = 10 +} hipExternalSemaphoreHandleType; +typedef struct hipExternalSemaphoreHandleDesc_st { + hipExternalSemaphoreHandleType type; + union { + int fd; + struct { + void* handle; + const void* name; + } win32; + const void* NvSciSyncObj; + } handle; + unsigned int flags; + unsigned int reserved[16]; +} hipExternalSemaphoreHandleDesc; +typedef void* hipExternalSemaphore_t; +typedef struct hipExternalSemaphoreSignalParams_st { + struct { + struct { + unsigned long long value; + } fence; + union { + void *fence; + unsigned long long reserved; + } nvSciSync; + struct { + unsigned long long key; + } keyedMutex; + unsigned int reserved[12]; + } params; + unsigned int flags; + unsigned int reserved[16]; +} hipExternalSemaphoreSignalParams; +/** + * External semaphore wait parameters, compatible with driver type + */ +typedef struct hipExternalSemaphoreWaitParams_st { + struct { + struct { + unsigned long long value; + } fence; + union { + void *fence; + unsigned long long reserved; + } nvSciSync; + struct { + unsigned long long key; + unsigned int timeoutMs; + } keyedMutex; + unsigned int reserved[10]; + } params; + unsigned int flags; + unsigned int reserved[16]; +} hipExternalSemaphoreWaitParams; + +#if __HIP_HAS_GET_PCH +/** + * Internal use only. This API may change in the future + * Pre-Compiled header for online compilation + */ + void __hipGetPCH(const char** pch, unsigned int*size); +#endif + +/** + * HIP Access falgs for Interop resources. + */ +typedef enum hipGraphicsRegisterFlags { + hipGraphicsRegisterFlagsNone = 0, + hipGraphicsRegisterFlagsReadOnly = 1, ///< HIP will not write to this registered resource + hipGraphicsRegisterFlagsWriteDiscard = + 2, ///< HIP will only write and will not read from this registered resource + hipGraphicsRegisterFlagsSurfaceLoadStore = 4, ///< HIP will bind this resource to a surface + hipGraphicsRegisterFlagsTextureGather = + 8 ///< HIP will perform texture gather operations on this registered resource +} hipGraphicsRegisterFlags; + +typedef struct _hipGraphicsResource hipGraphicsResource; + +typedef hipGraphicsResource* hipGraphicsResource_t; + +/** + * An opaque value that represents a hip graph + */ +typedef struct ihipGraph* hipGraph_t; +/** + * An opaque value that represents a hip graph node + */ +typedef struct hipGraphNode* hipGraphNode_t; +/** + * An opaque value that represents a hip graph Exec + */ +typedef struct hipGraphExec* hipGraphExec_t; + +/** + * An opaque value that represents a user obj + */ +typedef struct hipUserObject* hipUserObject_t; + + +/** + * hipGraphNodeType + */ +typedef enum hipGraphNodeType { + hipGraphNodeTypeKernel = 0, ///< GPU kernel node + hipGraphNodeTypeMemcpy = 1, ///< Memcpy node + hipGraphNodeTypeMemset = 2, ///< Memset node + hipGraphNodeTypeHost = 3, ///< Host (executable) node + hipGraphNodeTypeGraph = 4, ///< Node which executes an embedded graph + hipGraphNodeTypeEmpty = 5, ///< Empty (no-op) node + hipGraphNodeTypeWaitEvent = 6, ///< External event wait node + hipGraphNodeTypeEventRecord = 7, ///< External event record node + hipGraphNodeTypeExtSemaphoreSignal = 8, ///< External Semaphore signal node + hipGraphNodeTypeExtSemaphoreWait = 9, ///< External Semaphore wait node + hipGraphNodeTypeMemAlloc = 10, ///< Memory alloc node + hipGraphNodeTypeMemFree = 11, ///< Memory free node + hipGraphNodeTypeMemcpyFromSymbol = 12, ///< MemcpyFromSymbol node + hipGraphNodeTypeMemcpyToSymbol = 13, ///< MemcpyToSymbol node + hipGraphNodeTypeCount +} hipGraphNodeType; + +typedef void (*hipHostFn_t)(void* userData); +typedef struct hipHostNodeParams { + hipHostFn_t fn; + void* userData; +} hipHostNodeParams; +typedef struct hipKernelNodeParams { + dim3 blockDim; + void** extra; + void* func; + dim3 gridDim; + void** kernelParams; + unsigned int sharedMemBytes; +} hipKernelNodeParams; +typedef struct hipMemsetParams { + void* dst; + unsigned int elementSize; + size_t height; + size_t pitch; + unsigned int value; + size_t width; +} hipMemsetParams; + +typedef struct hipMemAllocNodeParams { + hipMemPoolProps poolProps; ///< Pool properties, which contain where + ///< the location should reside + const hipMemAccessDesc* accessDescs;///< The number of memory access descriptors. + ///< Must not be bigger than the number of GPUs + size_t accessDescCount; ///< The number of access descriptors + size_t bytesize; ///< The size of the requested allocation in bytes + void* dptr; ///< Returned device address of the allocation +} hipMemAllocNodeParams; + + +typedef enum hipAccessProperty { + hipAccessPropertyNormal = 0, + hipAccessPropertyStreaming = 1, + hipAccessPropertyPersisting = 2, +} hipAccessProperty; +typedef struct hipAccessPolicyWindow { + void* base_ptr; + hipAccessProperty hitProp; + float hitRatio; + hipAccessProperty missProp; + size_t num_bytes; +} hipAccessPolicyWindow; + +/** + * Launch Attribute ID + */ +typedef enum hipLaunchAttributeID { + hipLaunchAttributeAccessPolicyWindow = 1, /**< Valid for Streams, graph nodes, launches*/ + hipLaunchAttributeCooperative = 2, /**< Valid for graph nodes, launches */ + hipLaunchAttributePriority = 8, /**< Valid for graph node, streams, launches */ +} hipLaunchAttributeID; + +/** + * Launch Attribute Value + */ +typedef union hipLaunchAttributeValue { + hipAccessPolicyWindow accessPolicyWindow; /**< Value of launch attribute:: + hipLaunchAttributePolicyWindow. */ + int cooperative; /**< Value of launch attribute ::hipLaunchAttributeCooperative */ + int priority; /**< Value of launch attribute :: hipLaunchAttributePriority. Execution + priority of kernel. */ +} hipLaunchAttributeValue; + +/** + * Kernel node attributeID + */ +#define hipKernelNodeAttrID hipLaunchAttributeID +#define hipKernelNodeAttributeAccessPolicyWindow hipLaunchAttributeAccessPolicyWindow +#define hipKernelNodeAttributeCooperative hipLaunchAttributeCooperative +#define hipKernelNodeAttributePriority hipLaunchAttributePriority + +/** + * Kernel node attribute value + */ +#define hipKernelNodeAttrValue hipLaunchAttributeValue + +/** + * Memset node params + */ +typedef struct HIP_MEMSET_NODE_PARAMS { + hipDeviceptr_t dst; ///< Destination pointer on device + size_t pitch; ///< Destination device pointer pitch. Unused if height equals 1 + unsigned int value; ///< Value of memset to be set + unsigned int elementSize; ///< Element in bytes. Must be 1, 2, or 4. + size_t width; ///< Width of a row + size_t height; ///< Number of rows +} HIP_MEMSET_NODE_PARAMS; + +/** + * Graph execution update result + */ +typedef enum hipGraphExecUpdateResult { + hipGraphExecUpdateSuccess = 0x0, ///< The update succeeded + hipGraphExecUpdateError = 0x1, ///< The update failed for an unexpected reason which is described + ///< in the return value of the function + hipGraphExecUpdateErrorTopologyChanged = 0x2, ///< The update failed because the topology changed + hipGraphExecUpdateErrorNodeTypeChanged = 0x3, ///< The update failed because a node type changed + hipGraphExecUpdateErrorFunctionChanged = + 0x4, ///< The update failed because the function of a kernel node changed + hipGraphExecUpdateErrorParametersChanged = + 0x5, ///< The update failed because the parameters changed in a way that is not supported + hipGraphExecUpdateErrorNotSupported = + 0x6, ///< The update failed because something about the node is not supported + hipGraphExecUpdateErrorUnsupportedFunctionChange = 0x7 +} hipGraphExecUpdateResult; + +typedef enum hipStreamCaptureMode { + hipStreamCaptureModeGlobal = 0, + hipStreamCaptureModeThreadLocal, + hipStreamCaptureModeRelaxed +} hipStreamCaptureMode; +typedef enum hipStreamCaptureStatus { + hipStreamCaptureStatusNone = 0, ///< Stream is not capturing + hipStreamCaptureStatusActive, ///< Stream is actively capturing + hipStreamCaptureStatusInvalidated ///< Stream is part of a capture sequence that has been + ///< invalidated, but not terminated +} hipStreamCaptureStatus; + +typedef enum hipStreamUpdateCaptureDependenciesFlags { + hipStreamAddCaptureDependencies = 0, ///< Add new nodes to the dependency set + hipStreamSetCaptureDependencies, ///< Replace the dependency set with the new nodes +} hipStreamUpdateCaptureDependenciesFlags; + +typedef enum hipGraphMemAttributeType { + hipGraphMemAttrUsedMemCurrent = 0, ///< Amount of memory, in bytes, currently associated with graphs + hipGraphMemAttrUsedMemHigh, ///< High watermark of memory, in bytes, associated with graphs since the last time. + hipGraphMemAttrReservedMemCurrent, ///< Amount of memory, in bytes, currently allocated for graphs. + hipGraphMemAttrReservedMemHigh, ///< High watermark of memory, in bytes, currently allocated for graphs +}hipGraphMemAttributeType; +typedef enum hipUserObjectFlags { + hipUserObjectNoDestructorSync = 0x1, ///< Destructor execution is not synchronized. +} hipUserObjectFlags; + +typedef enum hipUserObjectRetainFlags { + hipGraphUserObjectMove = 0x1, ///< Add new reference or retain. +} hipUserObjectRetainFlags; + +typedef enum hipGraphInstantiateFlags { + hipGraphInstantiateFlagAutoFreeOnLaunch = + 1, ///< Automatically free memory allocated in a graph before relaunching. + hipGraphInstantiateFlagUpload = + 2, ///< Automatically upload the graph after instantiaton. + hipGraphInstantiateFlagDeviceLaunch = + 4, ///< Instantiate the graph to be launchable from the device. + hipGraphInstantiateFlagUseNodePriority = + 8, ///< Run the graph using the per-node priority attributes rather than the priority of the stream it is launched into. +} hipGraphInstantiateFlags; + +enum hipGraphDebugDotFlags { + hipGraphDebugDotFlagsVerbose = 1 + << 0, /**< Output all debug data as if every debug flag is enabled */ + hipGraphDebugDotFlagsKernelNodeParams = 1 << 2, /**< Adds hipKernelNodeParams to output */ + hipGraphDebugDotFlagsMemcpyNodeParams = 1 << 3, /**< Adds hipMemcpy3DParms to output */ + hipGraphDebugDotFlagsMemsetNodeParams = 1 << 4, /**< Adds hipMemsetParams to output */ + hipGraphDebugDotFlagsHostNodeParams = 1 << 5, /**< Adds hipHostNodeParams to output */ + hipGraphDebugDotFlagsEventNodeParams = 1 + << 6, /**< Adds hipEvent_t handle from record and wait nodes to output */ + hipGraphDebugDotFlagsExtSemasSignalNodeParams = 1 + << 7, /**< Adds hipExternalSemaphoreSignalNodeParams values to output */ + hipGraphDebugDotFlagsExtSemasWaitNodeParams = 1 + << 8, /**< Adds hipExternalSemaphoreWaitNodeParams to output */ + hipGraphDebugDotFlagsKernelNodeAttributes = 1 + << 9, /**< Adds hipKernelNodeAttrID values to output */ + hipGraphDebugDotFlagsHandles = 1 + << 10 /**< Adds node handles and every kernel function handle to output */ +}; + +/** +* hipGraphInstantiateWithParams results +*/ +typedef enum hipGraphInstantiateResult { + hipGraphInstantiateSuccess = 0, /**< Instantiation Success */ + hipGraphInstantiateError = 1, /**< Instantiation failed for an + unexpected reason which is described in the return value of the function */ + hipGraphInstantiateInvalidStructure = 2, /**< Instantiation failed due + to invalid structure, such as cycles */ + hipGraphInstantiateNodeOperationNotSupported = 3, /**< Instantiation for device launch failed + because the graph contained an unsupported operation */ + hipGraphInstantiateMultipleDevicesNotSupported = 4, /**< Instantiation for device launch failed + due to the nodes belonging to different contexts */ +}hipGraphInstantiateResult; + +/** + * Graph Instantiation parameters +*/ +typedef struct hipGraphInstantiateParams { + hipGraphNode_t errNode_out; /**< The node which caused instantiation to fail, if any*/ + unsigned long long flags; /**< Instantiation flags */ + hipGraphInstantiateResult result_out; /**< Whether instantiation was successful. + If it failed, the reason why */ + hipStream_t uploadStream; /**< Upload stream */ +} hipGraphInstantiateParams; + + +/** + * Memory allocation properties + */ +typedef struct hipMemAllocationProp { + hipMemAllocationType type; ///< Memory allocation type + hipMemAllocationHandleType requestedHandleType; ///< Requested handle type + hipMemLocation location; ///< Memory location + void* win32HandleMetaData; ///< Metadata for Win32 handles + struct { + unsigned char compressionType; ///< Compression type + unsigned char gpuDirectRDMACapable; ///< RDMA capable + unsigned short usage; ///< Usage + } allocFlags; +} hipMemAllocationProp; + +/** + * External semaphore signal node parameters + */ +typedef struct hipExternalSemaphoreSignalNodeParams { + ///< Array containing external semaphore handles. + hipExternalSemaphore_t* extSemArray; + ///< Array containing parameters of external signal semaphore. + const hipExternalSemaphoreSignalParams* paramsArray; + ///< Total number of handles and parameters contained in extSemArray and paramsArray. + unsigned int numExtSems; +} hipExternalSemaphoreSignalNodeParams; + +/** + * External semaphore wait node parameters + */ +typedef struct hipExternalSemaphoreWaitNodeParams { + ///< Array containing external semaphore handles. + hipExternalSemaphore_t* extSemArray; + ///< Array containing parameters of external wait semaphore. + const hipExternalSemaphoreWaitParams* paramsArray; + ///< Total number of handles and parameters contained in extSemArray and paramsArray. + unsigned int numExtSems; +} hipExternalSemaphoreWaitNodeParams; + +/** + * Generic handle for memory allocation + */ +typedef struct ihipMemGenericAllocationHandle* hipMemGenericAllocationHandle_t; + +/** + * Flags for granularity + */ +typedef enum hipMemAllocationGranularity_flags { + hipMemAllocationGranularityMinimum = 0x0, ///< Minimum granularity + hipMemAllocationGranularityRecommended = 0x1 ///< Recommended granularity for performance +} hipMemAllocationGranularity_flags; + +/** + * Memory handle type + */ +typedef enum hipMemHandleType { + hipMemHandleTypeGeneric = 0x0 ///< Generic handle type +} hipMemHandleType; + +/** + * Memory operation types + */ +typedef enum hipMemOperationType { + hipMemOperationTypeMap = 0x1, ///< Map operation + hipMemOperationTypeUnmap = 0x2 ///< Unmap operation +} hipMemOperationType; + +/** + * Subresource types for sparse arrays + */ +typedef enum hipArraySparseSubresourceType { + hipArraySparseSubresourceTypeSparseLevel = 0x0, ///< Sparse level + hipArraySparseSubresourceTypeMiptail = 0x1 ///< Miptail +} hipArraySparseSubresourceType; + +/** + * Map info for arrays + */ +typedef struct hipArrayMapInfo { + hipResourceType resourceType; ///< Resource type + union { + hipMipmappedArray mipmap; + hipArray_t array; + } resource; + hipArraySparseSubresourceType subresourceType; ///< Sparse subresource type + union { + struct { + unsigned int level; ///< For mipmapped arrays must be a valid mipmap level. For arrays must be zero + unsigned int layer; ///< For layered arrays must be a valid layer index. Otherwise, must be zero + unsigned int offsetX; ///< X offset in elements + unsigned int offsetY; ///< Y offset in elements + unsigned int offsetZ; ///< Z offset in elements + unsigned int extentWidth; ///< Width in elements + unsigned int extentHeight; ///< Height in elements + unsigned int extentDepth; ///< Depth in elements + } sparseLevel; + struct { + unsigned int layer; ///< For layered arrays must be a valid layer index. Otherwise, must be zero + unsigned long long offset; ///< Offset within mip tail + unsigned long long size; ///< Extent in bytes + } miptail; + } subresource; + hipMemOperationType memOperationType; ///< Memory operation type + hipMemHandleType memHandleType; ///< Memory handle type + union { + hipMemGenericAllocationHandle_t memHandle; + } memHandle; + unsigned long long offset; ///< Offset within the memory + unsigned int deviceBitMask; ///< Device ordinal bit mask + unsigned int flags; ///< flags for future use, must be zero now. + unsigned int reserved[2]; ///< Reserved for future use, must be zero now. +} hipArrayMapInfo; + +/** + * Memcpy node params + */ +typedef struct hipMemcpyNodeParams { + int flags; ///< Must be zero. + int reserved[3]; ///< Must be zero. + hipMemcpy3DParms copyParams; ///< Params set for the memory copy. +} hipMemcpyNodeParams; + +/** + * Child graph node params + */ +typedef struct hipChildGraphNodeParams { + hipGraph_t graph; ///< Either the child graph to clone into the node, or + ///< a handle to the graph possesed by the node used during query +} hipChildGraphNodeParams; + +/** + * Event record node params + */ +typedef struct hipEventWaitNodeParams { + hipEvent_t event; ///< Event to wait on +} hipEventWaitNodeParams; + +/** + * Event record node params + */ +typedef struct hipEventRecordNodeParams { + hipEvent_t event; ///< The event to be recorded when node executes +} hipEventRecordNodeParams; + +/** + * Memory free node params + */ +typedef struct hipMemFreeNodeParams { + void *dptr; ///< the pointer to be freed +} hipMemFreeNodeParams; + +/** + * Params for different graph nodes + */ +typedef struct hipGraphNodeParams { + hipGraphNodeType type; + int reserved0[3]; + union { + long long reserved1[29]; + hipKernelNodeParams kernel; + hipMemcpyNodeParams memcpy; + hipMemsetParams memset; + hipHostNodeParams host; + hipChildGraphNodeParams graph; + hipEventWaitNodeParams eventWait; + hipEventRecordNodeParams eventRecord; + hipExternalSemaphoreSignalNodeParams extSemSignal; + hipExternalSemaphoreWaitNodeParams extSemWait; + hipMemAllocNodeParams alloc; + hipMemFreeNodeParams free; + }; + + long long reserved2; +} hipGraphNodeParams; + +/** + * This port activates when the kernel has finished executing. + */ +#define hipGraphKernelNodePortDefault 0 + +/** + * This port activates when all blocks of the kernel have begun execution. + */ +#define hipGraphKernelNodePortLaunchCompletion 2 + +/** + * This port activates when all blocks of the kernel have performed + * hipTriggerProgrammaticLaunchCompletion() or have terminated. + * It must be used with edge type hipGraphDependencyTypeProgrammatic. + */ +#define hipGraphKernelNodePortProgrammatic 1 + +typedef enum hipGraphDependencyType { + hipGraphDependencyTypeDefault = 0, + hipGraphDependencyTypeProgrammatic = 1 +}hipGraphDependencyType; + +typedef struct hipGraphEdgeData { + unsigned char + from_port; ///< This indicates when the dependency is triggered from the upstream node on the + ///< edge. The meaning is specfic to the node type. A value of 0 in all cases + ///< means full completion of the upstream node, with memory visibility to the + ///< downstream node or portion thereof (indicated by to_port). Only kernel nodes + ///< define non-zero ports. A kernel node can use the following output port types: + ///< hipGraphKernelNodePortDefault, hipGraphKernelNodePortProgrammatic, or + ///< hipGraphKernelNodePortLaunchCompletion. + unsigned char reserved[5]; ///< These bytes are unused and must be zeroed + unsigned char + to_port; ///< Currently no node types define non-zero ports. This field must be set to zero. + unsigned char type; ///< This should be populated with a value from hipGraphDependencyType +} hipGraphEdgeData; + +// Doxygen end group GlobalDefs +/** +* @} +*/ +/** + * @defgroup API HIP API + * @{ + * + * Defines the HIP API. See the individual sections for more information. + */ +/** + * @defgroup Driver Initialization and Version + * @{ + * This section describes the initializtion and version functions of HIP runtime API. + * + */ +/** + * @brief Explicitly initializes the HIP runtime. + * + * @param [in] flags Initialization flag, should be zero. + * + * Most HIP APIs implicitly initialize the HIP runtime. + * This API provides control over the timing of the initialization. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +// TODO-ctx - more description on error codes. +hipError_t hipInit(unsigned int flags); + +/** + * @brief Returns the approximate HIP driver version. + * + * @param [out] driverVersion driver version + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning The HIP feature set does not correspond to an exact CUDA SDK driver revision. + * This function always set *driverVersion to 4 as an approximation though HIP supports + * some features which were introduced in later CUDA SDK revisions. + * HIP apps code should not rely on the driver revision number here and should + * use arch feature flags to test device capabilities or conditional compilation. + * + * @see hipRuntimeGetVersion + */ +hipError_t hipDriverGetVersion(int* driverVersion); +/** + * @brief Returns the approximate HIP Runtime version. + * + * @param [out] runtimeVersion HIP runtime version + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning The version definition of HIP runtime is different from CUDA. + * On AMD platform, the function returns HIP runtime version, + * while on NVIDIA platform, it returns CUDA runtime version. + * And there is no mapping/correlation between HIP version and CUDA version. + * + * @see hipDriverGetVersion + */ +hipError_t hipRuntimeGetVersion(int* runtimeVersion); +/** + * @brief Returns a handle to a compute device + * @param [out] device Handle of device + * @param [in] ordinal Device ordinal + * + * @returns #hipSuccess, #hipErrorInvalidDevice + */ +hipError_t hipDeviceGet(hipDevice_t* device, int ordinal); + +/** + * @brief Returns the compute capability of the device + * @param [out] major Major compute capability version number + * @param [out] minor Minor compute capability version number + * @param [in] device Device ordinal + * + * @returns #hipSuccess, #hipErrorInvalidDevice + */ +hipError_t hipDeviceComputeCapability(int* major, int* minor, hipDevice_t device); +/** + * @brief Returns an identifer string for the device. + * @param [out] name String of the device name + * @param [in] len Maximum length of string to store in device name + * @param [in] device Device ordinal + * + * @returns #hipSuccess, #hipErrorInvalidDevice + */ +hipError_t hipDeviceGetName(char* name, int len, hipDevice_t device); +/** + * @brief Returns an UUID for the device.[BETA] + * @param [out] uuid UUID for the device + * @param [in] device device ordinal + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue, #hipErrorNotInitialized, + * #hipErrorDeinitialized + */ +hipError_t hipDeviceGetUuid(hipUUID* uuid, hipDevice_t device); +/** + * @brief Returns a value for attribute of link between two devices + * @param [out] value Pointer of the value for the attrubute + * @param [in] attr enum of hipDeviceP2PAttr to query + * @param [in] srcDevice The source device of the link + * @param [in] dstDevice The destination device of the link + * + * @returns #hipSuccess, #hipErrorInvalidDevice + */ +hipError_t hipDeviceGetP2PAttribute(int* value, hipDeviceP2PAttr attr, + int srcDevice, int dstDevice); +/** + * @brief Returns a PCI Bus Id string for the device, overloaded to take int device ID. + * @param [out] pciBusId The string of PCI Bus Id format for the device + * @param [in] len Maximum length of string + * @param [in] device The device ordinal + * + * @returns #hipSuccess, #hipErrorInvalidDevice + */ +hipError_t hipDeviceGetPCIBusId(char* pciBusId, int len, int device); +/** + * @brief Returns a handle to a compute device. + * @param [out] device The handle of the device + * @param [in] pciBusId The string of PCI Bus Id for the device + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + */ +hipError_t hipDeviceGetByPCIBusId(int* device, const char* pciBusId); +/** + * @brief Returns the total amount of memory on the device. + * @param [out] bytes The size of memory in bytes, on the device + * @param [in] device The ordinal of the device + * + * @returns #hipSuccess, #hipErrorInvalidDevice + */ +hipError_t hipDeviceTotalMem(size_t* bytes, hipDevice_t device); +// doxygen end initialization +/** + * @} + */ +/** + * @defgroup Device Device Management + * @{ + * This section describes the device management functions of HIP runtime API. + */ +/** + * @brief Waits on all active streams on current device + * + * When this command is invoked, the host thread gets blocked until all the commands associated + * with streams associated with the device. HIP does not support multiple blocking modes (yet!). + * + * @returns #hipSuccess + * + * @see hipSetDevice, hipDeviceReset + */ +hipError_t hipDeviceSynchronize(void); +/** + * @brief The state of current device is discarded and updated to a fresh state. + * + * Calling this function deletes all streams created, memory allocated, kernels running, events + * created. Make sure that no other thread is using the device or streams, memory, kernels, events + * associated with the current device. + * + * @returns #hipSuccess + * + * @see hipDeviceSynchronize + */ +hipError_t hipDeviceReset(void); +/** + * @brief Set default device to be used for subsequent hip API calls from this thread. + * + * @param[in] deviceId Valid device in range 0...hipGetDeviceCount(). + * + * Sets @p device as the default device for the calling host thread. Valid device id's are 0... + * (hipGetDeviceCount()-1). + * + * Many HIP APIs implicitly use the "default device" : + * + * - Any device memory subsequently allocated from this host thread (using hipMalloc) will be + * allocated on device. + * - Any streams or events created from this host thread will be associated with device. + * - Any kernels launched from this host thread (using hipLaunchKernel) will be executed on device + * (unless a specific stream is specified, in which case the device associated with that stream will + * be used). + * + * This function may be called from any host thread. Multiple host threads may use the same device. + * This function does no synchronization with the previous or new device, and has very little + * runtime overhead. Applications can use hipSetDevice to quickly switch the default device before + * making a HIP runtime call which uses the default device. + * + * The default device is stored in thread-local-storage for each thread. + * Thread-pool implementations may inherit the default device of the previous thread. A good + * practice is to always call hipSetDevice at the start of HIP coding sequency to establish a known + * standard device. + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorNoDevice + * + * @see #hipGetDevice, #hipGetDeviceCount + */ +hipError_t hipSetDevice(int deviceId); +/** + * @brief Set a list of devices that can be used. + * + * @param[in] device_arr List of devices to try + * @param[in] len Number of devices in specified list + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @see #hipGetDevice, #hipGetDeviceCount. #hipSetDevice. #hipGetDeviceProperties. #hipSetDeviceFlags. #hipChooseDevice + * + * */ +hipError_t hipSetValidDevices(int* device_arr, int len); +/** + * @brief Return the default device id for the calling host thread. + * + * @param [out] deviceId *device is written with the default device + * + * HIP maintains an default device for each thread using thread-local-storage. + * This device is used implicitly for HIP runtime APIs called by this thread. + * hipGetDevice returns in * @p device the default device for the calling host thread. + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @see hipSetDevice, hipGetDevicesizeBytes + */ +hipError_t hipGetDevice(int* deviceId); +/** + * @brief Return number of compute-capable devices. + * + * @param [out] count Returns number of compute-capable devices. + * + * @returns #hipSuccess, #hipErrorNoDevice + * + * + * Returns in @p *count the number of devices that have ability to run compute commands. If there + * are no such devices, then @ref hipGetDeviceCount will return #hipErrorNoDevice. If 1 or more + * devices can be found, then hipGetDeviceCount returns #hipSuccess. + */ +hipError_t hipGetDeviceCount(int* count); +/** + * @brief Query for a specific device attribute. + * + * @param [out] pi pointer to value to return + * @param [in] attr attribute to query + * @param [in] deviceId which device to query for information + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + */ +hipError_t hipDeviceGetAttribute(int* pi, hipDeviceAttribute_t attr, int deviceId); +/** + * @brief Returns the default memory pool of the specified device + * + * @param [out] mem_pool Default memory pool to return + * @param [in] device Device index for query the default memory pool + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipDeviceGetDefaultMemPool, hipMallocAsync, hipMemPoolTrimTo, hipMemPoolGetAttribute, + * hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDeviceGetDefaultMemPool(hipMemPool_t* mem_pool, int device); +/** + * @brief Sets the current memory pool of a device + * + * The memory pool must be local to the specified device. + * @p hipMallocAsync allocates from the current mempool of the provided stream's device. + * By default, a device's current memory pool is its default memory pool. + * + * @note Use @p hipMallocFromPoolAsync for asynchronous memory allocations from a device + * different than the one the stream runs on. + * + * @param [in] device Device index for the update + * @param [in] mem_pool Memory pool for update as the current on the specified device + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidDevice, #hipErrorNotSupported + * + * @see hipDeviceGetDefaultMemPool, hipMallocAsync, hipMemPoolTrimTo, hipMemPoolGetAttribute, + * hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDeviceSetMemPool(int device, hipMemPool_t mem_pool); +/** + * @brief Gets the current memory pool for the specified device + * + * Returns the last pool provided to @p hipDeviceSetMemPool for this device + * or the device's default memory pool if @p hipDeviceSetMemPool has never been called. + * By default the current mempool is the default mempool for a device, + * otherwise the returned pool must have been set with @p hipDeviceSetMemPool. + * + * @param [out] mem_pool Current memory pool on the specified device + * @param [in] device Device index to query the current memory pool + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipDeviceGetDefaultMemPool, hipMallocAsync, hipMemPoolTrimTo, hipMemPoolGetAttribute, + * hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDeviceGetMemPool(hipMemPool_t* mem_pool, int device); +/** + * @brief Returns device properties. + * + * @param [out] prop written with device properties + * @param [in] deviceId which device to query for information + * + * @return #hipSuccess, #hipErrorInvalidDevice + * @bug HCC always returns 0 for maxThreadsPerMultiProcessor + * @bug HCC always returns 0 for regsPerBlock + * @bug HCC always returns 0 for l2CacheSize + * + * Populates hipGetDeviceProperties with information for the specified device. + */ +hipError_t hipGetDeviceProperties(hipDeviceProp_t* prop, int deviceId); +/** + * @brief Set L1/Shared cache partition. + * + * @param [in] cacheConfig Cache configuration + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorNotSupported + * + * Note: AMD devices do not support reconfigurable cache. This API is not implemented + * on AMD platform. If the function is called, it will return hipErrorNotSupported. + * + */ +hipError_t hipDeviceSetCacheConfig(hipFuncCache_t cacheConfig); +/** + * @brief Get Cache configuration for a specific Device + * + * @param [out] cacheConfig Pointer of cache configuration + * + * @returns #hipSuccess, #hipErrorNotInitialized + * Note: AMD devices do not support reconfigurable cache. This hint is ignored + * on these architectures. + * + */ +hipError_t hipDeviceGetCacheConfig(hipFuncCache_t* cacheConfig); +/** + * @brief Gets resource limits of current device + * + * The function queries the size of limit value, as required by the input enum value hipLimit_t, + * which can be either #hipLimitStackSize, or #hipLimitMallocHeapSize. Any other input as + * default, the function will return #hipErrorUnsupportedLimit. + * + * @param [out] pValue Returns the size of the limit in bytes + * @param [in] limit The limit to query + * + * @returns #hipSuccess, #hipErrorUnsupportedLimit, #hipErrorInvalidValue + * + */ +hipError_t hipDeviceGetLimit(size_t* pValue, enum hipLimit_t limit); +/** + * @brief Sets resource limits of current device. + * + * As the input enum limit, + * #hipLimitStackSize sets the limit value of the stack size on the current GPU device, per thread. + * The limit size can get via hipDeviceGetLimit. The size is in units of 256 dwords, up to the limit + * (128K - 16). + * + * #hipLimitMallocHeapSize sets the limit value of the heap used by the malloc()/free() + * calls. For limit size, use the #hipDeviceGetLimit API. + * + * Any other input as default, the funtion will return hipErrorUnsupportedLimit. + * + * @param [in] limit Enum of hipLimit_t to set + * @param [in] value The size of limit value in bytes + * + * @returns #hipSuccess, #hipErrorUnsupportedLimit, #hipErrorInvalidValue + * + */ +hipError_t hipDeviceSetLimit ( enum hipLimit_t limit, size_t value ); +/** + * @brief Returns bank width of shared memory for current device + * + * @param [out] pConfig The pointer of the bank width for shared memory + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + * + * Note: AMD devices and some Nvidia GPUS do not support shared cache banking, and the hint is + * ignored on those architectures. + * + */ +hipError_t hipDeviceGetSharedMemConfig(hipSharedMemConfig* pConfig); +/** + * @brief Gets the flags set for current device + * + * @param [out] flags Pointer of the flags + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + */ +hipError_t hipGetDeviceFlags(unsigned int* flags); +/** + * @brief The bank width of shared memory on current device is set + * + * @param [in] config Configuration for the bank width of shared memory + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + * + * Note: AMD devices and some Nvidia GPUS do not support shared cache banking, and the hint is + * ignored on those architectures. + * + */ +hipError_t hipDeviceSetSharedMemConfig(hipSharedMemConfig config); +/** + * @brief The current device behavior is changed according the flags passed. + * + * @param [in] flags Flag to set on the current device + * + * The schedule flags impact how HIP waits for the completion of a command running on a device. + * hipDeviceScheduleSpin : HIP runtime will actively spin in the thread which submitted the + * work until the command completes. This offers the lowest latency, but will consume a CPU core + * and may increase power. hipDeviceScheduleYield : The HIP runtime will yield the CPU to + * system so that other tasks can use it. This may increase latency to detect the completion but + * will consume less power and is friendlier to other tasks in the system. + * hipDeviceScheduleBlockingSync : On ROCm platform, this is a synonym for hipDeviceScheduleYield. + * hipDeviceScheduleAuto : Use a hueristic to select between Spin and Yield modes. If the + * number of HIP contexts is greater than the number of logical processors in the system, use Spin + * scheduling. Else use Yield scheduling. + * + * + * hipDeviceMapHost : Allow mapping host memory. On ROCM, this is always allowed and + * the flag is ignored. hipDeviceLmemResizeToMax : @warning ROCm silently ignores this flag. + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorSetOnActiveProcess + * + * + */ +hipError_t hipSetDeviceFlags(unsigned flags); +/** + * @brief Device which matches hipDeviceProp_t is returned + * + * @param [out] device Pointer of the device + * @param [in] prop Pointer of the properties + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipChooseDevice(int* device, const hipDeviceProp_t* prop); +/** + * @brief Returns the link type and hop count between two devices + * + * @param [in] device1 Ordinal for device1 + * @param [in] device2 Ordinal for device2 + * @param [out] linktype Returns the link type (See hsa_amd_link_info_type_t) between the two devices + * @param [out] hopcount Returns the hop count between the two devices + * + * Queries and returns the HSA link type and the hop count between the two specified devices. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipExtGetLinkTypeAndHopCount(int device1, int device2, uint32_t* linktype, uint32_t* hopcount); +// TODO: implement IPC apis +/** + * @brief Gets an interprocess memory handle for an existing device memory + * allocation + * + * Takes a pointer to the base of an existing device memory allocation created + * with hipMalloc and exports it for use in another process. This is a + * lightweight operation and may be called multiple times on an allocation + * without adverse effects. + * + * If a region of memory is freed with hipFree and a subsequent call + * to hipMalloc returns memory with the same device address, + * hipIpcGetMemHandle will return a unique handle for the + * new memory. + * + * @param handle - Pointer to user allocated hipIpcMemHandle to return + * the handle in. + * @param devPtr - Base pointer to previously allocated device memory + * + * @returns #hipSuccess, #hipErrorInvalidHandle, #hipErrorOutOfMemory, #hipErrorMapFailed + * + * @note This IPC memory related feature API on Windows may behave differently from Linux. + * + */ +hipError_t hipIpcGetMemHandle(hipIpcMemHandle_t* handle, void* devPtr); +/** + * @brief Opens an interprocess memory handle exported from another process + * and returns a device pointer usable in the local process. + * + * Maps memory exported from another process with hipIpcGetMemHandle into + * the current device address space. For contexts on different devices + * hipIpcOpenMemHandle can attempt to enable peer access between the + * devices as if the user called hipDeviceEnablePeerAccess. This behavior is + * controlled by the hipIpcMemLazyEnablePeerAccess flag. + * hipDeviceCanAccessPeer can determine if a mapping is possible. + * + * Contexts that may open hipIpcMemHandles are restricted in the following way. + * hipIpcMemHandles from each device in a given process may only be opened + * by one context per device per other process. + * + * Memory returned from hipIpcOpenMemHandle must be freed with + * hipIpcCloseMemHandle. + * + * Calling hipFree on an exported memory region before calling + * hipIpcCloseMemHandle in the importing context will result in undefined + * behavior. + * + * @param devPtr - Returned device pointer + * @param handle - hipIpcMemHandle to open + * @param flags - Flags for this operation. Must be specified as hipIpcMemLazyEnablePeerAccess + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidContext, + * #hipErrorInvalidDevicePointer + * + * @note During multiple processes, using the same memory handle opened by the current context, + * there is no guarantee that the same device poiter will be returned in @p *devPtr. + * This is diffrent from CUDA. + * @note This IPC memory related feature API on Windows may behave differently from Linux. + * + */ +hipError_t hipIpcOpenMemHandle(void** devPtr, hipIpcMemHandle_t handle, unsigned int flags); +/** + * @brief Close memory mapped with hipIpcOpenMemHandle + * + * Unmaps memory returnd by hipIpcOpenMemHandle. The original allocation + * in the exporting process as well as imported mappings in other processes + * will be unaffected. + * + * Any resources used to enable peer access will be freed if this is the + * last mapping using them. + * + * @param devPtr - Device pointer returned by hipIpcOpenMemHandle + * + * @returns #hipSuccess, #hipErrorMapFailed, #hipErrorInvalidHandle + * + * @note This IPC memory related feature API on Windows may behave differently from Linux. + * + */ +hipError_t hipIpcCloseMemHandle(void* devPtr); + +/** + * @brief Gets an opaque interprocess handle for an event. + * + * This opaque handle may be copied into other processes and opened with hipIpcOpenEventHandle. + * Then hipEventRecord, hipEventSynchronize, hipStreamWaitEvent and hipEventQuery may be used in + * either process. Operations on the imported event after the exported event has been freed with hipEventDestroy + * will result in undefined behavior. + * + * @param[out] handle Pointer to hipIpcEventHandle to return the opaque event handle + * @param[in] event Event allocated with hipEventInterprocess and hipEventDisableTiming flags + * + * @returns #hipSuccess, #hipErrorInvalidConfiguration, #hipErrorInvalidValue + * + * @note This IPC event related feature API is currently applicable on Linux. + * + */ +hipError_t hipIpcGetEventHandle(hipIpcEventHandle_t* handle, hipEvent_t event); + +/** + * @brief Opens an interprocess event handles. + * + * Opens an interprocess event handle exported from another process with hipIpcGetEventHandle. The returned + * hipEvent_t behaves like a locally created event with the hipEventDisableTiming flag specified. This event + * need be freed with hipEventDestroy. Operations on the imported event after the exported event has been freed + * with hipEventDestroy will result in undefined behavior. If the function is called within the same process where + * handle is returned by hipIpcGetEventHandle, it will return hipErrorInvalidContext. + * + * @param[out] event Pointer to hipEvent_t to return the event + * @param[in] handle The opaque interprocess handle to open + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidContext + * + * @note This IPC event related feature API is currently applicable on Linux. + * + */ +hipError_t hipIpcOpenEventHandle(hipEvent_t* event, hipIpcEventHandle_t handle); + +// end doxygen Device +/** + * @} + */ +/** + * + * @defgroup Execution Execution Control + * @{ + * This section describes the execution control functions of HIP runtime API. + * + */ +/** + * @brief Set attribute for a specific function + * + * @param [in] func Pointer of the function + * @param [in] attr Attribute to set + * @param [in] value Value to set + * + * @returns #hipSuccess, #hipErrorInvalidDeviceFunction, #hipErrorInvalidValue + * + * Note: AMD devices and some Nvidia GPUS do not support shared cache banking, and the hint is + * ignored on those architectures. + * + */ +hipError_t hipFuncSetAttribute(const void* func, hipFuncAttribute attr, int value); +/** + * @brief Set Cache configuration for a specific function + * + * @param [in] func Pointer of the function. + * @param [in] config Configuration to set. + * + * @returns #hipSuccess, #hipErrorNotInitialized + * Note: AMD devices and some Nvidia GPUS do not support reconfigurable cache. This hint is ignored + * on those architectures. + * + */ +hipError_t hipFuncSetCacheConfig(const void* func, hipFuncCache_t config); +/** + * @brief Set shared memory configuation for a specific function + * + * @param [in] func Pointer of the function + * @param [in] config Configuration + * + * @returns #hipSuccess, #hipErrorInvalidDeviceFunction, #hipErrorInvalidValue + * + * Note: AMD devices and some Nvidia GPUS do not support shared cache banking, and the hint is + * ignored on those architectures. + * + */ +hipError_t hipFuncSetSharedMemConfig(const void* func, hipSharedMemConfig config); +//doxygen end execution +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Error Error Handling + * @{ + * This section describes the error handling functions of HIP runtime API. + */ +/** + * @brief Return last error returned by any HIP runtime API call and resets the stored error code to + * #hipSuccess + * + * @returns return code from last HIP called from the active host thread + * + * Returns the last error that has been returned by any of the runtime calls in the same host + * thread, and then resets the saved error to #hipSuccess. + * + * @see hipGetErrorString, hipGetLastError, hipPeakAtLastError, hipError_t + */ +hipError_t hipGetLastError(void); + +/** + * @brief Return last error returned by any HIP runtime API call and resets the stored error code to + * #hipSuccess + * + * @returns return code from last HIP called from the active host thread + * + * Returns the last error that has been returned by any of the runtime calls in the same host + * thread, and then resets the saved error to #hipSuccess. + * + * @see hipGetErrorString, hipGetLastError, hipPeakAtLastError, hipError_t + */ +hipError_t hipExtGetLastError(void); + +/** + * @brief Return last error returned by any HIP runtime API call. + * + * @return #hipSuccess + * + * Returns the last error that has been returned by any of the runtime calls in the same host + * thread. Unlike hipGetLastError, this function does not reset the saved error code. + * + * @see hipGetErrorString, hipGetLastError, hipPeakAtLastError, hipError_t + */ +hipError_t hipPeekAtLastError(void); +/** + * @brief Return hip error as text string form. + * + * @param hip_error Error code to convert to name. + * @return const char pointer to the NULL-terminated error name + * + * @see hipGetErrorString, hipGetLastError, hipPeakAtLastError, hipError_t + */ +const char* hipGetErrorName(hipError_t hip_error); +/** + * @brief Return handy text string message to explain the error which occurred + * + * @param hipError Error code to convert to string. + * @return const char pointer to the NULL-terminated error string + * + * @see hipGetErrorName, hipGetLastError, hipPeakAtLastError, hipError_t + */ +const char* hipGetErrorString(hipError_t hipError); +/** + * @brief Return hip error as text string form. + * + * @param [in] hipError Error code to convert to string. + * @param [out] errorString char pointer to the NULL-terminated error string + * @return #hipSuccess, #hipErrorInvalidValue + * + * @see hipGetErrorName, hipGetLastError, hipPeakAtLastError, hipError_t + */ +hipError_t hipDrvGetErrorName(hipError_t hipError, const char** errorString); +/** + * @brief Return handy text string message to explain the error which occurred + * + * @param [in] hipError Error code to convert to string. + * @param [out] errorString char pointer to the NULL-terminated error string + * @return #hipSuccess, #hipErrorInvalidValue + * + * @see hipGetErrorName, hipGetLastError, hipPeakAtLastError, hipError_t + */ +hipError_t hipDrvGetErrorString(hipError_t hipError, const char** errorString); +// end doxygen Error +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Stream Stream Management + * @{ + * This section describes the stream management functions of HIP runtime API. + * The following Stream APIs are not (yet) supported in HIP: + * - hipStreamAttachMemAsync is a nop + */ + +/** + * @brief Create an asynchronous stream. + * + * @param[in, out] stream Valid pointer to hipStream_t. This function writes the memory with the + * newly created stream. + * @return #hipSuccess, #hipErrorInvalidValue + * + * Create a new asynchronous stream. @p stream returns an opaque handle that can be used to + * reference the newly created stream in subsequent hipStream* commands. The stream is allocated on + * the heap and will remain allocated even if the handle goes out-of-scope. To release the memory + * used by the stream, application must call hipStreamDestroy. + * + * @return #hipSuccess, #hipErrorInvalidValue + * + * @see hipStreamCreateWithFlags, hipStreamCreateWithPriority, hipStreamSynchronize, hipStreamWaitEvent, hipStreamDestroy + */ +hipError_t hipStreamCreate(hipStream_t* stream); +/** + * @brief Create an asynchronous stream. + * + * @param[in, out] stream Pointer to new stream + * @param[in ] flags to control stream creation. + * @return #hipSuccess, #hipErrorInvalidValue + * + * Create a new asynchronous stream. @p stream returns an opaque handle that can be used to + * reference the newly created stream in subsequent hipStream* commands. The stream is allocated on + * the heap and will remain allocated even if the handle goes out-of-scope. To release the memory + * used by the stream, application must call hipStreamDestroy. Flags controls behavior of the + * stream. See #hipStreamDefault, #hipStreamNonBlocking. + * + * + * @see hipStreamCreate, hipStreamCreateWithPriority, hipStreamSynchronize, hipStreamWaitEvent, hipStreamDestroy + */ +hipError_t hipStreamCreateWithFlags(hipStream_t* stream, unsigned int flags); +/** + * @brief Create an asynchronous stream with the specified priority. + * + * @param[in, out] stream Pointer to new stream + * @param[in ] flags to control stream creation. + * @param[in ] priority of the stream. Lower numbers represent higher priorities. + * @return #hipSuccess, #hipErrorInvalidValue + * + * Create a new asynchronous stream with the specified priority. @p stream returns an opaque handle + * that can be used to reference the newly created stream in subsequent hipStream* commands. The + * stream is allocated on the heap and will remain allocated even if the handle goes out-of-scope. + * To release the memory used by the stream, application must call hipStreamDestroy. Flags controls + * behavior of the stream. See #hipStreamDefault, #hipStreamNonBlocking. + * + * + * @see hipStreamCreate, hipStreamSynchronize, hipStreamWaitEvent, hipStreamDestroy + */ +hipError_t hipStreamCreateWithPriority(hipStream_t* stream, unsigned int flags, int priority); +/** + * @brief Returns numerical values that correspond to the least and greatest stream priority. + * + * @param[in, out] leastPriority pointer in which value corresponding to least priority is returned. + * @param[in, out] greatestPriority pointer in which value corresponding to greatest priority is returned. + * @returns #hipSuccess + * + * Returns in *leastPriority and *greatestPriority the numerical values that correspond to the least + * and greatest stream priority respectively. Stream priorities follow a convention where lower numbers + * imply greater priorities. The range of meaningful stream priorities is given by + * [*greatestPriority, *leastPriority]. If the user attempts to create a stream with a priority value + * that is outside the meaningful range as specified by this API, the priority is automatically + * clamped to within the valid range. + */ +hipError_t hipDeviceGetStreamPriorityRange(int* leastPriority, int* greatestPriority); +/** + * @brief Destroys the specified stream. + * + * @param[in] stream stream identifier. + * @return #hipSuccess #hipErrorInvalidHandle + * + * Destroys the specified stream. + * + * If commands are still executing on the specified stream, some may complete execution before the + * queue is deleted. + * + * The queue may be destroyed while some commands are still inflight, or may wait for all commands + * queued to the stream before destroying it. + * + * @see hipStreamCreate, hipStreamCreateWithFlags, hipStreamCreateWithPriority, hipStreamQuery, + * hipStreamWaitEvent, hipStreamSynchronize + */ +hipError_t hipStreamDestroy(hipStream_t stream); +/** + * @brief Return #hipSuccess if all of the operations in the specified @p stream have completed, or + * #hipErrorNotReady if not. + * + * @param[in] stream stream to query + * + * @return #hipSuccess, #hipErrorNotReady, #hipErrorInvalidHandle + * + * This is thread-safe and returns a snapshot of the current state of the queue. However, if other + * host threads are sending work to the stream, the status may change immediately after the function + * is called. It is typically used for debug. + * + * @see hipStreamCreate, hipStreamCreateWithFlags, hipStreamCreateWithPriority, hipStreamWaitEvent, + * hipStreamSynchronize, hipStreamDestroy + */ +hipError_t hipStreamQuery(hipStream_t stream); +/** + * @brief Wait for all commands in stream to complete. + * + * @param[in] stream stream identifier. + * + * @return #hipSuccess, #hipErrorInvalidHandle + * + * This command is host-synchronous : the host will block until the specified stream is empty. + * + * This command follows standard null-stream semantics. Specifically, specifying the null stream + * will cause the command to wait for other streams on the same device to complete all pending + * operations. + * + * This command honors the hipDeviceLaunchBlocking flag, which controls whether the wait is active + * or blocking. + * + * @see hipStreamCreate, hipStreamCreateWithFlags, hipStreamCreateWithPriority, hipStreamWaitEvent, + * hipStreamDestroy + * + */ +hipError_t hipStreamSynchronize(hipStream_t stream); +/** + * @brief Make the specified compute stream wait for an event + * + * @param[in] stream stream to make wait. + * @param[in] event event to wait on + * @param[in] flags control operation [must be 0] + * + * @return #hipSuccess, #hipErrorInvalidHandle + * + * This function inserts a wait operation into the specified stream. + * All future work submitted to @p stream will wait until @p event reports completion before + * beginning execution. + * + * This function only waits for commands in the current stream to complete. Notably, this function + * does not implicitly wait for commands in the default stream to complete, even if the specified + * stream is created with hipStreamNonBlocking = 0. + * + * @see hipStreamCreate, hipStreamCreateWithFlags, hipStreamCreateWithPriority, hipStreamSynchronize, hipStreamDestroy + */ +hipError_t hipStreamWaitEvent(hipStream_t stream, hipEvent_t event, unsigned int flags __dparm(0)); +/** + * @brief Return flags associated with this stream. + * + * @param[in] stream stream to be queried + * @param[in,out] flags Pointer to an unsigned integer in which the stream's flags are returned + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidHandle + * + * @returns #hipSuccess #hipErrorInvalidValue #hipErrorInvalidHandle + * + * Return flags associated with this stream in *@p flags. + * + * @see hipStreamCreateWithFlags + */ +hipError_t hipStreamGetFlags(hipStream_t stream, unsigned int* flags); +/** + * @brief Query the priority of a stream. + * + * @param[in] stream stream to be queried + * @param[in,out] priority Pointer to an unsigned integer in which the stream's priority is returned + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidHandle + * + * @returns #hipSuccess #hipErrorInvalidValue #hipErrorInvalidHandle + * + * Query the priority of a stream. The priority is returned in in priority. + * + * @see hipStreamCreateWithFlags + */ +hipError_t hipStreamGetPriority(hipStream_t stream, int* priority); +/** + * @brief Get the device assocaited with the stream + * + * @param[in] stream stream to be queried + * @param[out] device device associated with the stream + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorContextIsDestroyed, #hipErrorInvalidHandle, + * #hipErrorNotInitialized, #hipErrorDeinitialized, #hipErrorInvalidContext + * + * @see hipStreamCreate, hipStreamDestroy, hipDeviceGetStreamPriorityRange + */ +hipError_t hipStreamGetDevice(hipStream_t stream, hipDevice_t* device); +/** + * @brief Create an asynchronous stream with the specified CU mask. + * + * @param[in, out] stream Pointer to new stream + * @param[in ] cuMaskSize Size of CU mask bit array passed in. + * @param[in ] cuMask Bit-vector representing the CU mask. Each active bit represents using one CU. + * The first 32 bits represent the first 32 CUs, and so on. If its size is greater than physical + * CU number (i.e., multiProcessorCount member of hipDeviceProp_t), the extra elements are ignored. + * It is user's responsibility to make sure the input is meaningful. + * @return #hipSuccess, #hipErrorInvalidHandle, #hipErrorInvalidValue + * + * Create a new asynchronous stream with the specified CU mask. @p stream returns an opaque handle + * that can be used to reference the newly created stream in subsequent hipStream* commands. The + * stream is allocated on the heap and will remain allocated even if the handle goes out-of-scope. + * To release the memory used by the stream, application must call hipStreamDestroy. + * + * + * @see hipStreamCreate, hipStreamSynchronize, hipStreamWaitEvent, hipStreamDestroy + */ +hipError_t hipExtStreamCreateWithCUMask(hipStream_t* stream, uint32_t cuMaskSize, const uint32_t* cuMask); +/** + * @brief Get CU mask associated with an asynchronous stream + * + * @param[in] stream stream to be queried + * @param[in] cuMaskSize number of the block of memories (uint32_t *) allocated by user + * @param[out] cuMask Pointer to a pre-allocated block of memories (uint32_t *) in which + * the stream's CU mask is returned. The CU mask is returned in a chunck of 32 bits where + * each active bit represents one active CU + * @return #hipSuccess, #hipErrorInvalidHandle, #hipErrorInvalidValue + * + * @see hipStreamCreate, hipStreamSynchronize, hipStreamWaitEvent, hipStreamDestroy + */ +hipError_t hipExtStreamGetCUMask(hipStream_t stream, uint32_t cuMaskSize, uint32_t* cuMask); +/** + * Stream CallBack struct + */ +typedef void (*hipStreamCallback_t)(hipStream_t stream, hipError_t status, void* userData); +/** + * @brief Adds a callback to be called on the host after all currently enqueued + * items in the stream have completed. For each + * hipStreamAddCallback call, a callback will be executed exactly once. + * The callback will block later work in the stream until it is finished. + * @param[in] stream - Stream to add callback to + * @param[in] callback - The function to call once preceding stream operations are complete + * @param[in] userData - User specified data to be passed to the callback function + * @param[in] flags - Reserved for future use, must be 0 + * @return #hipSuccess, #hipErrorInvalidHandle, #hipErrorNotSupported + * + * @see hipStreamCreate, hipStreamCreateWithFlags, hipStreamQuery, hipStreamSynchronize, + * hipStreamWaitEvent, hipStreamDestroy, hipStreamCreateWithPriority + * + */ +hipError_t hipStreamAddCallback(hipStream_t stream, hipStreamCallback_t callback, void* userData, + unsigned int flags); +// end doxygen Stream +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup StreamM Stream Memory Operations + * @{ + * This section describes Stream Memory Wait and Write functions of HIP runtime API. + */ +/** + * @brief Enqueues a wait command to the stream.[BETA] + * + * @param [in] stream - Stream identifier + * @param [in] ptr - Pointer to memory object allocated using 'hipMallocSignalMemory' flag + * @param [in] value - Value to be used in compare operation + * @param [in] flags - Defines the compare operation, supported values are hipStreamWaitValueGte + * hipStreamWaitValueEq, hipStreamWaitValueAnd and hipStreamWaitValueNor + * @param [in] mask - Mask to be applied on value at memory before it is compared with value, + * default value is set to enable every bit + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * Enqueues a wait command to the stream, all operations enqueued on this stream after this, will + * not execute until the defined wait condition is true. + * + * hipStreamWaitValueGte: waits until *ptr&mask >= value + * hipStreamWaitValueEq : waits until *ptr&mask == value + * hipStreamWaitValueAnd: waits until ((*ptr&mask) & value) != 0 + * hipStreamWaitValueNor: waits until ~((*ptr&mask) | (value&mask)) != 0 + * + * @note when using 'hipStreamWaitValueNor', mask is applied on both 'value' and '*ptr'. + * + * @note Support for hipStreamWaitValue32 can be queried using 'hipDeviceGetAttribute()' and + * 'hipDeviceAttributeCanUseStreamWaitValue' flag. + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @see hipExtMallocWithFlags, hipFree, hipStreamWaitValue64, hipStreamWriteValue64, + * hipStreamWriteValue32, hipDeviceGetAttribute + */ +hipError_t hipStreamWaitValue32(hipStream_t stream, void* ptr, uint32_t value, unsigned int flags, + uint32_t mask __dparm(0xFFFFFFFF)); +/** + * @brief Enqueues a wait command to the stream.[BETA] + * + * @param [in] stream - Stream identifier + * @param [in] ptr - Pointer to memory object allocated using 'hipMallocSignalMemory' flag + * @param [in] value - Value to be used in compare operation + * @param [in] flags - Defines the compare operation, supported values are hipStreamWaitValueGte + * hipStreamWaitValueEq, hipStreamWaitValueAnd and hipStreamWaitValueNor. + * @param [in] mask - Mask to be applied on value at memory before it is compared with value + * default value is set to enable every bit + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * Enqueues a wait command to the stream, all operations enqueued on this stream after this, will + * not execute until the defined wait condition is true. + * + * hipStreamWaitValueGte: waits until *ptr&mask >= value + * hipStreamWaitValueEq : waits until *ptr&mask == value + * hipStreamWaitValueAnd: waits until ((*ptr&mask) & value) != 0 + * hipStreamWaitValueNor: waits until ~((*ptr&mask) | (value&mask)) != 0 + * + * @note when using 'hipStreamWaitValueNor', mask is applied on both 'value' and '*ptr'. + * + * @note Support for hipStreamWaitValue64 can be queried using 'hipDeviceGetAttribute()' and + * 'hipDeviceAttributeCanUseStreamWaitValue' flag. + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @see hipExtMallocWithFlags, hipFree, hipStreamWaitValue32, hipStreamWriteValue64, + * hipStreamWriteValue32, hipDeviceGetAttribute + */ +hipError_t hipStreamWaitValue64(hipStream_t stream, void* ptr, uint64_t value, unsigned int flags, + uint64_t mask __dparm(0xFFFFFFFFFFFFFFFF)); +/** + * @brief Enqueues a write command to the stream.[BETA] + * + * @param [in] stream - Stream identifier + * @param [in] ptr - Pointer to a GPU accessible memory object + * @param [in] value - Value to be written + * @param [in] flags - reserved, ignored for now, will be used in future releases + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * Enqueues a write command to the stream, write operation is performed after all earlier commands + * on this stream have completed the execution. + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @see hipExtMallocWithFlags, hipFree, hipStreamWriteValue32, hipStreamWaitValue32, + * hipStreamWaitValue64 + */ +hipError_t hipStreamWriteValue32(hipStream_t stream, void* ptr, uint32_t value, unsigned int flags); +/** + * @brief Enqueues a write command to the stream.[BETA] + * + * @param [in] stream - Stream identifier + * @param [in] ptr - Pointer to a GPU accessible memory object + * @param [in] value - Value to be written + * @param [in] flags - reserved, ignored for now, will be used in future releases + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * Enqueues a write command to the stream, write operation is performed after all earlier commands + * on this stream have completed the execution. + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @see hipExtMallocWithFlags, hipFree, hipStreamWriteValue32, hipStreamWaitValue32, + * hipStreamWaitValue64 + */ +hipError_t hipStreamWriteValue64(hipStream_t stream, void* ptr, uint64_t value, unsigned int flags); +// end doxygen Stream Memory Operations +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Event Event Management + * @{ + * This section describes the event management functions of HIP runtime API. + */ +/** + * @brief Create an event with the specified flags + * + * @param[in,out] event Returns the newly created event. + * @param[in] flags Flags to control event behavior. Valid values are #hipEventDefault, + #hipEventBlockingSync, #hipEventDisableTiming, #hipEventInterprocess + * #hipEventDefault : Default flag. The event will use active synchronization and will support + timing. Blocking synchronization provides lowest possible latency at the expense of dedicating a + CPU to poll on the event. + * #hipEventBlockingSync : The event will use blocking synchronization : if hipEventSynchronize is + called on this event, the thread will block until the event completes. This can increase latency + for the synchroniation but can result in lower power and more resources for other CPU threads. + * #hipEventDisableTiming : Disable recording of timing information. Events created with this flag + would not record profiling data and provide best performance if used for synchronization. + * #hipEventInterprocess : The event can be used as an interprocess event. hipEventDisableTiming + flag also must be set when hipEventInterprocess flag is set. + * #hipEventDisableSystemFence : Disable acquire and release system scope fence. This may + improve performance but device memory may not be visible to the host and other devices + if this flag is set. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue, + #hipErrorLaunchFailure, #hipErrorOutOfMemory + * + * @see hipEventCreate, hipEventSynchronize, hipEventDestroy, hipEventElapsedTime + */ +hipError_t hipEventCreateWithFlags(hipEvent_t* event, unsigned flags); +/** + * Create an event + * + * @param[in,out] event Returns the newly created event. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue, + * #hipErrorLaunchFailure, #hipErrorOutOfMemory + * + * @see hipEventCreateWithFlags, hipEventRecord, hipEventQuery, hipEventSynchronize, + * hipEventDestroy, hipEventElapsedTime + */ +hipError_t hipEventCreate(hipEvent_t* event); +/** + * @brief Record an event in the specified stream. + * + * @param[in] event event to record. + * @param[in] stream stream in which to record event. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized, + * #hipErrorInvalidHandle, #hipErrorLaunchFailure + * + * hipEventQuery() or hipEventSynchronize() must be used to determine when the event + * transitions from "recording" (after hipEventRecord() is called) to "recorded" + * (when timestamps are set, if requested). + * + * Events which are recorded in a non-NULL stream will transition to + * from recording to "recorded" state when they reach the head of + * the specified stream, after all previous + * commands in that stream have completed executing. + * + * If hipEventRecord() has been previously called on this event, then this call will overwrite any + * existing state in event. + * + * If this function is called on an event that is currently being recorded, results are undefined + * - either outstanding recording may save state into the event, and the order is not guaranteed. + * + * @note: If this function is not called before use hipEventQuery() or hipEventSynchronize(), + * #hipSuccess is returned, meaning no pending event in the stream. + * + * @see hipEventCreate, hipEventCreateWithFlags, hipEventQuery, hipEventSynchronize, + * hipEventDestroy, hipEventElapsedTime + * + */ +#ifdef __cplusplus +hipError_t hipEventRecord(hipEvent_t event, hipStream_t stream = NULL); +#else +hipError_t hipEventRecord(hipEvent_t event, hipStream_t stream); +#endif +/** + * @brief Destroy the specified event. + * + * @param[in] event Event to destroy. + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue, + * #hipErrorLaunchFailure + * + * Releases memory associated with the event. If the event is recording but has not completed + * recording when hipEventDestroy() is called, the function will return immediately and the + * completion_future resources will be released later, when the hipDevice is synchronized. + * + * @see hipEventCreate, hipEventCreateWithFlags, hipEventQuery, hipEventSynchronize, hipEventRecord, + * hipEventElapsedTime + * + * @returns #hipSuccess + */ +hipError_t hipEventDestroy(hipEvent_t event); +/** + * @brief Wait for an event to complete. + * + * This function will block until the event is ready, waiting for all previous work in the stream + * specified when event was recorded with hipEventRecord(). + * + * If hipEventRecord() has not been called on @p event, this function returns #hipSuccess when no + * event is captured. + * + * + * @param[in] event Event on which to wait. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized, + * #hipErrorInvalidHandle, #hipErrorLaunchFailure + * + * @see hipEventCreate, hipEventCreateWithFlags, hipEventQuery, hipEventDestroy, hipEventRecord, + * hipEventElapsedTime + */ +hipError_t hipEventSynchronize(hipEvent_t event); +/** + * @brief Return the elapsed time between two events. + * + * @param[out] ms : Return time between start and stop in ms. + * @param[in] start : Start event. + * @param[in] stop : Stop event. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotReady, #hipErrorInvalidHandle, + * #hipErrorNotInitialized, #hipErrorLaunchFailure + * + * Computes the elapsed time between two events. Time is computed in ms, with + * a resolution of approximately 1 us. + * + * Events which are recorded in a NULL stream will block until all commands + * on all other streams complete execution, and then record the timestamp. + * + * Events which are recorded in a non-NULL stream will record their timestamp + * when they reach the head of the specified stream, after all previous + * commands in that stream have completed executing. Thus the time that + * the event recorded may be significantly after the host calls hipEventRecord(). + * + * If hipEventRecord() has not been called on either event, then #hipErrorInvalidHandle is + * returned. If hipEventRecord() has been called on both events, but the timestamp has not yet been + * recorded on one or both events (that is, hipEventQuery() would return #hipErrorNotReady on at + * least one of the events), then #hipErrorNotReady is returned. + * + * @see hipEventCreate, hipEventCreateWithFlags, hipEventQuery, hipEventDestroy, hipEventRecord, + * hipEventSynchronize + */ +hipError_t hipEventElapsedTime(float* ms, hipEvent_t start, hipEvent_t stop); +/** + * @brief Query event status + * + * @param[in] event Event to query. + * @returns #hipSuccess, #hipErrorNotReady, #hipErrorInvalidHandle, #hipErrorInvalidValue, + * #hipErrorNotInitialized, #hipErrorLaunchFailure + * + * Query the status of the specified event. This function will return #hipSuccess if all + * commands in the appropriate stream (specified to hipEventRecord()) have completed. If any execution + * has not completed, then #hipErrorNotReady is returned. + * + * @note: This API returns #hipSuccess, if hipEventRecord() is not called before this API. + * + * @see hipEventCreate, hipEventCreateWithFlags, hipEventRecord, hipEventDestroy, + * hipEventSynchronize, hipEventElapsedTime + */ +hipError_t hipEventQuery(hipEvent_t event); +// end doxygen Events +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Memory Memory Management + * @{ + * This section describes the memory management functions of HIP runtime API. + * The following CUDA APIs are not currently supported: + * - cudaMalloc3D + * - cudaMalloc3DArray + * - TODO - more 2D, 3D, array APIs here. + * + * + */ + +/** + * @brief Sets information on the specified pointer.[BETA] + * + * @param [in] value Sets pointer attribute value + * @param [in] attribute Attribute to set + * @param [in] ptr Pointer to set attributes for + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipPointerSetAttribute(const void* value, hipPointer_attribute attribute, + hipDeviceptr_t ptr); + + +/** + * @brief Returns attributes for the specified pointer + * + * @param [out] attributes attributes for the specified pointer + * @param [in] ptr pointer to get attributes for + * + * The output parameter 'attributes' has a member named 'type' that describes what memory the + * pointer is associated with, such as device memory, host memory, managed memory, and others. + * Otherwise, the API cannot handle the pointer and returns #hipErrorInvalidValue. + * + * @note The unrecognized memory type is unsupported to keep the HIP functionality backward + * compatibility due to #hipMemoryType enum values. + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @note The current behavior of this HIP API corresponds to the CUDA API before version 11.0. + * + * @see hipPointerGetAttribute + */ +hipError_t hipPointerGetAttributes(hipPointerAttribute_t* attributes, const void* ptr); +/** + * @brief Returns information about the specified pointer.[BETA] + * + * @param [in, out] data Returned pointer attribute value + * @param [in] attribute Attribute to query for + * @param [in] ptr Pointer to get attributes for + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @see hipPointerGetAttributes + */ +hipError_t hipPointerGetAttribute(void* data, hipPointer_attribute attribute, + hipDeviceptr_t ptr); +/** + * @brief Returns information about the specified pointer.[BETA] + * + * @param [in] numAttributes number of attributes to query for + * @param [in] attributes attributes to query for + * @param [in, out] data a two-dimensional containing pointers to memory locations + * where the result of each attribute query will be written to + * @param [in] ptr pointer to get attributes for + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @see hipPointerGetAttribute + */ +hipError_t hipDrvPointerGetAttributes(unsigned int numAttributes, hipPointer_attribute* attributes, + void** data, hipDeviceptr_t ptr); +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup External External Resource Interoperability + * @{ + * @ingroup API + * + * This section describes the external resource interoperability functions of HIP runtime API. + * + */ +/** + * @brief Imports an external semaphore. + * + * @param[out] extSem_out External semaphores to be waited on + * @param[in] semHandleDesc Semaphore import handle descriptor + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @see + */ +hipError_t hipImportExternalSemaphore(hipExternalSemaphore_t* extSem_out, + const hipExternalSemaphoreHandleDesc* semHandleDesc); +/** + * @brief Signals a set of external semaphore objects. + * + * @param[in] extSemArray External semaphores to be waited on + * @param[in] paramsArray Array of semaphore parameters + * @param[in] numExtSems Number of semaphores to wait on + * @param[in] stream Stream to enqueue the wait operations in + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @see + */ +hipError_t hipSignalExternalSemaphoresAsync(const hipExternalSemaphore_t* extSemArray, + const hipExternalSemaphoreSignalParams* paramsArray, + unsigned int numExtSems, hipStream_t stream); +/** + * @brief Waits on a set of external semaphore objects + * + * @param[in] extSemArray External semaphores to be waited on + * @param[in] paramsArray Array of semaphore parameters + * @param[in] numExtSems Number of semaphores to wait on + * @param[in] stream Stream to enqueue the wait operations in + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @see + */ +hipError_t hipWaitExternalSemaphoresAsync(const hipExternalSemaphore_t* extSemArray, + const hipExternalSemaphoreWaitParams* paramsArray, + unsigned int numExtSems, hipStream_t stream); +/** + * @brief Destroys an external semaphore object and releases any references to the underlying resource. Any outstanding signals or waits must have completed before the semaphore is destroyed. + * + * @param[in] extSem handle to an external memory object + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @see + */ +hipError_t hipDestroyExternalSemaphore(hipExternalSemaphore_t extSem); + +/** +* @brief Imports an external memory object. +* +* @param[out] extMem_out Returned handle to an external memory object +* @param[in] memHandleDesc Memory import handle descriptor +* +* @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue +* +* @see +*/ +hipError_t hipImportExternalMemory(hipExternalMemory_t* extMem_out, const hipExternalMemoryHandleDesc* memHandleDesc); +/** +* @brief Maps a buffer onto an imported memory object. +* +* @param[out] devPtr Returned device pointer to buffer +* @param[in] extMem Handle to external memory object +* @param[in] bufferDesc Buffer descriptor +* +* @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue +* +* @see +*/ +hipError_t hipExternalMemoryGetMappedBuffer(void **devPtr, hipExternalMemory_t extMem, const hipExternalMemoryBufferDesc *bufferDesc); +/** +* @brief Destroys an external memory object. +* +* @param[in] extMem External memory object to be destroyed +* +* @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue +* +* @see +*/ +hipError_t hipDestroyExternalMemory(hipExternalMemory_t extMem); +/** + * @brief Maps a mipmapped array onto an external memory object. + * + * @param[out] mipmap mipmapped array to return + * @param[in] extMem external memory object handle + * @param[in] mipmapDesc external mipmapped array descriptor + * + * Returned mipmapped array must be freed using hipFreeMipmappedArray. + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidResourceHandle + * + * @see hipImportExternalMemory, hipDestroyExternalMemory, hipExternalMemoryGetMappedBuffer, hipFreeMipmappedArray + */ +hipError_t hipExternalMemoryGetMappedMipmappedArray(hipMipmappedArray_t* mipmap, hipExternalMemory_t extMem, + const hipExternalMemoryMipmappedArrayDesc* mipmapDesc); + // end of external resource + /** + * @} + */ +/** + * @brief Allocate memory on the default accelerator + * + * @param[out] ptr Pointer to the allocated memory + * @param[in] size Requested memory size + * + * If size is 0, no memory is allocated, *ptr returns nullptr, and hipSuccess is returned. + * + * @return #hipSuccess, #hipErrorOutOfMemory, #hipErrorInvalidValue (bad context, null *ptr) + * + * @see hipMallocPitch, hipFree, hipMallocArray, hipFreeArray, hipMalloc3D, hipMalloc3DArray, + * hipHostFree, hipHostMalloc + */ +hipError_t hipMalloc(void** ptr, size_t size); +/** + * @brief Allocate memory on the default accelerator + * + * @param[out] ptr Pointer to the allocated memory + * @param[in] sizeBytes Requested memory size + * @param[in] flags Type of memory allocation + * + * If requested memory size is 0, no memory is allocated, *ptr returns nullptr, and #hipSuccess + * is returned. + * + * The memory allocation flag should be either #hipDeviceMallocDefault, + * #hipDeviceMallocFinegrained, #hipDeviceMallocUncached, or #hipMallocSignalMemory. + * If the flag is any other value, the API returns #hipErrorInvalidValue. + * + * @return #hipSuccess, #hipErrorOutOfMemory, #hipErrorInvalidValue (bad context, null *ptr) + * + * @see hipMallocPitch, hipFree, hipMallocArray, hipFreeArray, hipMalloc3D, hipMalloc3DArray, + * hipHostFree, hipHostMalloc + */ +hipError_t hipExtMallocWithFlags(void** ptr, size_t sizeBytes, unsigned int flags); +/** + * @brief Allocate pinned host memory [Deprecated] + * + * @param[out] ptr Pointer to the allocated host pinned memory + * @param[in] size Requested memory size + * + * If size is 0, no memory is allocated, *ptr returns nullptr, and hipSuccess is returned. + * + * @return #hipSuccess, #hipErrorOutOfMemory + * + * @warning This API is deprecated, use hipHostMalloc() instead + */ +DEPRECATED("use hipHostMalloc instead") +hipError_t hipMallocHost(void** ptr, size_t size); +/** + * @brief Allocate pinned host memory [Deprecated] + * + * @param[out] ptr Pointer to the allocated host pinned memory + * @param[in] size Requested memory size + * + * If size is 0, no memory is allocated, *ptr returns nullptr, and hipSuccess is returned. + * + * @return #hipSuccess, #hipErrorOutOfMemory + * + * @warning This API is deprecated, use hipHostMalloc() instead + */ +DEPRECATED("use hipHostMalloc instead") +hipError_t hipMemAllocHost(void** ptr, size_t size); +/** + * @brief Allocates device accessible page locked (pinned) host memory + * + * This API allocates pinned host memory which is mapped into the address space of all GPUs + * in the system, the memory can be accessed directly by the GPU device, and can be read or + * written with much higher bandwidth than pageable memory obtained with functions such as + * malloc(). + * + * Using the pinned host memory, applications can implement faster data transfers for HostToDevice + * and DeviceToHost. The runtime tracks the hipHostMalloc allocations and can avoid some of the + * setup required for regular unpinned memory. + * + * When the memory accesses are infrequent, zero-copy memory can be a good choice, for coherent + * allocation. GPU can directly access the host memory over the CPU/GPU interconnect, without need + * to copy the data. + * + * Currently the allocation granularity is 4KB for the API. + * + * Developers need to choose proper allocation flag with consideration of synchronization. + * + * @param[out] ptr Pointer to the allocated host pinned memory + * @param[in] size Requested memory size in bytes + * If size is 0, no memory is allocated, *ptr returns nullptr, and hipSuccess is returned. + * @param[in] flags Type of host memory allocation + * + * If no input for flags, it will be the default pinned memory allocation on the host. + * + * @return #hipSuccess, #hipErrorOutOfMemory + * + * @see hipSetDeviceFlags, hipHostFree + */ +hipError_t hipHostMalloc(void** ptr, size_t size, unsigned int flags); +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup MemoryM Managed Memory + * + * @ingroup Memory + * @{ + * This section describes the managed memory management functions of HIP runtime API. + * + * @note The managed memory management APIs are implemented on Linux, under developement + * on Windows. + * + */ +/** + * @brief Allocates memory that will be automatically managed by HIP. + * + * This API is used for managed memory, allows data be shared and accessible to both CPU and + * GPU using a single pointer. + * + * The API returns the allocation pointer, managed by HMM, can be used further to execute kernels + * on device and fetch data between the host and device as needed. + * + * @note It is recommend to do the capability check before call this API. + * + * @param [out] dev_ptr - pointer to allocated device memory + * @param [in] size - requested allocation size in bytes, it should be granularity of 4KB + * @param [in] flags - must be either hipMemAttachGlobal or hipMemAttachHost + * (defaults to hipMemAttachGlobal) + * + * @returns #hipSuccess, #hipErrorMemoryAllocation, #hipErrorNotSupported, #hipErrorInvalidValue + * + */ +hipError_t hipMallocManaged(void** dev_ptr, + size_t size, + unsigned int flags __dparm(hipMemAttachGlobal)); +/** + * @brief Prefetches memory to the specified destination device using HIP. + * + * @param [in] dev_ptr pointer to be prefetched + * @param [in] count size in bytes for prefetching + * @param [in] device destination device to prefetch to + * @param [in] stream stream to enqueue prefetch operation + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPrefetchAsync(const void* dev_ptr, + size_t count, + int device, + hipStream_t stream __dparm(0)); +/** + * @brief Advise about the usage of a given memory range to HIP. + * + * @param [in] dev_ptr pointer to memory to set the advice for + * @param [in] count size in bytes of the memory range, it should be CPU page size alligned. + * @param [in] advice advice to be applied for the specified memory range + * @param [in] device device to apply the advice for + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * This HIP API advises about the usage to be applied on unified memory allocation in the + * range starting from the pointer address devPtr, with the size of count bytes. + * The memory range must refer to managed memory allocated via the API hipMallocManaged, and the + * range will be handled with proper round down and round up respectively in the driver to + * be aligned to CPU page size, the same way as corresponding CUDA API behaves in CUDA version 8.0 + * and afterwards. + * + * @note This API is implemented on Linux and is under development on Windows. + */ +hipError_t hipMemAdvise(const void* dev_ptr, + size_t count, + hipMemoryAdvise advice, + int device); +/** + * @brief Query an attribute of a given memory range in HIP. + * + * @param [in,out] data a pointer to a memory location where the result of each + * attribute query will be written to + * @param [in] data_size the size of data + * @param [in] attribute the attribute to query + * @param [in] dev_ptr start of the range to query + * @param [in] count size of the range to query + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemRangeGetAttribute(void* data, + size_t data_size, + hipMemRangeAttribute attribute, + const void* dev_ptr, + size_t count); +/** + * @brief Query attributes of a given memory range in HIP. + * + * @param [in,out] data a two-dimensional array containing pointers to memory locations + * where the result of each attribute query will be written to + * @param [in] data_sizes an array, containing the sizes of each result + * @param [in] attributes the attribute to query + * @param [in] num_attributes an array of attributes to query (numAttributes and the number + * of attributes in this array should match) + * @param [in] dev_ptr start of the range to query + * @param [in] count size of the range to query + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemRangeGetAttributes(void** data, + size_t* data_sizes, + hipMemRangeAttribute* attributes, + size_t num_attributes, + const void* dev_ptr, + size_t count); +/** + * @brief Attach memory to a stream asynchronously in HIP. + * + * @param [in] stream - stream in which to enqueue the attach operation + * @param [in] dev_ptr - pointer to memory (must be a pointer to managed memory or + * to a valid host-accessible region of system-allocated memory) + * @param [in] length - length of memory (defaults to zero) + * @param [in] flags - must be one of hipMemAttachGlobal, hipMemAttachHost or + * hipMemAttachSingle (defaults to hipMemAttachSingle) + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipStreamAttachMemAsync(hipStream_t stream, + void* dev_ptr, + size_t length __dparm(0), + unsigned int flags __dparm(hipMemAttachSingle)); +// end doxygen Managed Memory +/** + * @} + */ + +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup StreamO Stream Ordered Memory Allocator + * @{ + * @ingroup Memory + * This section describes Stream Ordered Memory Allocator functions of HIP runtime API. + * + * The asynchronous allocator allows the user to allocate and free in stream order. + * All asynchronous accesses of the allocation must happen between the stream executions of + * the allocation and the free. If the memory is accessed outside of the promised stream order, + * a use before allocation / use after free error will cause undefined behavior. + * + * The allocator is free to reallocate the memory as long as it can guarantee that compliant memory + * accesses will not overlap temporally. The allocator may refer to internal stream ordering as well + * as inter-stream dependencies (such as HIP events and null stream dependencies) when establishing + * the temporal guarantee. The allocator may also insert inter-stream dependencies to establish + * the temporal guarantee. Whether or not a device supports the integrated stream ordered memory + * allocator may be queried by calling @p hipDeviceGetAttribute with the device attribute + * @p hipDeviceAttributeMemoryPoolsSupported + * + * @note APIs in this section are implemented on Linux, under development on Windows. + */ + +/** + * @brief Allocates memory with stream ordered semantics + * + * Inserts a memory allocation operation into @p stream. + * A pointer to the allocated memory is returned immediately in *dptr. + * The allocation must not be accessed until the allocation operation completes. + * The allocation comes from the memory pool associated with the stream's device. + * + * @note The default memory pool of a device contains device memory from that device. + * @note Basic stream ordering allows future work submitted into the same stream to use the + * allocation. Stream query, stream synchronize, and HIP events can be used to guarantee that + * the allocation operation completes before work submitted in a separate stream runs. + * @note During stream capture, this function results in the creation of an allocation node. + * In this case, the allocation is owned by the graph instead of the memory pool. The memory + * pool's properties are used to set the node's creation parameters. + * + * @param [out] dev_ptr Returned device pointer of memory allocation + * @param [in] size Number of bytes to allocate + * @param [in] stream The stream establishing the stream ordering contract and + * the memory pool to allocate from + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported, #hipErrorOutOfMemory + * + * @see hipMallocFromPoolAsync, hipFreeAsync, hipMemPoolTrimTo, hipMemPoolGetAttribute, + * hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMallocAsync(void** dev_ptr, size_t size, hipStream_t stream); +/** + * @brief Frees memory with stream ordered semantics + * + * Inserts a free operation into @p stream. + * The allocation must not be used after stream execution reaches the free. + * After this API returns, accessing the memory from any subsequent work launched on the GPU + * or querying its pointer attributes results in undefined behavior. + * + * @note During stream capture, this function results in the creation of a free node and + * must therefore be passed the address of a graph allocation. + * + * @param [in] dev_ptr Pointer to device memory to free + * @param [in] stream The stream, where the destruciton will occur according to the execution order + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipMemPoolTrimTo, hipMemPoolGetAttribute, + * hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipFreeAsync(void* dev_ptr, hipStream_t stream); +/** + * @brief Releases freed memory back to the OS + * + * Releases memory back to the OS until the pool contains fewer than @p min_bytes_to_keep + * reserved bytes, or there is no more memory that the allocator can safely release. + * The allocator cannot release OS allocations that back outstanding asynchronous allocations. + * The OS allocations may happen at different granularity from the user allocations. + * + * @note: Allocations that have not been freed count as outstanding. + * @note: Allocations that have been asynchronously freed but whose completion has + * not been observed on the host (eg. by a synchronize) can count as outstanding. + * + * @param[in] mem_pool The memory pool to trim allocations + * @param[in] min_bytes_to_hold If the pool has less than min_bytes_to_hold reserved, + * then the TrimTo operation is a no-op. Otherwise the memory pool will contain + * at least min_bytes_to_hold bytes reserved after the operation. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipFreeAsync, hipMemPoolGetAttribute, + * hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolTrimTo(hipMemPool_t mem_pool, size_t min_bytes_to_hold); +/** + * @brief Sets attributes of a memory pool + * + * Supported attributes are: + * - @p hipMemPoolAttrReleaseThreshold: (value type = cuuint64_t) + * Amount of reserved memory in bytes to hold onto before trying + * to release memory back to the OS. When more than the release + * threshold bytes of memory are held by the memory pool, the + * allocator will try to release memory back to the OS on the + * next call to stream, event or context synchronize. (default 0) + * - @p hipMemPoolReuseFollowEventDependencies: (value type = int) + * Allow @p hipMallocAsync to use memory asynchronously freed + * in another stream as long as a stream ordering dependency + * of the allocating stream on the free action exists. + * HIP events and null stream interactions can create the required + * stream ordered dependencies. (default enabled) + * - @p hipMemPoolReuseAllowOpportunistic: (value type = int) + * Allow reuse of already completed frees when there is no dependency + * between the free and allocation. (default enabled) + * - @p hipMemPoolReuseAllowInternalDependencies: (value type = int) + * Allow @p hipMallocAsync to insert new stream dependencies + * in order to establish the stream ordering required to reuse + * a piece of memory released by @p hipFreeAsync (default enabled). + * + * @param [in] mem_pool The memory pool to modify + * @param [in] attr The attribute to modify + * @param [in] value Pointer to the value to assign + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipFreeAsync, hipMemPoolGetAttribute, + * hipMemPoolTrimTo, hipDeviceSetMemPool, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolSetAttribute(hipMemPool_t mem_pool, hipMemPoolAttr attr, void* value); +/** + * @brief Gets attributes of a memory pool + * + * Supported attributes are: + * - @p hipMemPoolAttrReleaseThreshold: (value type = cuuint64_t) + * Amount of reserved memory in bytes to hold onto before trying + * to release memory back to the OS. When more than the release + * threshold bytes of memory are held by the memory pool, the + * allocator will try to release memory back to the OS on the + * next call to stream, event or context synchronize. (default 0) + * - @p hipMemPoolReuseFollowEventDependencies: (value type = int) + * Allow @p hipMallocAsync to use memory asynchronously freed + * in another stream as long as a stream ordering dependency + * of the allocating stream on the free action exists. + * HIP events and null stream interactions can create the required + * stream ordered dependencies. (default enabled) + * - @p hipMemPoolReuseAllowOpportunistic: (value type = int) + * Allow reuse of already completed frees when there is no dependency + * between the free and allocation. (default enabled) + * - @p hipMemPoolReuseAllowInternalDependencies: (value type = int) + * Allow @p hipMallocAsync to insert new stream dependencies + * in order to establish the stream ordering required to reuse + * a piece of memory released by @p hipFreeAsync (default enabled). + * + * @param [in] mem_pool The memory pool to get attributes of + * @param [in] attr The attribute to get + * @param [in] value Retrieved value + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipFreeAsync, + * hipMemPoolTrimTo, hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolGetAttribute(hipMemPool_t mem_pool, hipMemPoolAttr attr, void* value); +/** + * @brief Controls visibility of the specified pool between devices + * + * @param [in] mem_pool Memory pool for acccess change + * @param [in] desc_list Array of access descriptors. Each descriptor instructs the access to enable for a single gpu + * @param [in] count Number of descriptors in the map array. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipFreeAsync, hipMemPoolGetAttribute, + * hipMemPoolTrimTo, hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolSetAccess(hipMemPool_t mem_pool, const hipMemAccessDesc* desc_list, size_t count); +/** + * @brief Returns the accessibility of a pool from a device + * + * Returns the accessibility of the pool's memory from the specified location. + * + * @param [out] flags Accessibility of the memory pool from the specified location/device + * @param [in] mem_pool Memory pool being queried + * @param [in] location Location/device for memory pool access + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipFreeAsync, hipMemPoolGetAttribute, + * hipMemPoolTrimTo, hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolGetAccess(hipMemAccessFlags* flags, hipMemPool_t mem_pool, hipMemLocation* location); +/** + * @brief Creates a memory pool + * + * Creates a HIP memory pool and returns the handle in @p mem_pool. The @p pool_props determines + * the properties of the pool such as the backing device and IPC capabilities. + * + * By default, the memory pool will be accessible from the device it is allocated on. + * + * @param [out] mem_pool Contains createed memory pool + * @param [in] pool_props Memory pool properties + * + * @note Specifying hipMemHandleTypeNone creates a memory pool that will not support IPC. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipFreeAsync, hipMemPoolGetAttribute, hipMemPoolDestroy, + * hipMemPoolTrimTo, hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolCreate(hipMemPool_t* mem_pool, const hipMemPoolProps* pool_props); +/** + * @brief Destroys the specified memory pool + * + * If any pointers obtained from this pool haven't been freed or + * the pool has free operations that haven't completed + * when @p hipMemPoolDestroy is invoked, the function will return immediately and the + * resources associated with the pool will be released automatically + * once there are no more outstanding allocations. + * + * Destroying the current mempool of a device sets the default mempool of + * that device as the current mempool for that device. + * + * @param [in] mem_pool Memory pool for destruction + * + * @note A device's default memory pool cannot be destroyed. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipFreeAsync, hipMemPoolGetAttribute, hipMemPoolCreate + * hipMemPoolTrimTo, hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolDestroy(hipMemPool_t mem_pool); +/** + * @brief Allocates memory from a specified pool with stream ordered semantics. + * + * Inserts an allocation operation into @p stream. + * A pointer to the allocated memory is returned immediately in @p dev_ptr. + * The allocation must not be accessed until the allocation operation completes. + * The allocation comes from the specified memory pool. + * + * @note The specified memory pool may be from a device different than that of the specified @p stream. + * + * Basic stream ordering allows future work submitted into the same stream to use the allocation. + * Stream query, stream synchronize, and HIP events can be used to guarantee that the allocation + * operation completes before work submitted in a separate stream runs. + * + * @note During stream capture, this function results in the creation of an allocation node. In this case, + * the allocation is owned by the graph instead of the memory pool. The memory pool's properties + * are used to set the node's creation parameters. + * + * @param [out] dev_ptr Returned device pointer + * @param [in] size Number of bytes to allocate + * @param [in] mem_pool The pool to allocate from + * @param [in] stream The stream establishing the stream ordering semantic + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported, #hipErrorOutOfMemory + * + * @see hipMallocAsync, hipFreeAsync, hipMemPoolGetAttribute, hipMemPoolCreate + * hipMemPoolTrimTo, hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess, + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMallocFromPoolAsync(void** dev_ptr, size_t size, hipMemPool_t mem_pool, hipStream_t stream); +/** + * @brief Exports a memory pool to the requested handle type. + * + * Given an IPC capable mempool, create an OS handle to share the pool with another process. + * A recipient process can convert the shareable handle into a mempool with @p hipMemPoolImportFromShareableHandle. + * Individual pointers can then be shared with the @p hipMemPoolExportPointer and @p hipMemPoolImportPointer APIs. + * The implementation of what the shareable handle is and how it can be transferred is defined by the requested + * handle type. + * + * @note: To create an IPC capable mempool, create a mempool with a @p hipMemAllocationHandleType other + * than @p hipMemHandleTypeNone. + * + * @param [out] shared_handle Pointer to the location in which to store the requested handle + * @param [in] mem_pool Pool to export + * @param [in] handle_type The type of handle to create + * @param [in] flags Must be 0 + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorOutOfMemory + * + * @see hipMemPoolImportFromShareableHandle + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolExportToShareableHandle( + void* shared_handle, + hipMemPool_t mem_pool, + hipMemAllocationHandleType handle_type, + unsigned int flags); +/** + * @brief Imports a memory pool from a shared handle. + * + * Specific allocations can be imported from the imported pool with @p hipMemPoolImportPointer. + * + * @note Imported memory pools do not support creating new allocations. + * As such imported memory pools may not be used in @p hipDeviceSetMemPool + * or @p hipMallocFromPoolAsync calls. + * + * @param [out] mem_pool Returned memory pool + * @param [in] shared_handle OS handle of the pool to open + * @param [in] handle_type The type of handle being imported + * @param [in] flags Must be 0 + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorOutOfMemory + * + * @see hipMemPoolExportToShareableHandle + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolImportFromShareableHandle( + hipMemPool_t* mem_pool, + void* shared_handle, + hipMemAllocationHandleType handle_type, + unsigned int flags); +/** + * @brief Export data to share a memory pool allocation between processes. + * + * Constructs @p export_data for sharing a specific allocation from an already shared memory pool. + * The recipient process can import the allocation with the @p hipMemPoolImportPointer api. + * The data is not a handle and may be shared through any IPC mechanism. + * + * @param[out] export_data Returned export data + * @param[in] dev_ptr Pointer to memory being exported + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorOutOfMemory + * + * @see hipMemPoolImportPointer + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolExportPointer(hipMemPoolPtrExportData* export_data, void* dev_ptr); +/** + * @brief Import a memory pool allocation from another process. + * + * Returns in @p dev_ptr a pointer to the imported memory. + * The imported memory must not be accessed before the allocation operation completes + * in the exporting process. The imported memory must be freed from all importing processes before + * being freed in the exporting process. The pointer may be freed with @p hipFree + * or @p hipFreeAsync. If @p hipFreeAsync is used, the free must be completed + * on the importing process before the free operation on the exporting process. + * + * @note The @p hipFreeAsync api may be used in the exporting process before + * the @p hipFreeAsync operation completes in its stream as long as the + * @p hipFreeAsync in the exporting process specifies a stream with + * a stream dependency on the importing process's @p hipFreeAsync. + * + * @param [out] dev_ptr Pointer to imported memory + * @param [in] mem_pool Memory pool from which to import a pointer + * @param [in] export_data Data specifying the memory to import + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized, #hipErrorOutOfMemory + * + * @see hipMemPoolExportPointer + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolImportPointer( + void** dev_ptr, + hipMemPool_t mem_pool, + hipMemPoolPtrExportData* export_data); +// Doxygen end of ordered memory allocator +/** + * @} + */ + +/** + * @brief Allocate device accessible page locked host memory [Deprecated] + * + * @param[out] ptr Pointer to the allocated host pinned memory + * @param[in] size Requested memory size in bytes + * @param[in] flags Type of host memory allocation + * + * If size is 0, no memory is allocated, *ptr returns nullptr, and hipSuccess is returned. + * + * @return #hipSuccess, #hipErrorOutOfMemory + * + * @warning This API is deprecated, use hipHostMalloc() instead + */ +DEPRECATED("use hipHostMalloc instead") +hipError_t hipHostAlloc(void** ptr, size_t size, unsigned int flags); +/** + * @brief Get Device pointer from Host Pointer allocated through hipHostMalloc + * + * @param[out] devPtr Device Pointer mapped to passed host pointer + * @param[in] hstPtr Host Pointer allocated through hipHostMalloc + * @param[in] flags Flags to be passed for extension + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorOutOfMemory + * + * @see hipSetDeviceFlags, hipHostMalloc + */ +hipError_t hipHostGetDevicePointer(void** devPtr, void* hstPtr, unsigned int flags); +/** + * @brief Return flags associated with host pointer + * + * @param[out] flagsPtr Memory location to store flags + * @param[in] hostPtr Host Pointer allocated through hipHostMalloc + * @return #hipSuccess, #hipErrorInvalidValue + * + * @see hipHostMalloc + */ +hipError_t hipHostGetFlags(unsigned int* flagsPtr, void* hostPtr); +/** + * @brief Register host memory so it can be accessed from the current device. + * + * @param[out] hostPtr Pointer to host memory to be registered. + * @param[in] sizeBytes Size of the host memory + * @param[in] flags See below. + * + * Flags: + * - #hipHostRegisterDefault Memory is Mapped and Portable + * - #hipHostRegisterPortable Memory is considered registered by all contexts. HIP only supports + * one context so this is always assumed true. + * - #hipHostRegisterMapped Map the allocation into the address space for the current device. + * The device pointer can be obtained with #hipHostGetDevicePointer. + * + * + * After registering the memory, use #hipHostGetDevicePointer to obtain the mapped device pointer. + * On many systems, the mapped device pointer will have a different value than the mapped host + * pointer. Applications must use the device pointer in device code, and the host pointer in device + * code. + * + * On some systems, registered memory is pinned. On some systems, registered memory may not be + * actually be pinned but uses OS or hardware facilities to all GPU access to the host memory. + * + * Developers are strongly encouraged to register memory blocks which are aligned to the host + * cache-line size. (typically 64-bytes but can be obtains from the CPUID instruction). + * + * If registering non-aligned pointers, the application must take care when register pointers from + * the same cache line on different devices. HIP's coarse-grained synchronization model does not + * guarantee correct results if different devices write to different parts of the same cache block - + * typically one of the writes will "win" and overwrite data from the other registered memory + * region. + * + * @return #hipSuccess, #hipErrorOutOfMemory + * + * @see hipHostUnregister, hipHostGetFlags, hipHostGetDevicePointer + */ +hipError_t hipHostRegister(void* hostPtr, size_t sizeBytes, unsigned int flags); +/** + * @brief Un-register host pointer + * + * @param[in] hostPtr Host pointer previously registered with #hipHostRegister + * @return Error code + * + * @see hipHostRegister + */ +hipError_t hipHostUnregister(void* hostPtr); +/** + * Allocates at least width (in bytes) * height bytes of linear memory + * Padding may occur to ensure alighnment requirements are met for the given row + * The change in width size due to padding will be returned in *pitch. + * Currently the alignment is set to 128 bytes + * + * @param[out] ptr Pointer to the allocated device memory + * @param[out] pitch Pitch for allocation (in bytes) + * @param[in] width Requested pitched allocation width (in bytes) + * @param[in] height Requested pitched allocation height + * + * If size is 0, no memory is allocated, *ptr returns nullptr, and hipSuccess is returned. + * + * @return Error code + * + * @see hipMalloc, hipFree, hipMallocArray, hipFreeArray, hipHostFree, hipMalloc3D, + * hipMalloc3DArray, hipHostMalloc + */ +hipError_t hipMallocPitch(void** ptr, size_t* pitch, size_t width, size_t height); +/** + * Allocates at least width (in bytes) * height bytes of linear memory + * Padding may occur to ensure alighnment requirements are met for the given row + * The change in width size due to padding will be returned in *pitch. + * Currently the alignment is set to 128 bytes + * + * @param[out] dptr Pointer to the allocated device memory + * @param[out] pitch Pitch for allocation (in bytes) + * @param[in] widthInBytes Requested pitched allocation width (in bytes) + * @param[in] height Requested pitched allocation height + * @param[in] elementSizeBytes The size of element bytes, should be 4, 8 or 16 + * + * If size is 0, no memory is allocated, *ptr returns nullptr, and hipSuccess is returned. + * The intended usage of pitch is as a separate parameter of the allocation, used to compute addresses within the 2D array. + * Given the row and column of an array element of type T, the address is computed as: + * T* pElement = (T*)((char*)BaseAddress + Row * Pitch) + Column; + * + * @return Error code + * + * @see hipMalloc, hipFree, hipMallocArray, hipFreeArray, hipHostFree, hipMalloc3D, + * hipMalloc3DArray, hipHostMalloc + */ +hipError_t hipMemAllocPitch(hipDeviceptr_t* dptr, size_t* pitch, size_t widthInBytes, size_t height, + unsigned int elementSizeBytes); +/** + * @brief Free memory allocated by the hcc hip memory allocation API. + * This API performs an implicit hipDeviceSynchronize() call. + * If pointer is NULL, the hip runtime is initialized and hipSuccess is returned. + * + * @param[in] ptr Pointer to memory to be freed + * @return #hipSuccess + * @return #hipErrorInvalidDevicePointer (if pointer is invalid, including host pointers allocated + * with hipHostMalloc) + * + * @see hipMalloc, hipMallocPitch, hipMallocArray, hipFreeArray, hipHostFree, hipMalloc3D, + * hipMalloc3DArray, hipHostMalloc + */ +hipError_t hipFree(void* ptr); +/** + * @brief Free memory allocated by the hcc hip host memory allocation API [Deprecated] + * + * @param[in] ptr Pointer to memory to be freed + * @return #hipSuccess, + * #hipErrorInvalidValue (if pointer is invalid, including device pointers allocated + * with hipMalloc) + * + * @warning This API is deprecated, use hipHostFree() instead + */ +DEPRECATED("use hipHostFree instead") +hipError_t hipFreeHost(void* ptr); +/** + * @brief Free memory allocated by the hcc hip host memory allocation API + * This API performs an implicit hipDeviceSynchronize() call. + * If pointer is NULL, the hip runtime is initialized and hipSuccess is returned. + * + * @param[in] ptr Pointer to memory to be freed + * @return #hipSuccess, + * #hipErrorInvalidValue (if pointer is invalid, including device pointers allocated with + * hipMalloc) + * + * @see hipMalloc, hipMallocPitch, hipFree, hipMallocArray, hipFreeArray, hipMalloc3D, + * hipMalloc3DArray, hipHostMalloc + */ +hipError_t hipHostFree(void* ptr); +/** + * @brief Copy data from src to dst. + * + * It supports memory from host to device, + * device to host, device to device and host to host + * The src and dst must not overlap. + * + * For hipMemcpy, the copy is always performed by the current device (set by hipSetDevice). + * For multi-gpu or peer-to-peer configurations, it is recommended to set the current device to the + * device where the src data is physically located. For optimal peer-to-peer copies, the copy device + * must be able to access the src and dst pointers (by calling hipDeviceEnablePeerAccess with copy + * agent as the current device and src/dest as the peerDevice argument. if this is not done, the + * hipMemcpy will still work, but will perform the copy using a staging buffer on the host. + * Calling hipMemcpy with dst and src pointers that do not match the hipMemcpyKind results in + * undefined behavior. + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * @param[in] kind Kind of transfer + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpy(void* dst, const void* src, size_t sizeBytes, hipMemcpyKind kind); +/** + * @brief Memory copy on the stream. + * It allows single or multiple devices to do memory copy on single or multiple streams. + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * @param[in] kind Kind of transfer + * @param[in] stream Valid stream + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown, #hipErrorContextIsDestroyed + * + * @see hipMemcpy, hipStreamCreate, hipStreamSynchronize, hipStreamDestroy, hipSetDevice, hipLaunchKernelGGL + * + */ +hipError_t hipMemcpyWithStream(void* dst, const void* src, size_t sizeBytes, + hipMemcpyKind kind, hipStream_t stream); +/** + * @brief Copy data from Host to Device + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyHtoD(hipDeviceptr_t dst, void* src, size_t sizeBytes); +/** + * @brief Copy data from Device to Host + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyDtoH(void* dst, hipDeviceptr_t src, size_t sizeBytes); +/** + * @brief Copy data from Device to Device + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyDtoD(hipDeviceptr_t dst, hipDeviceptr_t src, size_t sizeBytes); +/** + * @brief Copies from one 1D array to device memory. + * + * @param[out] dstDevice Destination device pointer + * @param[in] srcArray Source array + * @param[in] srcOffset Offset in bytes of source array + * @param[in] ByteCount Size of memory copy in bytes + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyAtoD(hipDeviceptr_t dstDevice, hipArray_t srcArray, size_t srcOffset, + size_t ByteCount); +/** + * @brief Copies from device memory to a 1D array. + * + * @param[out] dstArray Destination array + * @param[in] dstOffset Offset in bytes of destination array + * @param[in] srcDevice Source device pointer + * @param[in] ByteCount Size of memory copy in bytes + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyDtoA(hipArray_t dstArray, size_t dstOffset, hipDeviceptr_t srcDevice, + size_t ByteCount); + +/** + * @brief Copies from one 1D array to another. + * + * @param[out] dstArray Destination array + * @param[in] dstOffset Offset in bytes of destination array + * @param[in] srcArray Source array + * @param[in] srcOffset Offset in bytes of source array + * @param[in] ByteCount Size of memory copy in bytes + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyAtoA(hipArray_t dstArray, size_t dstOffset, hipArray_t srcArray, + size_t srcOffset, size_t ByteCount); +/** + * @brief Copy data from Host to Device asynchronously + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * @param[in] stream Stream identifier + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyHtoDAsync(hipDeviceptr_t dst, void* src, size_t sizeBytes, hipStream_t stream); +/** + * @brief Copy data from Device to Host asynchronously + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * @param[in] stream Stream identifier + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyDtoHAsync(void* dst, hipDeviceptr_t src, size_t sizeBytes, hipStream_t stream); +/** + * @brief Copy data from Device to Device asynchronously + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * @param[in] stream Stream identifier + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyDtoDAsync(hipDeviceptr_t dst, hipDeviceptr_t src, size_t sizeBytes, + hipStream_t stream); +/** + * @brief Copies from one 1D array to host memory. + * + * @param[out] dstHost Destination pointer + * @param[in] srcArray Source array + * @param[in] srcOffset Offset in bytes of source array + * @param[in] ByteCount Size of memory copy in bytes + * @param[in] stream Stream identifier + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyAtoHAsync(void* dstHost, hipArray_t srcArray, size_t srcOffset, + size_t ByteCount, hipStream_t stream); +/** + * @brief Copies from host memory to a 1D array. + * + * @param[out] dstArray Destination array + * @param[in] dstOffset Offset in bytes of destination array + * @param[in] srcHost Source host pointer + * @param[in] ByteCount Size of memory copy in bytes + * @param[in] stream Stream identifier + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyHtoAAsync(hipArray_t dstArray, size_t dstOffset, const void* srcHost, + size_t ByteCount, hipStream_t stream); +/** + * @brief Returns a global pointer from a module. + * Returns in *dptr and *bytes the pointer and size of the global of name name located in module hmod. + * If no variable of that name exists, it returns hipErrorNotFound. Both parameters dptr and bytes are optional. + * If one of them is NULL, it is ignored and hipSuccess is returned. + * + * @param[out] dptr Returns global device pointer + * @param[out] bytes Returns global size in bytes + * @param[in] hmod Module to retrieve global from + * @param[in] name Name of global to retrieve + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotFound, #hipErrorInvalidContext + * + */ +hipError_t hipModuleGetGlobal(hipDeviceptr_t* dptr, size_t* bytes, + hipModule_t hmod, const char* name); + +/** + * @brief Gets device pointer associated with symbol on the device. + * + * @param[out] devPtr pointer to the device associated the symbole + * @param[in] symbol pointer to the symbole of the device + * + * @return #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipGetSymbolAddress(void** devPtr, const void* symbol); + + + +/** + * @brief Gets the size of the given symbol on the device. + * + * @param[in] symbol pointer to the device symbole + * @param[out] size pointer to the size + * + * @return #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipGetSymbolSize(size_t* size, const void* symbol); + +/** + * @brief Gets the pointer of requested HIP driver function. + * + * @param[in] symbol The Symbol name of the driver function to request. + * @param[out] pfn Output pointer to the requested driver function. + * @param[in] hipVersion The HIP version for the requested driver function symbol. + * HIP version is defined as 100*version_major + version_minor. For example, in HIP 6.1, the + * hipversion is 601, for the symbol function "hipGetDeviceProperties", the specified hipVersion 601 + * is greater or equal to the version 600, the symbol function will be handle properly as backend + * compatible function. + * + * @param[in] flags Currently only default flag is supported. + * @param[out] symbolStatus Optional enumeration for returned status of searching for symbol driver + * function based on the input hipVersion. + * + * Returns hipSuccess if the returned pfn is addressed to the pointer of found driver function. + * + * @return #hipSuccess, #hipErrorInvalidValue. + */ +hipError_t hipGetProcAddress(const char* symbol, void** pfn, int hipVersion, uint64_t flags, + hipDriverProcAddressQueryResult* symbolStatus); + +/** + * @brief Copies data to the given symbol on the device. + * Symbol HIP APIs allow a kernel to define a device-side data symbol which can be accessed on + * the host side. The symbol can be in __constant or device space. + * Note that the symbol name needs to be encased in the HIP_SYMBOL macro. + * This also applies to hipMemcpyFromSymbol, hipGetSymbolAddress, and hipGetSymbolSize. + * For detailed usage, see the + * memcpyToSymbol example + * in the HIP Porting Guide. + * + * + * @param[out] symbol pointer to the device symbole + * @param[in] src pointer to the source address + * @param[in] sizeBytes size in bytes to copy + * @param[in] offset offset in bytes from start of symbole + * @param[in] kind type of memory transfer + * + * @return #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipMemcpyToSymbol(const void* symbol, const void* src, + size_t sizeBytes, size_t offset __dparm(0), + hipMemcpyKind kind __dparm(hipMemcpyHostToDevice)); + +/** + * @brief Copies data to the given symbol on the device asynchronously. + * + * @param[out] symbol pointer to the device symbole + * @param[in] src pointer to the source address + * @param[in] sizeBytes size in bytes to copy + * @param[in] offset offset in bytes from start of symbole + * @param[in] kind type of memory transfer + * @param[in] stream stream identifier + * + * @return #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipMemcpyToSymbolAsync(const void* symbol, const void* src, + size_t sizeBytes, size_t offset, + hipMemcpyKind kind, hipStream_t stream __dparm(0)); + +/** + * @brief Copies data from the given symbol on the device. + * + * @param[out] dst Returns pointer to destinition memory address + * @param[in] symbol Pointer to the symbole address on the device + * @param[in] sizeBytes Size in bytes to copy + * @param[in] offset Offset in bytes from the start of symbole + * @param[in] kind Type of memory transfer + * + * @return #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipMemcpyFromSymbol(void* dst, const void* symbol, + size_t sizeBytes, size_t offset __dparm(0), + hipMemcpyKind kind __dparm(hipMemcpyDeviceToHost)); + +/** + * @brief Copies data from the given symbol on the device asynchronously. + * + * @param[out] dst Returns pointer to destinition memory address + * @param[in] symbol pointer to the symbole address on the device + * @param[in] sizeBytes size in bytes to copy + * @param[in] offset offset in bytes from the start of symbole + * @param[in] kind type of memory transfer + * @param[in] stream stream identifier + * + * @return #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipMemcpyFromSymbolAsync(void* dst, const void* symbol, + size_t sizeBytes, size_t offset, + hipMemcpyKind kind, + hipStream_t stream __dparm(0)); +/** + * @brief Copy data from src to dst asynchronously. + * + * @warning If host or dest are not pinned, the memory copy will be performed synchronously. For + * best performance, use hipHostMalloc to allocate host memory that is transferred asynchronously. + * + * @warning on HCC hipMemcpyAsync does not support overlapped H2D and D2H copies. + * For hipMemcpy, the copy is always performed by the device associated with the specified stream. + * + * For multi-gpu or peer-to-peer configurations, it is recommended to use a stream which is a + * attached to the device where the src data is physically located. For optimal peer-to-peer copies, + * the copy device must be able to access the src and dst pointers (by calling + * hipDeviceEnablePeerAccess with copy agent as the current device and src/dest as the peerDevice + * argument. if this is not done, the hipMemcpy will still work, but will perform the copy using a + * staging buffer on the host. + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * @param[in] kind Type of memory transfer + * @param[in] stream Stream identifier + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown + * + * @see hipMemcpy, hipMemcpy2D, hipMemcpyToArray, hipMemcpy2DToArray, hipMemcpyFromArray, + * hipMemcpy2DFromArray, hipMemcpyArrayToArray, hipMemcpy2DArrayToArray, hipMemcpyToSymbol, + * hipMemcpyFromSymbol, hipMemcpy2DAsync, hipMemcpyToArrayAsync, hipMemcpy2DToArrayAsync, + * hipMemcpyFromArrayAsync, hipMemcpy2DFromArrayAsync, hipMemcpyToSymbolAsync, + * hipMemcpyFromSymbolAsync + */ +hipError_t hipMemcpyAsync(void* dst, const void* src, size_t sizeBytes, hipMemcpyKind kind, + hipStream_t stream __dparm(0)); +/** + * @brief Fills the first sizeBytes bytes of the memory area pointed to by dest with the constant + * byte value value. + * + * @param[out] dst Data being filled + * @param[in] value Value to be set + * @param[in] sizeBytes Data size in bytes + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + */ +hipError_t hipMemset(void* dst, int value, size_t sizeBytes); +/** + * @brief Fills the first sizeBytes bytes of the memory area pointed to by dest with the constant + * byte value value. + * + * @param[out] dest Data ptr to be filled + * @param[in] value Value to be set + * @param[in] count Number of values to be set + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + */ +hipError_t hipMemsetD8(hipDeviceptr_t dest, unsigned char value, size_t count); +/** + * @brief Fills the first sizeBytes bytes of the memory area pointed to by dest with the constant + * byte value value. + * + * hipMemsetD8Async() is asynchronous with respect to the host, so the call may return before the + * memset is complete. The operation can optionally be associated to a stream by passing a non-zero + * stream argument. If stream is non-zero, the operation may overlap with operations in other + * streams. + * + * @param[out] dest Data ptr to be filled + * @param[in] value Constant value to be set + * @param[in] count Number of values to be set + * @param[in] stream Stream identifier + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + */ +hipError_t hipMemsetD8Async(hipDeviceptr_t dest, unsigned char value, size_t count, hipStream_t stream __dparm(0)); +/** + * @brief Fills the first sizeBytes bytes of the memory area pointed to by dest with the constant + * short value value. + * + * @param[out] dest Data ptr to be filled + * @param[in] value Constant value to be set + * @param[in] count Number of values to be set + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + */ +hipError_t hipMemsetD16(hipDeviceptr_t dest, unsigned short value, size_t count); +/** + * @brief Fills the first sizeBytes bytes of the memory area pointed to by dest with the constant + * short value value. + * + * hipMemsetD16Async() is asynchronous with respect to the host, so the call may return before the + * memset is complete. The operation can optionally be associated to a stream by passing a non-zero + * stream argument. If stream is non-zero, the operation may overlap with operations in other + * streams. + * + * @param[out] dest Data ptr to be filled + * @param[in] value Constant value to be set + * @param[in] count Number of values to be set + * @param[in] stream Stream identifier + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + */ +hipError_t hipMemsetD16Async(hipDeviceptr_t dest, unsigned short value, size_t count, hipStream_t stream __dparm(0)); +/** + * @brief Fills the memory area pointed to by dest with the constant integer + * value for specified number of times. + * + * @param[out] dest Data being filled + * @param[in] value Constant value to be set + * @param[in] count Number of values to be set + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + */ +hipError_t hipMemsetD32(hipDeviceptr_t dest, int value, size_t count); +/** + * @brief Fills the first sizeBytes bytes of the memory area pointed to by dev with the constant + * byte value value. + * + * hipMemsetAsync() is asynchronous with respect to the host, so the call may return before the + * memset is complete. The operation can optionally be associated to a stream by passing a non-zero + * stream argument. If stream is non-zero, the operation may overlap with operations in other + * streams. + * + * @param[out] dst Pointer to device memory + * @param[in] value Value to set for each byte of specified memory + * @param[in] sizeBytes Size in bytes to set + * @param[in] stream Stream identifier + * @return #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipMemsetAsync(void* dst, int value, size_t sizeBytes, hipStream_t stream __dparm(0)); +/** + * @brief Fills the memory area pointed to by dev with the constant integer + * value for specified number of times. + * + * hipMemsetD32Async() is asynchronous with respect to the host, so the call may return before the + * memset is complete. The operation can optionally be associated to a stream by passing a non-zero + * stream argument. If stream is non-zero, the operation may overlap with operations in other + * streams. + * + * @param[out] dst Pointer to device memory + * @param[in] value Value to set for each byte of specified memory + * @param[in] count Number of values to be set + * @param[in] stream Stream identifier + * @return #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipMemsetD32Async(hipDeviceptr_t dst, int value, size_t count, + hipStream_t stream __dparm(0)); +/** + * @brief Fills the memory area pointed to by dst with the constant value. + * + * @param[out] dst Pointer to device memory + * @param[in] pitch Data size in bytes + * @param[in] value Constant value to be set + * @param[in] width + * @param[in] height + * @return #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipMemset2D(void* dst, size_t pitch, int value, size_t width, size_t height); +/** + * @brief Fills asynchronously the memory area pointed to by dst with the constant value. + * + * @param[in] dst Pointer to 2D device memory + * @param[in] pitch Pitch size in bytes + * @param[in] value Value to be set for each byte of specified memory + * @param[in] width Width of matrix set columns in bytes + * @param[in] height Height of matrix set rows in bytes + * @param[in] stream Stream identifier + * @return #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipMemset2DAsync(void* dst, size_t pitch, int value, size_t width, size_t height,hipStream_t stream __dparm(0)); +/** + * @brief Fills synchronously the memory area pointed to by pitchedDevPtr with the constant value. + * + * @param[in] pitchedDevPtr Pointer to pitched device memory + * @param[in] value Value to set for each byte of specified memory + * @param[in] extent Size parameters for width field in bytes in device memory + * @return #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipMemset3D(hipPitchedPtr pitchedDevPtr, int value, hipExtent extent ); +/** + * @brief Fills asynchronously the memory area pointed to by pitchedDevPtr with the constant value. + * + * @param[in] pitchedDevPtr Pointer to pitched device memory + * @param[in] value Value to set for each byte of specified memory + * @param[in] extent Size parameters for width field in bytes in device memory + * @param[in] stream Stream identifier + * @return #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipMemset3DAsync(hipPitchedPtr pitchedDevPtr, int value, hipExtent extent ,hipStream_t stream __dparm(0)); +/** + * @brief Query memory info. + * + * On ROCM, this function gets the actual free memory left on the current device, so supports + * the cases while running multi-workload (such as multiple processes, multiple threads, and + * multiple GPUs). + * + * @warning On Windows, the free memory only accounts for memory allocated by this process and may + * be optimistic. + * + * @param[out] free Returns free memory on the current device in bytes + * @param[out] total Returns total allocatable memory on the current device in bytes + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + **/ +hipError_t hipMemGetInfo(size_t* free, size_t* total); + +/** + * @brief Get allocated memory size via memory pointer. + * + * This function gets the allocated shared virtual memory size from memory pointer. + * + * @param[in] ptr Pointer to allocated memory + * @param[out] size Returns the allocated memory size in bytes + * + * @return #hipSuccess, #hipErrorInvalidValue + * + **/ +hipError_t hipMemPtrGetInfo(void* ptr, size_t* size); +/** + * @brief Allocate an array on the device. + * + * @param[out] array Pointer to allocated array in device memory + * @param[in] desc Requested channel format + * @param[in] width Requested array allocation width + * @param[in] height Requested array allocation height + * @param[in] flags Requested properties of allocated array + * @return #hipSuccess, #hipErrorOutOfMemory + * + * @see hipMalloc, hipMallocPitch, hipFree, hipFreeArray, hipHostMalloc, hipHostFree + */ +hipError_t hipMallocArray(hipArray_t* array, const hipChannelFormatDesc* desc, size_t width, + size_t height __dparm(0), unsigned int flags __dparm(hipArrayDefault)); +/** + * @brief Create an array memory pointer on the device. + * + * @param[out] pHandle Pointer to the array memory + * @param[in] pAllocateArray Requested array desciptor + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipMallocArray, hipArrayDestroy, hipFreeArray + */ +hipError_t hipArrayCreate(hipArray_t* pHandle, const HIP_ARRAY_DESCRIPTOR* pAllocateArray); + /** + * @brief Destroy an array memory pointer on the device. + * + * @param[in] array Pointer to the array memory + * + * @return #hipSuccess, #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipFreeArray + */ +hipError_t hipArrayDestroy(hipArray_t array); +/** + * @brief Create a 3D array memory pointer on the device. + * + * @param[out] array Pointer to the 3D array memory + * @param[in] pAllocateArray Requested array desciptor + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipMallocArray, hipArrayDestroy, hipFreeArray + */ +hipError_t hipArray3DCreate(hipArray_t* array, const HIP_ARRAY3D_DESCRIPTOR* pAllocateArray); +/** + * @brief Create a 3D memory pointer on the device. + * + * @param[out] pitchedDevPtr Pointer to the 3D memory + * @param[in] extent Requested extent + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipMallocPitch, hipMemGetInfo, hipFree + */ +hipError_t hipMalloc3D(hipPitchedPtr* pitchedDevPtr, hipExtent extent); +/** + * @brief Frees an array on the device. + * + * @param[in] array Pointer to array to free + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + * + * @see hipMalloc, hipMallocPitch, hipFree, hipMallocArray, hipHostMalloc, hipHostFree + */ +hipError_t hipFreeArray(hipArray_t array); +/** + * @brief Allocate an array on the device. + * + * @param[out] array Pointer to allocated array in device memory + * @param[in] desc Requested channel format + * @param[in] extent Requested array allocation width, height and depth + * @param[in] flags Requested properties of allocated array + * @return #hipSuccess, #hipErrorOutOfMemory + * + * @see hipMalloc, hipMallocPitch, hipFree, hipFreeArray, hipHostMalloc, hipHostFree + */ +hipError_t hipMalloc3DArray(hipArray_t* array, const struct hipChannelFormatDesc* desc, + struct hipExtent extent, unsigned int flags); +/** + * @brief Gets info about the specified array + * + * @param[out] desc - Returned array type + * @param[out] extent - Returned array shape. 2D arrays will have depth of zero + * @param[out] flags - Returned array flags + * @param[in] array - The HIP array to get info for + * + * @return #hipSuccess, #hipErrorInvalidValue #hipErrorInvalidHandle + * + * @see hipArrayGetDescriptor, hipArray3DGetDescriptor + */ +hipError_t hipArrayGetInfo(hipChannelFormatDesc* desc, hipExtent* extent, unsigned int* flags, + hipArray_t array); +/** + * @brief Gets a 1D or 2D array descriptor + * + * @param[out] pArrayDescriptor - Returned array descriptor + * @param[in] array - Array to get descriptor of + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue #hipErrorInvalidHandle + * + * @see hipArray3DCreate, hipArray3DGetDescriptor, hipArrayCreate, hipArrayDestroy, hipMemAlloc, + * hipMemAllocHost, hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, + * hipMemcpy3D, hipMemcpy3DAsync, hipMemcpyAtoA, hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, + * hipMemcpyDtoA, hipMemcpyDtoD, hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, + * hipMemcpyHtoA, hipMemcpyHtoAAsync, hipMemcpyHtoD, hipMemcpyHtoDAsync, hipMemFree, + * hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, hipMemHostAlloc, + * hipMemHostGetDevicePointer, hipMemsetD8, hipMemsetD16, hipMemsetD32, hipArrayGetInfo + */ +hipError_t hipArrayGetDescriptor(HIP_ARRAY_DESCRIPTOR* pArrayDescriptor, hipArray_t array); +/** + * @brief Gets a 3D array descriptor + * + * @param[out] pArrayDescriptor - Returned 3D array descriptor + * @param[in] array - 3D array to get descriptor of + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue #hipErrorInvalidHandle, #hipErrorContextIsDestroyed + * + * @see hipArray3DCreate, hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, + * hipMemAllocHost, hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, + * hipMemcpy3D, hipMemcpy3DAsync, hipMemcpyAtoA, hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, + * hipMemcpyDtoA, hipMemcpyDtoD, hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, + * hipMemcpyHtoA, hipMemcpyHtoAAsync, hipMemcpyHtoD, hipMemcpyHtoDAsync, hipMemFree, + * hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, hipMemHostAlloc, + * hipMemHostGetDevicePointer, hipMemsetD8, hipMemsetD16, hipMemsetD32, hipArrayGetInfo + */ +hipError_t hipArray3DGetDescriptor(HIP_ARRAY3D_DESCRIPTOR* pArrayDescriptor, hipArray_t array); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] dpitch Pitch of destination memory + * @param[in] src Source memory address + * @param[in] spitch Pitch of source memory + * @param[in] width Width of matrix transfer (columns in bytes) + * @param[in] height Height of matrix transfer (rows) + * @param[in] kind Type of transfer + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpyToArray, hipMemcpy2DToArray, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy2D(void* dst, size_t dpitch, const void* src, size_t spitch, size_t width, + size_t height, hipMemcpyKind kind); +/** + * @brief Copies memory for 2D arrays. + * @param[in] pCopy Parameters for the memory copy + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2D, hipMemcpyToArray, hipMemcpy2DToArray, hipMemcpyFromArray, + * hipMemcpyToSymbol, hipMemcpyAsync +*/ +hipError_t hipMemcpyParam2D(const hip_Memcpy2D* pCopy); +/** + * @brief Copies memory for 2D arrays. + * @param[in] pCopy Parameters for the memory copy + * @param[in] stream Stream to use + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2D, hipMemcpyToArray, hipMemcpy2DToArray, hipMemcpyFromArray, + * hipMemcpyToSymbol, hipMemcpyAsync +*/ +hipError_t hipMemcpyParam2DAsync(const hip_Memcpy2D* pCopy, hipStream_t stream __dparm(0)); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] dpitch Pitch of destination memory + * @param[in] src Source memory address + * @param[in] spitch Pitch of source memory + * @param[in] width Width of matrix transfer (columns in bytes) + * @param[in] height Height of matrix transfer (rows) + * @param[in] kind Type of transfer + * @param[in] stream Stream to use + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpyToArray, hipMemcpy2DToArray, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy2DAsync(void* dst, size_t dpitch, const void* src, size_t spitch, size_t width, + size_t height, hipMemcpyKind kind, hipStream_t stream __dparm(0)); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] wOffset Destination starting X offset + * @param[in] hOffset Destination starting Y offset + * @param[in] src Source memory address + * @param[in] spitch Pitch of source memory + * @param[in] width Width of matrix transfer (columns in bytes) + * @param[in] height Height of matrix transfer (rows) + * @param[in] kind Type of transfer + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpyToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy2DToArray(hipArray_t dst, size_t wOffset, size_t hOffset, const void* src, + size_t spitch, size_t width, size_t height, hipMemcpyKind kind); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] wOffset Destination starting X offset + * @param[in] hOffset Destination starting Y offset + * @param[in] src Source memory address + * @param[in] spitch Pitch of source memory + * @param[in] width Width of matrix transfer (columns in bytes) + * @param[in] height Height of matrix transfer (rows) + * @param[in] kind Type of transfer + * @param[in] stream Accelerator view which the copy is being enqueued + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpyToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy2DToArrayAsync(hipArray_t dst, size_t wOffset, size_t hOffset, const void* src, + size_t spitch, size_t width, size_t height, hipMemcpyKind kind, + hipStream_t stream __dparm(0)); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] wOffsetDst Destination starting X offset + * @param[in] hOffsetDst Destination starting Y offset + * @param[in] src Source memory address + * @param[in] wOffsetSrc Source starting X offset + * @param[in] hOffsetSrc Source starting Y offset (columns in bytes) + * @param[in] width Width of matrix transfer (columns in bytes) + * @param[in] height Height of matrix transfer (rows) + * @param[in] kind Type of transfer + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpyToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy2DArrayToArray(hipArray_t dst, size_t wOffsetDst, size_t hOffsetDst, + hipArray_const_t src, size_t wOffsetSrc, size_t hOffsetSrc, + size_t width, size_t height, hipMemcpyKind kind); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] wOffset Destination starting X offset + * @param[in] hOffset Destination starting Y offset + * @param[in] src Source memory address + * @param[in] count size in bytes to copy + * @param[in] kind Type of transfer + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + * @warning This API is deprecated. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipMemcpyToArray(hipArray_t dst, size_t wOffset, size_t hOffset, const void* src, + size_t count, hipMemcpyKind kind); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] srcArray Source memory address + * @param[in] wOffset Source starting X offset + * @param[in] hOffset Source starting Y offset + * @param[in] count Size in bytes to copy + * @param[in] kind Type of transfer + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + * @warning This API is deprecated. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipMemcpyFromArray(void* dst, hipArray_const_t srcArray, size_t wOffset, size_t hOffset, + size_t count, hipMemcpyKind kind); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] dpitch Pitch of destination memory + * @param[in] src Source memory address + * @param[in] wOffset Source starting X offset + * @param[in] hOffset Source starting Y offset + * @param[in] width Width of matrix transfer (columns in bytes) + * @param[in] height Height of matrix transfer (rows) + * @param[in] kind Type of transfer + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy2DFromArray( void* dst, size_t dpitch, hipArray_const_t src, size_t wOffset, size_t hOffset, size_t width, size_t height, hipMemcpyKind kind); +/** + * @brief Copies data between host and device asynchronously. + * + * @param[in] dst Destination memory address + * @param[in] dpitch Pitch of destination memory + * @param[in] src Source memory address + * @param[in] wOffset Source starting X offset + * @param[in] hOffset Source starting Y offset + * @param[in] width Width of matrix transfer (columns in bytes) + * @param[in] height Height of matrix transfer (rows) + * @param[in] kind Type of transfer + * @param[in] stream Accelerator view which the copy is being enqueued + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy2DFromArrayAsync( void* dst, size_t dpitch, hipArray_const_t src, size_t wOffset, size_t hOffset, size_t width, size_t height, hipMemcpyKind kind, hipStream_t stream __dparm(0)); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] srcArray Source array + * @param[in] srcOffset Offset in bytes of source array + * @param[in] count Size of memory copy in bytes + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpyAtoH(void* dst, hipArray_t srcArray, size_t srcOffset, size_t count); +/** + * @brief Copies data between host and device. + * + * @param[in] dstArray Destination memory address + * @param[in] dstOffset Offset in bytes of destination array + * @param[in] srcHost Source host pointer + * @param[in] count Size of memory copy in bytes + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpyHtoA(hipArray_t dstArray, size_t dstOffset, const void* srcHost, size_t count); +/** + * @brief Copies data between host and device. + * + * @param[in] p 3D memory copy parameters + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy3D(const struct hipMemcpy3DParms* p); +/** + * @brief Copies data between host and device asynchronously. + * + * @param[in] p 3D memory copy parameters + * @param[in] stream Stream to use + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy3DAsync(const struct hipMemcpy3DParms* p, hipStream_t stream __dparm(0)); +/** + * @brief Copies data between host and device. + * + * @param[in] pCopy 3D memory copy parameters + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipDrvMemcpy3D(const HIP_MEMCPY3D* pCopy); +/** + * @brief Copies data between host and device asynchronously. + * + * @param[in] pCopy 3D memory copy parameters + * @param[in] stream Stream to use + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipDrvMemcpy3DAsync(const HIP_MEMCPY3D* pCopy, hipStream_t stream); +// doxygen end Memory +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup PeerToPeer PeerToPeer Device Memory Access + * @{ + * @warning PeerToPeer support is experimental. + * This section describes the PeerToPeer device memory access functions of HIP runtime API. + */ +/** + * @brief Determine if a device can access a peer's memory. + * + * @param [out] canAccessPeer Returns the peer access capability (0 or 1) + * @param [in] deviceId - device from where memory may be accessed. + * @param [in] peerDeviceId - device where memory is physically located + * + * Returns "1" in @p canAccessPeer if the specified @p device is capable + * of directly accessing memory physically located on peerDevice , or "0" if not. + * + * Returns "0" in @p canAccessPeer if deviceId == peerDeviceId, and both are valid devices : a + * device is not a peer of itself. + * + * @returns #hipSuccess, + * @returns #hipErrorInvalidDevice if deviceId or peerDeviceId are not valid devices + */ +hipError_t hipDeviceCanAccessPeer(int* canAccessPeer, int deviceId, int peerDeviceId); +/** + * @brief Enable direct access from current device's virtual address space to memory allocations + * physically located on a peer device. + * + * Memory which already allocated on peer device will be mapped into the address space of the + * current device. In addition, all future memory allocations on peerDeviceId will be mapped into + * the address space of the current device when the memory is allocated. The peer memory remains + * accessible from the current device until a call to hipDeviceDisablePeerAccess or hipDeviceReset. + * + * + * @param [in] peerDeviceId Peer device to enable direct access to from the current device + * @param [in] flags Reserved for future use, must be zero + * + * Returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue, + * @returns #hipErrorPeerAccessAlreadyEnabled if peer access is already enabled for this device. + */ +hipError_t hipDeviceEnablePeerAccess(int peerDeviceId, unsigned int flags); +/** + * @brief Disable direct access from current device's virtual address space to memory allocations + * physically located on a peer device. + * + * Returns hipErrorPeerAccessNotEnabled if direct access to memory on peerDevice has not yet been + * enabled from the current device. + * + * @param [in] peerDeviceId Peer device to disable direct access to + * + * @returns #hipSuccess, #hipErrorPeerAccessNotEnabled + */ +hipError_t hipDeviceDisablePeerAccess(int peerDeviceId); +/** + * @brief Get information on memory allocations. + * + * @param [out] pbase - BAse pointer address + * @param [out] psize - Size of allocation + * @param [in] dptr- Device Pointer + * + * @returns #hipSuccess, #hipErrorNotFound + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + */ +hipError_t hipMemGetAddressRange(hipDeviceptr_t* pbase, size_t* psize, hipDeviceptr_t dptr); +#ifndef USE_PEER_NON_UNIFIED +#define USE_PEER_NON_UNIFIED 1 +#endif +#if USE_PEER_NON_UNIFIED == 1 +/** + * @brief Copies memory from one device to memory on another device. + * + * @param [out] dst - Destination device pointer. + * @param [in] dstDeviceId - Destination device + * @param [in] src - Source device pointer + * @param [in] srcDeviceId - Source device + * @param [in] sizeBytes - Size of memory copy in bytes + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidDevice + */ +hipError_t hipMemcpyPeer(void* dst, int dstDeviceId, const void* src, int srcDeviceId, + size_t sizeBytes); +/** + * @brief Copies memory from one device to memory on another device. + * + * @param [out] dst - Destination device pointer. + * @param [in] dstDeviceId - Destination device + * @param [in] src - Source device pointer + * @param [in] srcDevice - Source device + * @param [in] sizeBytes - Size of memory copy in bytes + * @param [in] stream - Stream identifier + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidDevice + */ +hipError_t hipMemcpyPeerAsync(void* dst, int dstDeviceId, const void* src, int srcDevice, + size_t sizeBytes, hipStream_t stream __dparm(0)); +#endif +// doxygen end PeerToPeer +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Context Context Management [Deprecated] + * @{ + * This section describes the context management functions of HIP runtime API. + * + * @warning + * + * On the AMD platform, context management APIs are deprecated as there are better alternate + * interfaces, such as using hipSetDevice and stream APIs to achieve the required functionality. + * + * On the NVIDIA platform, CUDA supports the driver API that defines "Context" and "Devices" as + * separate entities. Each context contains a single device, which can theoretically have multiple + * contexts. HIP initially added limited support for these APIs to facilitate easy porting from + * existing driver codes. + * + * These APIs are only for equivalent driver APIs on the NVIDIA platform. + * + */ + +/** + * @brief Create a context and set it as current/default context + * + * @param [out] ctx Context to create + * @param [in] flags Context creation flags + * @param [in] device device handle + * + * @return #hipSuccess + * + * @see hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, hipCtxPushCurrent, + * hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxCreate(hipCtx_t* ctx, unsigned int flags, hipDevice_t device); +/** + * @brief Destroy a HIP context. + * + * @param [in] ctx Context to destroy + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @see hipCtxCreate, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent,hipCtxSetCurrent, + * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize , hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxDestroy(hipCtx_t ctx); +/** + * @brief Pop the current/default context and return the popped context. + * + * @param [out] ctx The current context to pop + * + * @returns #hipSuccess, #hipErrorInvalidContext + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxSetCurrent, hipCtxGetCurrent, + * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxPopCurrent(hipCtx_t* ctx); +/** + * @brief Push the context to be set as current/ default context + * + * @param [in] ctx The current context to push + * + * @returns #hipSuccess, #hipErrorInvalidContext + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize , hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxPushCurrent(hipCtx_t ctx); +/** + * @brief Set the passed context as current/default + * + * @param [in] ctx The context to set as current + * + * @returns #hipSuccess, #hipErrorInvalidContext + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize , hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxSetCurrent(hipCtx_t ctx); +/** + * @brief Get the handle of the current/ default context + * + * @param [out] ctx The context to get as current + * + * @returns #hipSuccess, #hipErrorInvalidContext + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetDevice, hipCtxGetFlags, hipCtxPopCurrent, + * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxGetCurrent(hipCtx_t* ctx); +/** + * @brief Get the handle of the device associated with current/default context + * + * @param [out] device The device from the current context + * + * @returns #hipSuccess, #hipErrorInvalidContext + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxGetDevice(hipDevice_t* device); +/** + * @brief Returns the approximate HIP api version. + * + * @param [in] ctx Context to check + * @param [out] apiVersion API version to get + * + * @return #hipSuccess + * + * @warning The HIP feature set does not correspond to an exact CUDA SDK api revision. + * This function always set *apiVersion to 4 as an approximation though HIP supports + * some features which were introduced in later CUDA SDK revisions. + * HIP apps code should not rely on the api revision number here and should + * use arch feature flags to test device capabilities or conditional compilation. + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetDevice, hipCtxGetFlags, hipCtxPopCurrent, + * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxGetApiVersion(hipCtx_t ctx, int* apiVersion); +/** + * @brief Get Cache configuration for a specific function + * + * @param [out] cacheConfig Cache configuration + * + * @return #hipSuccess + * + * @warning AMD devices and some Nvidia GPUS do not support reconfigurable cache. This hint is + * ignored on those architectures. + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxGetCacheConfig(hipFuncCache_t* cacheConfig); +/** + * @brief Set L1/Shared cache partition. + * + * @param [in] cacheConfig Cache configuration to set + * + * @return #hipSuccess + * + * @warning AMD devices and some Nvidia GPUS do not support reconfigurable cache. This hint is + * ignored on those architectures. + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxSetCacheConfig(hipFuncCache_t cacheConfig); +/** + * @brief Set Shared memory bank configuration. + * + * @param [in] config Shared memory configuration to set + * + * @return #hipSuccess + * + * @warning AMD devices and some Nvidia GPUS do not support shared cache banking, and the hint is + * ignored on those architectures. + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxSetSharedMemConfig(hipSharedMemConfig config); +/** + * @brief Get Shared memory bank configuration. + * + * @param [out] pConfig Pointer of shared memory configuration + * + * @return #hipSuccess + * + * @warning AMD devices and some Nvidia GPUS do not support shared cache banking, and the hint is + * ignored on those architectures. + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxGetSharedMemConfig(hipSharedMemConfig* pConfig); +/** + * @brief Blocks until the default context has completed all preceding requested tasks. + * + * @return #hipSuccess + * + * @warning This function waits for all streams on the default context to complete execution, and + * then returns. + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxSynchronize(void); +/** + * @brief Return flags used for creating default context. + * + * @param [out] flags Pointer of flags + * + * @returns #hipSuccess + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxPopCurrent, hipCtxGetCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxGetFlags(unsigned int* flags); +/** + * @brief Enables direct access to memory allocations in a peer context. + * + * Memory which already allocated on peer device will be mapped into the address space of the + * current device. In addition, all future memory allocations on peerDeviceId will be mapped into + * the address space of the current device when the memory is allocated. The peer memory remains + * accessible from the current device until a call to hipDeviceDisablePeerAccess or hipDeviceReset. + * + * + * @param [in] peerCtx Peer context + * @param [in] flags flags, need to set as 0 + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue, + * #hipErrorPeerAccessAlreadyEnabled + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * @warning PeerToPeer support is experimental. + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxEnablePeerAccess(hipCtx_t peerCtx, unsigned int flags); +/** + * @brief Disable direct access from current context's virtual address space to memory allocations + * physically located on a peer context.Disables direct access to memory allocations in a peer + * context and unregisters any registered allocations. + * + * Returns #hipErrorPeerAccessNotEnabled if direct access to memory on peerDevice has not yet been + * enabled from the current device. + * + * @param [in] peerCtx Peer context to be disabled + * + * @returns #hipSuccess, #hipErrorPeerAccessNotEnabled + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * @warning PeerToPeer support is experimental. + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxDisablePeerAccess(hipCtx_t peerCtx); + +/** + * @brief Get the state of the primary context. + * + * @param [in] dev Device to get primary context flags for + * @param [out] flags Pointer to store flags + * @param [out] active Pointer to store context state; 0 = inactive, 1 = active + * + * @returns #hipSuccess + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipDevicePrimaryCtxGetState(hipDevice_t dev, unsigned int* flags, int* active); +/** + * @brief Release the primary context on the GPU. + * + * @param [in] dev Device which primary context is released + * + * @returns #hipSuccess + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * @warning This function return #hipSuccess though doesn't release the primaryCtx by design on + * HIP/HCC path. + * + * @warning This API is deprecated on the AMD platform, only for equivalent driver API on the NVIDIA + * platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipDevicePrimaryCtxRelease(hipDevice_t dev); +/** + * @brief Retain the primary context on the GPU. + * + * @param [out] pctx Returned context handle of the new context + * @param [in] dev Device which primary context is released + * + * @returns #hipSuccess + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent driver API on the NVIDIA + * platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipDevicePrimaryCtxRetain(hipCtx_t* pctx, hipDevice_t dev); +/** + * @brief Resets the primary context on the GPU. + * + * @param [in] dev Device which primary context is reset + * + * @returns #hipSuccess + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent driver API on the NVIDIA + * platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipDevicePrimaryCtxReset(hipDevice_t dev); +/** + * @brief Set flags for the primary context. + * + * @param [in] dev Device for which the primary context flags are set + * @param [in] flags New flags for the device + * + * @returns #hipSuccess, #hipErrorContextAlreadyInUse + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent driver API on the NVIDIA + * platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipDevicePrimaryCtxSetFlags(hipDevice_t dev, unsigned int flags); +// doxygen end Context Management +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * + * @defgroup Module Module Management + * @{ + * @ingroup API + * This section describes the module management functions of HIP runtime API. + * + */ +/** + * @brief Loads code object from file into a module in the current context. + * + * @param [in] fname Filename of code object to load + + * @param [out] module Module + * + * @warning File/memory resources allocated in this function are released only in hipModuleUnload. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidContext, #hipErrorFileNotFound, + * #hipErrorOutOfMemory, #hipErrorSharedObjectInitFailed, #hipErrorNotInitialized + * + */ +hipError_t hipModuleLoad(hipModule_t* module, const char* fname); +/** + * @brief Frees the module + * + * @param [in] module Module to free + * + * @returns #hipSuccess, #hipErrorInvalidResourceHandle + * + * The module is freed, and the code objects associated with it are destroyed. + */ +hipError_t hipModuleUnload(hipModule_t module); +/** + * @brief Function with kname will be extracted if present in module + * + * @param [in] module Module to get function from + * @param [in] kname Pointer to the name of function + * @param [out] function Pointer to function handle + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidContext, #hipErrorNotInitialized, + * #hipErrorNotFound, + */ +hipError_t hipModuleGetFunction(hipFunction_t* function, hipModule_t module, const char* kname); +/** + * @brief Find out attributes for a given function. + * + * @param [out] attr Attributes of funtion + * @param [in] func Pointer to the function handle + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidDeviceFunction + */ +hipError_t hipFuncGetAttributes(struct hipFuncAttributes* attr, const void* func); +/** + * @brief Find out a specific attribute for a given function. + * + * @param [out] value Pointer to the value + * @param [in] attrib Attributes of the given funtion + * @param [in] hfunc Function to get attributes from + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidDeviceFunction + */ +hipError_t hipFuncGetAttribute(int* value, hipFunction_attribute attrib, hipFunction_t hfunc); +/** + * @brief Gets pointer to device entry function that matches entry function symbolPtr. + * + * @param [out] functionPtr Device entry function + * @param [in] symbolPtr Pointer to device entry function to search for + * + * @returns #hipSuccess, #hipErrorInvalidDeviceFunction + * + */ +hipError_t hipGetFuncBySymbol(hipFunction_t* functionPtr, const void* symbolPtr); +/** + * @brief returns the handle of the texture reference with the name from the module. + * + * @param [in] hmod Module + * @param [in] name Pointer of name of texture reference + * @param [out] texRef Pointer of texture reference + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorNotFound, #hipErrorInvalidValue + */ +hipError_t hipModuleGetTexRef(textureReference** texRef, hipModule_t hmod, const char* name); +/** + * @brief builds module from code object which resides in host memory. Image is pointer to that + * location. + * + * @param [in] image The pointer to the location of data + * @param [out] module Retuned module + * + * @returns hipSuccess, hipErrorNotInitialized, hipErrorOutOfMemory, hipErrorNotInitialized + */ +hipError_t hipModuleLoadData(hipModule_t* module, const void* image); +/** + * @brief builds module from code object which resides in host memory. Image is pointer to that + * location. Options are not used. hipModuleLoadData is called. + * + * @param [in] image The pointer to the location of data + * @param [out] module Retuned module + * @param [in] numOptions Number of options + * @param [in] options Options for JIT + * @param [in] optionValues Option values for JIT + * + * @returns hipSuccess, hipErrorNotInitialized, hipErrorOutOfMemory, hipErrorNotInitialized + */ +hipError_t hipModuleLoadDataEx(hipModule_t* module, const void* image, unsigned int numOptions, + hipJitOption* options, void** optionValues); +/** + * @brief launches kernel f with launch parameters and shared memory on stream with arguments passed + * to kernelparams or extra + * + * @param [in] f Kernel to launch. + * @param [in] gridDimX X grid dimension specified as multiple of blockDimX. + * @param [in] gridDimY Y grid dimension specified as multiple of blockDimY. + * @param [in] gridDimZ Z grid dimension specified as multiple of blockDimZ. + * @param [in] blockDimX X block dimensions specified in work-items + * @param [in] blockDimY Y grid dimension specified in work-items + * @param [in] blockDimZ Z grid dimension specified in work-items + * @param [in] sharedMemBytes Amount of dynamic shared memory to allocate for this kernel. The + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream Stream where the kernel should be dispatched. May be 0, in which case th + * default stream is used with associated synchronization rules. + * @param [in] kernelParams Kernel parameters to launch + * @param [in] extra Pointer to kernel arguments. These are passed directly to the kernel and + * must be in the memory layout and alignment expected by the kernel. + * All passed arguments must be naturally aligned according to their type. The memory address of each + * argument should be a multiple of its size in bytes. Please refer to hip_porting_driver_api.md + * for sample usage. + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. So gridDim.x * blockDim.x, gridDim.y * blockDim.y + * and gridDim.z * blockDim.z are always less than 2^32. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue + */ +hipError_t 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); +/** + * @brief launches kernel f with launch parameters and shared memory on stream with arguments passed + * to kernelParams, where thread blocks can cooperate and synchronize as they execute + * + * @param [in] f Kernel to launch. + * @param [in] gridDimX X grid dimension specified as multiple of blockDimX. + * @param [in] gridDimY Y grid dimension specified as multiple of blockDimY. + * @param [in] gridDimZ Z grid dimension specified as multiple of blockDimZ. + * @param [in] blockDimX X block dimension specified in work-items. + * @param [in] blockDimY Y block dimension specified in work-items. + * @param [in] blockDimZ Z block dimension specified in work-items. + * @param [in] sharedMemBytes Amount of dynamic shared memory to allocate for this kernel. The + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream Stream where the kernel should be dispatched. May be 0, + * in which case the default stream is used with associated synchronization rules. + * @param [in] kernelParams A list of kernel arguments. + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidHandle, #hipErrorInvalidImage, #hipErrorInvalidValue, + * #hipErrorInvalidConfiguration, #hipErrorLaunchFailure, #hipErrorLaunchOutOfResources, + * #hipErrorLaunchTimeOut, #hipErrorCooperativeLaunchTooLarge, #hipErrorSharedObjectInitFailed + */ +hipError_t 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); +/** + * @brief Launches kernels on multiple devices where thread blocks can cooperate and + * synchronize as they execute. + * + * @param [in] launchParamsList List of launch parameters, one per device. + * @param [in] numDevices Size of the launchParamsList array. + * @param [in] flags Flags to control launch behavior. + * + * @returns #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidHandle, #hipErrorInvalidImage, #hipErrorInvalidValue, + * #hipErrorInvalidConfiguration, #hipErrorInvalidResourceHandle, #hipErrorLaunchFailure, + * #hipErrorLaunchOutOfResources, #hipErrorLaunchTimeOut, #hipErrorCooperativeLaunchTooLarge, + * #hipErrorSharedObjectInitFailed + */ +hipError_t hipModuleLaunchCooperativeKernelMultiDevice(hipFunctionLaunchParams* launchParamsList, + unsigned int numDevices, + unsigned int flags); +/** + * @brief launches kernel f with launch parameters and shared memory on stream with arguments passed + * to kernelparams or extra, where thread blocks can cooperate and synchronize as they execute + * + * @param [in] f Kernel to launch. + * @param [in] gridDim Grid dimensions specified as multiple of blockDim. + * @param [in] blockDimX Block dimensions specified in work-items + * @param [in] kernelParams A list of kernel arguments + * @param [in] sharedMemBytes Amount of dynamic shared memory to allocate for this kernel. The + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream Stream where the kernel should be dispatched. May be 0, in which case th + * default stream is used with associated synchronization rules. + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue, #hipErrorCooperativeLaunchTooLarge + */ +hipError_t hipLaunchCooperativeKernel(const void* f, dim3 gridDim, dim3 blockDimX, + void** kernelParams, unsigned int sharedMemBytes, + hipStream_t stream); +/** + * @brief Launches kernels on multiple devices where thread blocks can cooperate and + * synchronize as they execute. + * + * @param [in] launchParamsList List of launch parameters, one per device. + * @param [in] numDevices Size of the launchParamsList array. + * @param [in] flags Flags to control launch behavior. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue, + * #hipErrorCooperativeLaunchTooLarge + */ +hipError_t hipLaunchCooperativeKernelMultiDevice(hipLaunchParams* launchParamsList, + int numDevices, unsigned int flags); +/** + * @brief Launches kernels on multiple devices and guarantees all specified kernels are dispatched + * on respective streams before enqueuing any other work on the specified streams from any other threads + * + * + * @param [in] launchParamsList List of launch parameters, one per device. + * @param [in] numDevices Size of the launchParamsList array. + * @param [in] flags Flags to control launch behavior. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue + */ +hipError_t hipExtLaunchMultiKernelMultiDevice(hipLaunchParams* launchParamsList, + int numDevices, unsigned int flags); +// doxygen end Module +/** + * @} + */ + +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Occupancy Occupancy + * @{ + * This section describes the occupancy functions of HIP runtime API. + * + */ +/** + * @brief determine the grid and block sizes to achieves maximum occupancy for a kernel + * + * @param [out] gridSize minimum grid size for maximum potential occupancy + * @param [out] blockSize block size for maximum potential occupancy + * @param [in] f kernel function for which occupancy is calulated + * @param [in] dynSharedMemPerBlk dynamic shared memory usage (in bytes) intended for each block + * @param [in] blockSizeLimit the maximum block size for the kernel, use 0 for no limit + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +//TODO - Match CUoccupancyB2DSize +hipError_t hipModuleOccupancyMaxPotentialBlockSize(int* gridSize, int* blockSize, + hipFunction_t f, size_t dynSharedMemPerBlk, + int blockSizeLimit); +/** + * @brief determine the grid and block sizes to achieves maximum occupancy for a kernel + * + * @param [out] gridSize minimum grid size for maximum potential occupancy + * @param [out] blockSize block size for maximum potential occupancy + * @param [in] f kernel function for which occupancy is calulated + * @param [in] dynSharedMemPerBlk dynamic shared memory usage (in bytes) intended for each block + * @param [in] blockSizeLimit the maximum block size for the kernel, use 0 for no limit + * @param [in] flags Extra flags for occupancy calculation (only default supported) + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +//TODO - Match CUoccupancyB2DSize +hipError_t hipModuleOccupancyMaxPotentialBlockSizeWithFlags(int* gridSize, int* blockSize, + hipFunction_t f, size_t dynSharedMemPerBlk, + int blockSizeLimit, unsigned int flags); +/** + * @brief Returns occupancy for a device function. + * + * @param [out] numBlocks Returned occupancy + * @param [in] f Kernel function (hipFunction) for which occupancy is calulated + * @param [in] blockSize Block size the kernel is intended to be launched with + * @param [in] dynSharedMemPerBlk Dynamic shared memory usage (in bytes) intended for each block + * @returns #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipModuleOccupancyMaxActiveBlocksPerMultiprocessor( + int* numBlocks, hipFunction_t f, int blockSize, size_t dynSharedMemPerBlk); +/** + * @brief Returns occupancy for a device function. + * + * @param [out] numBlocks Returned occupancy + * @param [in] f Kernel function(hipFunction_t) for which occupancy is calulated + * @param [in] blockSize Block size the kernel is intended to be launched with + * @param [in] dynSharedMemPerBlk Dynamic shared memory usage (in bytes) intended for each block + * @param [in] flags Extra flags for occupancy calculation (only default supported) + * @returns #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( + int* numBlocks, hipFunction_t f, int blockSize, size_t dynSharedMemPerBlk, unsigned int flags); +/** + * @brief Returns occupancy for a device function. + * + * @param [out] numBlocks Returned occupancy + * @param [in] f Kernel function for which occupancy is calulated + * @param [in] blockSize Block size the kernel is intended to be launched with + * @param [in] dynSharedMemPerBlk Dynamic shared memory usage (in bytes) intended for each block + * @returns #hipSuccess, #hipErrorInvalidDeviceFunction, #hipErrorInvalidValue + */ +hipError_t hipOccupancyMaxActiveBlocksPerMultiprocessor( + int* numBlocks, const void* f, int blockSize, size_t dynSharedMemPerBlk); +/** + * @brief Returns occupancy for a device function. + * + * @param [out] numBlocks Returned occupancy + * @param [in] f Kernel function for which occupancy is calulated + * @param [in] blockSize Block size the kernel is intended to be launched with + * @param [in] dynSharedMemPerBlk Dynamic shared memory usage (in bytes) intended for each block + * @param [in] flags Extra flags for occupancy calculation (currently ignored) + * @returns #hipSuccess, #hipErrorInvalidDeviceFunction, #hipErrorInvalidValue + */ +hipError_t hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( + int* numBlocks, const void* f, int blockSize, size_t dynSharedMemPerBlk, unsigned int flags __dparm(hipOccupancyDefault)); +/** + * @brief determine the grid and block sizes to achieves maximum occupancy for a kernel + * + * @param [out] gridSize minimum grid size for maximum potential occupancy + * @param [out] blockSize block size for maximum potential occupancy + * @param [in] f kernel function for which occupancy is calulated + * @param [in] dynSharedMemPerBlk dynamic shared memory usage (in bytes) intended for each block + * @param [in] blockSizeLimit the maximum block size for the kernel, use 0 for no limit + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipOccupancyMaxPotentialBlockSize(int* gridSize, int* blockSize, + const void* f, size_t dynSharedMemPerBlk, + int blockSizeLimit); +// doxygen end Occupancy +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Profiler Profiler Control[Deprecated] + * @{ + * This section describes the profiler control functions of HIP runtime API. + * + * @warning The cudaProfilerInitialize API format for "configFile" is not supported. + * + */ +// TODO - expand descriptions: +/** + * @brief Start recording of profiling information + * When using this API, start the profiler with profiling disabled. (--startdisabled) + * @returns #hipErrorNotSupported + * @warning : hipProfilerStart API is deprecated, use roctracer/rocTX instead. + */ +DEPRECATED("use roctracer/rocTX instead") +hipError_t hipProfilerStart(); +/** + * @brief Stop recording of profiling information. + * When using this API, start the profiler with profiling disabled. (--startdisabled) + * @returns #hipErrorNotSupported + * @warning hipProfilerStart API is deprecated, use roctracer/rocTX instead. + */ +DEPRECATED("use roctracer/rocTX instead") +hipError_t hipProfilerStop(); +// doxygen end profiler +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Clang Launch API to support the triple-chevron syntax + * @{ + * This section describes the API to support the triple-chevron syntax. + */ +/** + * @brief Configure a kernel launch. + * + * @param [in] gridDim grid dimension specified as multiple of blockDim. + * @param [in] blockDim block dimensions specified in work-items + * @param [in] sharedMem Amount of dynamic shared memory to allocate for this kernel. The + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream Stream where the kernel should be dispatched. May be 0, in which case the + * default stream is used with associated synchronization rules. + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue + * + */ +hipError_t hipConfigureCall(dim3 gridDim, dim3 blockDim, size_t sharedMem __dparm(0), hipStream_t stream __dparm(0)); +/** + * @brief Set a kernel argument. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue + * + * @param [in] arg Pointer the argument in host memory. + * @param [in] size Size of the argument. + * @param [in] offset Offset of the argument on the argument stack. + * + */ +hipError_t hipSetupArgument(const void* arg, size_t size, size_t offset); +/** + * @brief Launch a kernel. + * + * @param [in] func Kernel to launch. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue + * + */ +hipError_t hipLaunchByPtr(const void* func); +/** + * @brief Push configuration of a kernel launch. + * + * @param [in] gridDim grid dimension specified as multiple of blockDim. + * @param [in] blockDim block dimensions specified in work-items + * @param [in] sharedMem Amount of dynamic shared memory to allocate for this kernel. The + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream Stream where the kernel should be dispatched. May be 0, in which case the + * default stream is used with associated synchronization rules. + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue + * + */ +hipError_t __hipPushCallConfiguration(dim3 gridDim, + dim3 blockDim, + size_t sharedMem __dparm(0), + hipStream_t stream __dparm(0)); +/** + * @brief Pop configuration of a kernel launch. + * + * @param [out] gridDim grid dimension specified as multiple of blockDim. + * @param [out] blockDim block dimensions specified in work-items + * @param [out] sharedMem Amount of dynamic shared memory to allocate for this kernel. The + * HIP-Clang compiler provides support for extern shared declarations. + * @param [out] stream Stream where the kernel should be dispatched. May be 0, in which case the + * default stream is used with associated synchronization rules. + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue + * + */ +hipError_t __hipPopCallConfiguration(dim3 *gridDim, + dim3 *blockDim, + size_t *sharedMem, + hipStream_t *stream); +/** + * @brief C compliant kernel launch API + * + * @param [in] function_address - kernel stub function pointer. + * @param [in] numBlocks - number of blocks + * @param [in] dimBlocks - dimension of a block + * @param [in] args - kernel arguments + * @param [in] sharedMemBytes - Amount of dynamic shared memory to allocate for this kernel. The + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream - Stream where the kernel should be dispatched. May be 0, in which case th + * default stream is used with associated synchronization rules. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipLaunchKernel(const void* function_address, + dim3 numBlocks, + dim3 dimBlocks, + void** args, + size_t sharedMemBytes __dparm(0), + hipStream_t stream __dparm(0)); + +/** + * @brief Enqueues a host function call in a stream. + * + * @param [in] stream - The stream to enqueue work in. + * @param [in] fn - The function to call once enqueued preceeding operations are complete. + * @param [in] userData - User-specified data to be passed to the function. + * + * @returns #hipSuccess, #hipErrorInvalidResourceHandle, #hipErrorInvalidValue, + * #hipErrorNotSupported + * + * The host function to call in this API will be executed after the preceding operations in + * the stream are complete. The function is a blocking operation that blocks operations in the + * stream that follow it, until the function is returned. + * Event synchronization and internal callback functions make sure enqueued operations will + * execute in order, in the stream. + * + * The host function must not make any HIP API calls. The host function is non-reentrant. It must + * not perform sychronization with any operation that may depend on other processing execution + * but is not enqueued to run earlier in the stream. + * + * Host functions that are enqueued respectively in different non-blocking streams can run concurrently. + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipLaunchHostFunc(hipStream_t stream, hipHostFn_t fn, void* userData); + +/** + * Copies memory for 2D arrays. + * + * @param pCopy - Parameters for the memory copy + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipDrvMemcpy2DUnaligned(const hip_Memcpy2D* pCopy); +//TODO: Move this to hip_ext.h +/** + * @brief Launches kernel from the pointer address, with arguments and shared memory on stream. + * + * @param [in] function_address pointer to the Kernel to launch. + * @param [in] numBlocks number of blocks. + * @param [in] dimBlocks dimension of a block. + * @param [in] args pointer to kernel arguments. + * @param [in] sharedMemBytes Amount of dynamic shared memory to allocate for this kernel. + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream Stream where the kernel should be dispatched. + * May be 0, in which case the default stream is used with associated synchronization rules. + * @param [in] startEvent If non-null, specified event will be updated to track the start time of + * the kernel launch. The event must be created before calling this API. + * @param [in] stopEvent If non-null, specified event will be updated to track the stop time of + * the kernel launch. The event must be created before calling this API. + * @param [in] flags The value of hipExtAnyOrderLaunch, signifies if kernel can be + * launched in any order. + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue. + * + */ +hipError_t hipExtLaunchKernel(const void* function_address, dim3 numBlocks, dim3 dimBlocks, + void** args, size_t sharedMemBytes, hipStream_t stream, + hipEvent_t startEvent, hipEvent_t stopEvent, int flags); +// doxygen end Clang launch +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Texture Texture Management + * @{ + * This section describes the texture management functions of HIP runtime API. + */ + +/** + * @brief Creates a texture object. + * + * @param [out] pTexObject pointer to the texture object to create + * @param [in] pResDesc pointer to resource descriptor + * @param [in] pTexDesc pointer to texture descriptor + * @param [in] pResViewDesc pointer to resource view descriptor + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported, #hipErrorOutOfMemory + * + * @note 3D liner filter isn't supported on GFX90A boards, on which the API @p hipCreateTextureObject will + * return hipErrorNotSupported. + * + */ +hipError_t hipCreateTextureObject( + hipTextureObject_t* pTexObject, + const hipResourceDesc* pResDesc, + const hipTextureDesc* pTexDesc, + const struct hipResourceViewDesc* pResViewDesc); + +/** + * @brief Destroys a texture object. + * + * @param [in] textureObject texture object to destroy + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipDestroyTextureObject(hipTextureObject_t textureObject); + +/** + * @brief Gets the channel descriptor in an array. + * + * @param [in] desc pointer to channel format descriptor + * @param [out] array memory array on the device + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipGetChannelDesc( + hipChannelFormatDesc* desc, + hipArray_const_t array); + +/** + * @brief Gets resource descriptor for the texture object. + * + * @param [out] pResDesc pointer to resource descriptor + * @param [in] textureObject texture object + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipGetTextureObjectResourceDesc( + hipResourceDesc* pResDesc, + hipTextureObject_t textureObject); + +/** + * @brief Gets resource view descriptor for the texture object. + * + * @param [out] pResViewDesc pointer to resource view descriptor + * @param [in] textureObject texture object + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipGetTextureObjectResourceViewDesc( + struct hipResourceViewDesc* pResViewDesc, + hipTextureObject_t textureObject); + +/** + * @brief Gets texture descriptor for the texture object. + * + * @param [out] pTexDesc pointer to texture descriptor + * @param [in] textureObject texture object + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipGetTextureObjectTextureDesc( + hipTextureDesc* pTexDesc, + hipTextureObject_t textureObject); + +/** + * @brief Creates a texture object. + * + * @param [out] pTexObject pointer to texture object to create + * @param [in] pResDesc pointer to resource descriptor + * @param [in] pTexDesc pointer to texture descriptor + * @param [in] pResViewDesc pointer to resource view descriptor + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipTexObjectCreate( + hipTextureObject_t* pTexObject, + const HIP_RESOURCE_DESC* pResDesc, + const HIP_TEXTURE_DESC* pTexDesc, + const HIP_RESOURCE_VIEW_DESC* pResViewDesc); + +/** + * @brief Destroys a texture object. + * + * @param [in] texObject texture object to destroy + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipTexObjectDestroy( + hipTextureObject_t texObject); + +/** + * @brief Gets resource descriptor of a texture object. + * + * @param [out] pResDesc pointer to resource descriptor + * @param [in] texObject texture object + * + * @returns #hipSuccess, #hipErrorNotSupported, #hipErrorInvalidValue + * + */ +hipError_t hipTexObjectGetResourceDesc( + HIP_RESOURCE_DESC* pResDesc, + hipTextureObject_t texObject); + +/** + * @brief Gets resource view descriptor of a texture object. + * + * @param [out] pResViewDesc pointer to resource view descriptor + * @param [in] texObject texture object + * + * @returns #hipSuccess, #hipErrorNotSupported, #hipErrorInvalidValue + * + */ +hipError_t hipTexObjectGetResourceViewDesc( + HIP_RESOURCE_VIEW_DESC* pResViewDesc, + hipTextureObject_t texObject); + +/** + * @brief Gets texture descriptor of a texture object. + * + * @param [out] pTexDesc pointer to texture descriptor + * @param [in] texObject texture object + * + * @returns #hipSuccess, #hipErrorNotSupported, #hipErrorInvalidValue + * + */ +hipError_t hipTexObjectGetTextureDesc( + HIP_TEXTURE_DESC* pTexDesc, + hipTextureObject_t texObject); + +/** + * @brief Allocate a mipmapped array on the device. + * + * @param[out] mipmappedArray - Pointer to allocated mipmapped array in device memory + * @param[in] desc - Requested channel format + * @param[in] extent - Requested allocation size (width field in elements) + * @param[in] numLevels - Number of mipmap levels to allocate + * @param[in] flags - Flags for extensions + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorMemoryAllocation + * + * @note This API is implemented on Windows, under development on Linux. + * + */ +hipError_t hipMallocMipmappedArray( + hipMipmappedArray_t *mipmappedArray, + const struct hipChannelFormatDesc* desc, + struct hipExtent extent, + unsigned int numLevels, + unsigned int flags __dparm(0)); + +/** + * @brief Frees a mipmapped array on the device. + * + * @param[in] mipmappedArray - Pointer to mipmapped array to free + * + * @return #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Windows, under development on Linux. + * + */ +hipError_t hipFreeMipmappedArray(hipMipmappedArray_t mipmappedArray); + +/** + * @brief Gets a mipmap level of a HIP mipmapped array. + * + * @param[out] levelArray - Returned mipmap level HIP array + * @param[in] mipmappedArray - HIP mipmapped array + * @param[in] level - Mipmap level + * + * @return #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Windows, under development on Linux. + * + */ +hipError_t hipGetMipmappedArrayLevel( + hipArray_t *levelArray, + hipMipmappedArray_const_t mipmappedArray, + unsigned int level); + +/** + * @brief Create a mipmapped array. + * + * @param [out] pHandle pointer to mipmapped array + * @param [in] pMipmappedArrayDesc mipmapped array descriptor + * @param [in] numMipmapLevels mipmap level + * + * @returns #hipSuccess, #hipErrorNotSupported, #hipErrorInvalidValue + * + * @note This API is implemented on Windows, under development on Linux. + */ +hipError_t hipMipmappedArrayCreate( + hipMipmappedArray_t* pHandle, + HIP_ARRAY3D_DESCRIPTOR* pMipmappedArrayDesc, + unsigned int numMipmapLevels); + +/** + * @brief Destroy a mipmapped array. + * + * @param [out] hMipmappedArray pointer to mipmapped array to destroy + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Windows, under development on Linux. + * + */ +hipError_t hipMipmappedArrayDestroy(hipMipmappedArray_t hMipmappedArray); + +/** + * @brief Get a mipmapped array on a mipmapped level. + * + * @param [in] pLevelArray Pointer of array + * @param [out] hMipMappedArray Pointer of mipmapped array on the requested mipmap level + * @param [out] level Mipmap level + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Windows, under development on Linux. + * + */ +hipError_t hipMipmappedArrayGetLevel( + hipArray_t* pLevelArray, + hipMipmappedArray_t hMipMappedArray, + unsigned int level); + +/** + * + * @addtogroup TextureD Texture Management [Deprecated] + * @{ + * @ingroup Texture + * This section describes the deprecated texture management functions of HIP runtime API. + */ + +/** + * @brief Binds a mipmapped array to a texture. + * + * @param [in] tex pointer to the texture reference to bind + * @param [in] mipmappedArray memory mipmapped array on the device + * @param [in] desc opointer to the channel format + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipBindTextureToMipmappedArray( + const textureReference* tex, + hipMipmappedArray_const_t mipmappedArray, + const hipChannelFormatDesc* desc); + +/** + * @brief Gets the texture reference related with the symbol. + * + * @param [out] texref texture reference + * @param [in] symbol pointer to the symbol related with the texture for the reference + * + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipGetTextureReference( + const textureReference** texref, + const void* symbol); + +/** + * @brief Gets the border color used by a texture reference. + * + * @param [out] pBorderColor Returned Type and Value of RGBA color. + * @param [in] texRef Texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetBorderColor(float* pBorderColor, const textureReference* texRef); + +/** + * @brief Gets the array bound to a texture reference. + + * + * @param [in] pArray Returned array. + * @param [in] texRef texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetArray(hipArray_t* pArray, const textureReference* texRef); + +/** + * @brief Sets address mode for a texture reference. + * + * @param [in] texRef texture reference. + * @param [in] dim Dimension of the texture. + * @param [in] am Value of the texture address mode. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetAddressMode( + textureReference* texRef, + int dim, + enum hipTextureAddressMode am); +/** + * @brief Binds an array as a texture reference. + * + * @param [in] tex Pointer texture reference. + * @param [in] array Array to bind. + * @param [in] flags Flags should be set as HIP_TRSA_OVERRIDE_FORMAT, as a valid value. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetArray( + textureReference* tex, + hipArray_const_t array, + unsigned int flags); +/** + * @brief Set filter mode for a texture reference. + * + * @param [in] texRef Pointer texture reference. + * @param [in] fm Value of texture filter mode. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetFilterMode( + textureReference* texRef, + enum hipTextureFilterMode fm); +/** + * @brief Set flags for a texture reference. + * + * @param [in] texRef Pointer texture reference. + * @param [in] Flags Value of flags. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetFlags( + textureReference* texRef, + unsigned int Flags); +/** + * @brief Set format for a texture reference. + * + * @param [in] texRef Pointer texture reference. + * @param [in] fmt Value of format. + * @param [in] NumPackedComponents Number of components per array. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetFormat( + textureReference* texRef, + hipArray_Format fmt, + int NumPackedComponents); +/** + * @brief Binds a memory area to a texture. + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of memory on the device. + * @param [in] desc Pointer of channel format descriptor. + * @param [in] size Size of memory in bites. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipBindTexture( + size_t* offset, + const textureReference* tex, + const void* devPtr, + const hipChannelFormatDesc* desc, + size_t size __dparm(UINT_MAX)); +/** + * @brief Binds a 2D memory area to a texture. + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of 2D memory area on the device. + * @param [in] desc Pointer of channel format descriptor. + * @param [in] width Width in texel units. + * @param [in] height Height in texel units. + * @param [in] pitch Pitch in bytes. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipBindTexture2D( + size_t* offset, + const textureReference* tex, + const void* devPtr, + const hipChannelFormatDesc* desc, + size_t width, + size_t height, + size_t pitch); +/** + * @brief Binds a memory area to a texture. + * + * @param [in] tex Pointer of texture reference. + * @param [in] array Array to bind. + * @param [in] desc Pointer of channel format descriptor. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipBindTextureToArray( + const textureReference* tex, + hipArray_const_t array, + const hipChannelFormatDesc* desc); +/** + * @brief Get the offset of the alignment in a texture. + * + * @param [in] offset Offset in bytes. + * @param [in] texref Pointer of texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipGetTextureAlignmentOffset( + size_t* offset, + const textureReference* texref); +/** + * @brief Unbinds a texture. + * + * @param [in] tex Texture to unbind. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipUnbindTexture(const textureReference* tex); +/** + * @brief Gets the address for a texture reference. + * + * @param [out] dev_ptr Pointer of device address. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetAddress( + hipDeviceptr_t* dev_ptr, + const textureReference* texRef); +/** + * @brief Gets the address mode for a texture reference. + * + * @param [out] pam Pointer of address mode. + * @param [in] texRef Pointer of texture reference. + * @param [in] dim Dimension. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetAddressMode( + enum hipTextureAddressMode* pam, + const textureReference* texRef, + int dim); +/** + * @brief Gets filter mode for a texture reference. + * + * @param [out] pfm Pointer of filter mode. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetFilterMode( + enum hipTextureFilterMode* pfm, + const textureReference* texRef); +/** + * @brief Gets flags for a texture reference. + * + * @param [out] pFlags Pointer of flags. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetFlags( + unsigned int* pFlags, + const textureReference* texRef); +/** + * @brief Gets texture format for a texture reference. + * + * @param [out] pFormat Pointer of the format. + * @param [out] pNumChannels Pointer of number of channels. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetFormat( + hipArray_Format* pFormat, + int* pNumChannels, + const textureReference* texRef); +/** + * @brief Gets the maximum anisotropy for a texture reference. + * + * @param [out] pmaxAnsio Pointer of the maximum anisotropy. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetMaxAnisotropy( + int* pmaxAnsio, + const textureReference* texRef); +/** + * @brief Gets the mipmap filter mode for a texture reference. + * + * @param [out] pfm Pointer of the mipmap filter mode. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetMipmapFilterMode( + enum hipTextureFilterMode* pfm, + const textureReference* texRef); +/** + * @brief Gets the mipmap level bias for a texture reference. + * + * @param [out] pbias Pointer of the mipmap level bias. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetMipmapLevelBias( + float* pbias, + const textureReference* texRef); +/** + * @brief Gets the minimum and maximum mipmap level clamps for a texture reference. + * + * @param [out] pminMipmapLevelClamp Pointer of the minimum mipmap level clamp. + * @param [out] pmaxMipmapLevelClamp Pointer of the maximum mipmap level clamp. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetMipmapLevelClamp( + float* pminMipmapLevelClamp, + float* pmaxMipmapLevelClamp, + const textureReference* texRef); +/** + * @brief Gets the mipmapped array bound to a texture reference. + * + * @param [out] pArray Pointer of the mipmapped array. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetMipMappedArray( + hipMipmappedArray_t* pArray, + const textureReference* texRef); +/** + * @brief Sets an bound address for a texture reference. + * + * @param [out] ByteOffset Pointer of the offset in bytes. + * @param [in] texRef Pointer of texture reference. + * @param [in] dptr Pointer of device address to bind. + * @param [in] bytes Size in bytes. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetAddress( + size_t* ByteOffset, + textureReference* texRef, + hipDeviceptr_t dptr, + size_t bytes); +/** + * @brief Set a bind an address as a 2D texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [in] desc Pointer of array descriptor. + * @param [in] dptr Pointer of device address to bind. + * @param [in] Pitch Pitch in bytes. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetAddress2D( + textureReference* texRef, + const HIP_ARRAY_DESCRIPTOR* desc, + hipDeviceptr_t dptr, + size_t Pitch); +/** + * @brief Sets the maximum anisotropy for a texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [out] maxAniso Value of the maximum anisotropy. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetMaxAnisotropy( + textureReference* texRef, + unsigned int maxAniso); +/** + * @brief Sets border color for a texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [in] pBorderColor Pointer of border color. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetBorderColor( + textureReference* texRef, + float* pBorderColor); +/** + * @brief Sets mipmap filter mode for a texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [in] fm Value of filter mode. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetMipmapFilterMode( + textureReference* texRef, + enum hipTextureFilterMode fm); +/** + * @brief Sets mipmap level bias for a texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [in] bias Value of mipmap bias. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetMipmapLevelBias( + textureReference* texRef, + float bias); +/** + * @brief Sets mipmap level clamp for a texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [in] minMipMapLevelClamp Value of minimum mipmap level clamp. + * @param [in] maxMipMapLevelClamp Value of maximum mipmap level clamp. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetMipmapLevelClamp( + textureReference* texRef, + float minMipMapLevelClamp, + float maxMipMapLevelClamp); +/** + * @brief Binds mipmapped array to a texture reference. + * + * @param [in] texRef Pointer of texture reference to bind. + * @param [in] mipmappedArray Pointer of mipmapped array to bind. + * @param [in] Flags Flags should be set as HIP_TRSA_OVERRIDE_FORMAT, as a valid value. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetMipmappedArray( + textureReference* texRef, + struct hipMipmappedArray* mipmappedArray, + unsigned int Flags); + +// doxygen end deprecated texture management +/** + * @} + */ + +// doxygen end Texture management +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Runtime Runtime Compilation + * @{ + * This section describes the runtime compilation functions of HIP runtime API. + * + */ +// This group is for HIPrtc + +// doxygen end Runtime +/** + * @} + */ + +/** + * + * @defgroup Callback Callback Activity APIs + * @{ + * This section describes the callback/Activity of HIP runtime API. + */ +/** + * @brief Returns HIP API name by ID. + * + * @param [in] id ID of HIP API + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +const char* hipApiName(uint32_t id); +/** + * @brief Returns kernel name reference by function name. + * + * @param [in] f Name of function + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +const char* hipKernelNameRef(const hipFunction_t f); +/** + * @brief Retrives kernel for a given host pointer, unless stated otherwise. + * + * @param [in] hostFunction Pointer of host function. + * @param [in] stream Stream the kernel is executed on. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +const char* hipKernelNameRefByPtr(const void* hostFunction, hipStream_t stream); +/** + * @brief Returns device ID on the stream. + * + * @param [in] stream Stream of device executed on. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +int hipGetStreamDeviceId(hipStream_t stream); + +// doxygen end Callback +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Graph Graph Management + * @{ + * This section describes the graph management types & functions of HIP runtime API. + */ + +/** + * @brief Begins graph capture on a stream. + * + * @param [in] stream - Stream to initiate capture. + * @param [in] mode - Controls the interaction of this capture sequence with other API calls that + * are not safe. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipStreamBeginCapture(hipStream_t stream, hipStreamCaptureMode mode); + +/** +* @brief Begins graph capture on a stream to an existing graph. +* +* @param [in] stream - Stream to initiate capture. +* @param [in] graph - Graph to capture into. +* @param [in] dependencies - Dependencies of the first node captured in the stream. Can be NULL if +* numDependencies is 0. +* @param [in] dependencyData - Optional array of data associated with each dependency. +* @param [in] numDependencies - Number of dependencies. +* @param [in] mode - Controls the interaction of this capture sequence with other API calls that +are not safe. +* +* @returns #hipSuccess, #hipErrorInvalidValue +* +* @warning : param "const hipGraphEdgeData* dependencyData" is currently not supported and has to +passed as nullptr. This API is marked as beta, meaning, while this is feature complete, it is still +open to changes and may have outstanding issues. +* +*/ +hipError_t hipStreamBeginCaptureToGraph(hipStream_t stream, hipGraph_t graph, + const hipGraphNode_t* dependencies, + const hipGraphEdgeData* dependencyData, + size_t numDependencies, hipStreamCaptureMode mode); + +/** + * @brief Ends capture on a stream, returning the captured graph. + * + * @param [in] stream - Stream to end capture. + * @param [out] pGraph - returns the graph captured. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipStreamEndCapture(hipStream_t stream, hipGraph_t* pGraph); + +/** + * @brief Get capture status of a stream. + * + * @param [in] stream - Stream under capture. + * @param [out] pCaptureStatus - returns current status of the capture. + * @param [out] pId - unique ID of the capture. + * + * @returns #hipSuccess, #hipErrorStreamCaptureImplicit + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipStreamGetCaptureInfo(hipStream_t stream, hipStreamCaptureStatus* pCaptureStatus, + unsigned long long* pId); + +/** + * @brief Get stream's capture state + * + * @param [in] stream - Stream under capture. + * @param [out] captureStatus_out - returns current status of the capture. + * @param [out] id_out - unique ID of the capture. + * @param [in] graph_out - returns the graph being captured into. + * @param [out] dependencies_out - returns pointer to an array of nodes. + * @param [out] numDependencies_out - returns size of the array returned in dependencies_out. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorStreamCaptureImplicit + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipStreamGetCaptureInfo_v2(hipStream_t stream, hipStreamCaptureStatus* captureStatus_out, + unsigned long long* id_out __dparm(0), + hipGraph_t* graph_out __dparm(0), + const hipGraphNode_t** dependencies_out __dparm(0), + size_t* numDependencies_out __dparm(0)); + +/** + * @brief Get stream's capture state + * + * @param [in] stream - Stream under capture. + * @param [out] pCaptureStatus - returns current status of the capture. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorStreamCaptureImplicit + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipStreamIsCapturing(hipStream_t stream, hipStreamCaptureStatus* pCaptureStatus); + +/** + * @brief Update the set of dependencies in a capturing stream + * + * @param [in] stream Stream under capture. + * @param [in] dependencies pointer to an array of nodes to Add/Replace. + * @param [in] numDependencies size of the array in dependencies. + * @param [in] flags Flag how to update dependency set. Should be one of value in enum + * #hipStreamUpdateCaptureDependenciesFlags + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorIllegalState + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipStreamUpdateCaptureDependencies(hipStream_t stream, hipGraphNode_t* dependencies, + size_t numDependencies, + unsigned int flags __dparm(0)); + +/** + * @brief Swaps the stream capture mode of a thread. + * + * @param [in] mode - Pointer to mode value to swap with the current mode + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipThreadExchangeStreamCaptureMode(hipStreamCaptureMode* mode); + +/** + * @brief Creates a graph + * + * @param [out] pGraph - pointer to graph to create. + * @param [in] flags - flags for graph creation, must be 0. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorMemoryAllocation + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphCreate(hipGraph_t* pGraph, unsigned int flags); + +/** + * @brief Destroys a graph + * + * @param [in] graph - instance of graph to destroy. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphDestroy(hipGraph_t graph); + +/** + * @brief Adds dependency edges to a graph. + * + * @param [in] graph - instance of the graph to add dependencies. + * @param [in] from - pointer to the graph nodes with dependenties to add from. + * @param [in] to - pointer to the graph nodes to add dependenties to. + * @param [in] numDependencies - the number of dependencies to add. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphAddDependencies(hipGraph_t graph, const hipGraphNode_t* from, + const hipGraphNode_t* to, size_t numDependencies); + +/** + * @brief Removes dependency edges from a graph. + * + * @param [in] graph - instance of the graph to remove dependencies. + * @param [in] from - Array of nodes that provide the dependencies. + * @param [in] to - Array of dependent nodes. + * @param [in] numDependencies - the number of dependencies to remove. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphRemoveDependencies(hipGraph_t graph, const hipGraphNode_t* from, + const hipGraphNode_t* to, size_t numDependencies); + +/** + * @brief Returns a graph's dependency edges. + * + * @param [in] graph - instance of the graph to get the edges from. + * @param [out] from - pointer to the graph nodes to return edge endpoints. + * @param [out] to - pointer to the graph nodes to return edge endpoints. + * @param [out] numEdges - returns number of edges. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * from and to may both be NULL, in which case this function only returns the number of edges in + * numEdges. Otherwise, numEdges entries will be filled in. If numEdges is higher than the actual + * number of edges, the remaining entries in from and to will be set to NULL, and the number of + * edges actually returned will be written to numEdges + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphGetEdges(hipGraph_t graph, hipGraphNode_t* from, hipGraphNode_t* to, + size_t* numEdges); + +/** + * @brief Returns graph nodes. + * + * @param [in] graph - instance of graph to get the nodes. + * @param [out] nodes - pointer to return the graph nodes. + * @param [out] numNodes - returns number of graph nodes. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * nodes may be NULL, in which case this function will return the number of nodes in numNodes. + * Otherwise, numNodes entries will be filled in. If numNodes is higher than the actual number of + * nodes, the remaining entries in nodes will be set to NULL, and the number of nodes actually + * obtained will be returned in numNodes. + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphGetNodes(hipGraph_t graph, hipGraphNode_t* nodes, size_t* numNodes); + +/** + * @brief Returns graph's root nodes. + * + * @param [in] graph - instance of the graph to get the nodes. + * @param [out] pRootNodes - pointer to return the graph's root nodes. + * @param [out] pNumRootNodes - returns the number of graph's root nodes. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * pRootNodes may be NULL, in which case this function will return the number of root nodes in + * pNumRootNodes. Otherwise, pNumRootNodes entries will be filled in. If pNumRootNodes is higher + * than the actual number of root nodes, the remaining entries in pRootNodes will be set to NULL, + * and the number of nodes actually obtained will be returned in pNumRootNodes. + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphGetRootNodes(hipGraph_t graph, hipGraphNode_t* pRootNodes, + size_t* pNumRootNodes); + +/** + * @brief Returns a node's dependencies. + * + * @param [in] node - graph node to get the dependencies from. + * @param [out] pDependencies - pointer to to return the dependencies. + * @param [out] pNumDependencies - returns the number of graph node dependencies. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * pDependencies may be NULL, in which case this function will return the number of dependencies in + * pNumDependencies. Otherwise, pNumDependencies entries will be filled in. If pNumDependencies is + * higher than the actual number of dependencies, the remaining entries in pDependencies will be set + * to NULL, and the number of nodes actually obtained will be returned in pNumDependencies. + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphNodeGetDependencies(hipGraphNode_t node, hipGraphNode_t* pDependencies, + size_t* pNumDependencies); + +/** + * @brief Returns a node's dependent nodes. + * + * @param [in] node - graph node to get the Dependent nodes from. + * @param [out] pDependentNodes - pointer to return the graph dependent nodes. + * @param [out] pNumDependentNodes - returns the number of graph node dependent nodes. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * DependentNodes may be NULL, in which case this function will return the number of dependent nodes + * in pNumDependentNodes. Otherwise, pNumDependentNodes entries will be filled in. If + * pNumDependentNodes is higher than the actual number of dependent nodes, the remaining entries in + * pDependentNodes will be set to NULL, and the number of nodes actually obtained will be returned + * in pNumDependentNodes. + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphNodeGetDependentNodes(hipGraphNode_t node, hipGraphNode_t* pDependentNodes, + size_t* pNumDependentNodes); + +/** + * @brief Returns a node's type. + * + * @param [in] node - instance of the graph to add dependencies. + * @param [out] pType - pointer to the return the type + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphNodeGetType(hipGraphNode_t node, hipGraphNodeType* pType); + +/** + * @brief Remove a node from the graph. + * + * @param [in] node - graph node to remove + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphDestroyNode(hipGraphNode_t node); + +/** + * @brief Clones a graph. + * + * @param [out] pGraphClone - Returns newly created cloned graph. + * @param [in] originalGraph - original graph to clone from. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorMemoryAllocation + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphClone(hipGraph_t* pGraphClone, hipGraph_t originalGraph); + +/** + * @brief Finds a cloned version of a node. + * + * @param [out] pNode - Returns the cloned node. + * @param [in] originalNode - original node handle. + * @param [in] clonedGraph - Cloned graph to query. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphNodeFindInClone(hipGraphNode_t* pNode, hipGraphNode_t originalNode, + hipGraph_t clonedGraph); + +/** + * @brief Creates an executable graph from a graph + * + * @param [out] pGraphExec - pointer to instantiated executable graph that is created. + * @param [in] graph - instance of graph to instantiate. + * @param [out] pErrorNode - pointer to error node in case error occured in graph instantiation, + * it could modify the correponding node. + * @param [out] pLogBuffer - pointer to log buffer. + * @param [out] bufferSize - the size of log buffer. + * + * @returns #hipSuccess, #hipErrorOutOfMemory + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphInstantiate(hipGraphExec_t* pGraphExec, hipGraph_t graph, + hipGraphNode_t* pErrorNode, char* pLogBuffer, size_t bufferSize); + +/** + * @brief Creates an executable graph from a graph. + * + * @param [out] pGraphExec - pointer to instantiated executable graph that is created. + * @param [in] graph - instance of graph to instantiate. + * @param [in] flags - Flags to control instantiation. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues.It does not support + * any of flag and is behaving as hipGraphInstantiate. + */ +hipError_t hipGraphInstantiateWithFlags(hipGraphExec_t* pGraphExec, hipGraph_t graph, + unsigned long long flags); + +/** + * @brief Creates an executable graph from a graph. + * + * @param [out] pGraphExec - pointer to instantiated executable graph that is created. + * @param [in] graph - instance of graph to instantiate. + * @param [in] instantiateParams - Graph Instantiate Params + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphInstantiateWithParams(hipGraphExec_t* pGraphExec, hipGraph_t graph, + hipGraphInstantiateParams *instantiateParams); +/** + * @brief launches an executable graph in a stream + * + * @param [in] graphExec - instance of executable graph to launch. + * @param [in] stream - instance of stream in which to launch executable graph. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphLaunch(hipGraphExec_t graphExec, hipStream_t stream); + +/** + * @brief uploads an executable graph in a stream + * + * @param [in] graphExec - instance of executable graph to launch. + * @param [in] stream - instance of stream in which to launch executable graph. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphUpload(hipGraphExec_t graphExec, hipStream_t stream); + +/** + * @brief Creates a kernel execution node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to graph node to create. + * @param [in] graph - instance of graph to add the created node. + * @param [in] pDependencies - pointer to the dependencies on the kernel execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] nodeParams - pointer to the parameters for the node. + * @returns #hipSuccess, #hipErrorInvalidValue. + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddNode(hipGraphNode_t *pGraphNode, hipGraph_t graph, + const hipGraphNode_t *pDependencies, size_t numDependencies, + hipGraphNodeParams *nodeParams); + +/** + * @brief Destroys an executable graph + * + * @param [in] graphExec - instance of executable graph to destry. + * + * @returns #hipSuccess. + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecDestroy(hipGraphExec_t graphExec); + +// Check whether an executable graph can be updated with a graph and perform the update if possible. +/** + * @brief Check whether an executable graph can be updated with a graph and perform the update if * + * possible. + * + * @param [in] hGraphExec - instance of executable graph to update. + * @param [in] hGraph - graph that contains the updated parameters. + * @param [in] hErrorNode_out - node which caused the permissibility check to forbid the update. + * @param [in] updateResult_out - Whether the graph update was permitted. + * @returns #hipSuccess, #hipErrorGraphExecUpdateFailure + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecUpdate(hipGraphExec_t hGraphExec, hipGraph_t hGraph, + hipGraphNode_t* hErrorNode_out, + hipGraphExecUpdateResult* updateResult_out); + +/** + * @brief Creates a kernel execution node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to graph node to create. + * @param [in] graph - instance of graph to add the created node. + * @param [in] pDependencies - pointer to the dependencies on the kernel execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] pNodeParams - pointer to the parameters to the kernel execution node on the GPU. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidDeviceFunction + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddKernelNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + const hipKernelNodeParams* pNodeParams); + +/** + * @brief Gets kernel node's parameters. + * + * @param [in] node - instance of the node to get parameters from. + * @param [out] pNodeParams - pointer to the parameters + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphKernelNodeGetParams(hipGraphNode_t node, hipKernelNodeParams* pNodeParams); + +/** + * @brief Sets a kernel node's parameters. + * + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - const pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphKernelNodeSetParams(hipGraphNode_t node, const hipKernelNodeParams* pNodeParams); + +/** + * @brief Sets the parameters for a kernel node in the given graphExec. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - const pointer to the kernel node parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecKernelNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t node, + const hipKernelNodeParams* pNodeParams); + +/** + * @brief Creates a memcpy node and adds it to a graph. + * + * @param [out] phGraphNode - pointer to graph node to create. + * @param [in] hGraph - instance of graph to add the created node. + * @param [in] dependencies - const pointer to the dependencies on the memcpy execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] copyParams - const pointer to the parameters for the memory copy. + * @param [in] ctx - cotext related to current device. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDrvGraphAddMemcpyNode(hipGraphNode_t* phGraphNode, hipGraph_t hGraph, + const hipGraphNode_t* dependencies, + size_t numDependencies, + const HIP_MEMCPY3D* copyParams, hipCtx_t ctx); +/** + * @brief Creates a memcpy node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to graph node to create. + * @param [in] graph - instance of graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memcpy execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] pCopyParams - const pointer to the parameters for the memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddMemcpyNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + const hipMemcpy3DParms* pCopyParams); +/** + * @brief Gets a memcpy node's parameters. + * + * @param [in] node - instance of the node to get parameters from. + * @param [out] pNodeParams - pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemcpyNodeGetParams(hipGraphNode_t node, hipMemcpy3DParms* pNodeParams); + +/** + * @brief Sets a memcpy node's parameters. + * + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - const pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemcpyNodeSetParams(hipGraphNode_t node, const hipMemcpy3DParms* pNodeParams); + +/** + * @brief Sets a node attribute. + * + * @param [in] hNode - instance of the node to set parameters to. + * @param [in] attr - the attribute node is set to. + * @param [in] value - const pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphKernelNodeSetAttribute(hipGraphNode_t hNode, hipKernelNodeAttrID attr, + const hipKernelNodeAttrValue* value); +/** + * @brief Gets a node attribute. + * + * @param [in] hNode - instance of the node to set parameters to. + * @param [in] attr - the attribute node is set to. + * @param [in] value - const pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphKernelNodeGetAttribute(hipGraphNode_t hNode, hipKernelNodeAttrID attr, + hipKernelNodeAttrValue* value); +/** + * @brief Sets the parameters for a memcpy node in the given graphExec. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - const pointer to the kernel node parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecMemcpyNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t node, + hipMemcpy3DParms* pNodeParams); + +/** + * @brief Creates a 1D memcpy node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to graph node to create. + * @param [in] graph - instance of graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memcpy execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] dst - pointer to memory address to the destination. + * @param [in] src - pointer to memory address to the source. + * @param [in] count - the size of the memory to copy. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddMemcpyNode1D(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + void* dst, const void* src, size_t count, hipMemcpyKind kind); + +/** + * @brief Sets a memcpy node's parameters to perform a 1-dimensional copy. + * + * @param [in] node - instance of the node to set parameters to. + * @param [in] dst - pointer to memory address to the destination. + * @param [in] src - pointer to memory address to the source. + * @param [in] count - the size of the memory to copy. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemcpyNodeSetParams1D(hipGraphNode_t node, void* dst, const void* src, + size_t count, hipMemcpyKind kind); + +/** + * @brief Sets the parameters for a memcpy node in the given graphExec to perform a 1-dimensional + * copy. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - instance of the node to set parameters to. + * @param [in] dst - pointer to memory address to the destination. + * @param [in] src - pointer to memory address to the source. + * @param [in] count - the size of the memory to copy. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecMemcpyNodeSetParams1D(hipGraphExec_t hGraphExec, hipGraphNode_t node, + void* dst, const void* src, size_t count, + hipMemcpyKind kind); + +/** + * @brief Creates a memcpy node to copy from a symbol on the device and adds it to a graph. + * + * @param [out] pGraphNode - pointer to graph node to create. + * @param [in] graph - instance of graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memcpy execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] dst - pointer to memory address to the destination. + * @param [in] symbol - Device symbol address. + * @param [in] count - the size of the memory to copy. + * @param [in] offset - Offset from start of symbol in bytes. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddMemcpyNodeFromSymbol(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, void* dst, const void* symbol, + size_t count, size_t offset, hipMemcpyKind kind); + +/** + * @brief Sets a memcpy node's parameters to copy from a symbol on the device. + * + * @param [in] node - instance of the node to set parameters to. + * @param [in] dst - pointer to memory address to the destination. + * @param [in] symbol - Device symbol address. + * @param [in] count - the size of the memory to copy. + * @param [in] offset - Offset from start of symbol in bytes. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemcpyNodeSetParamsFromSymbol(hipGraphNode_t node, void* dst, const void* symbol, + size_t count, size_t offset, hipMemcpyKind kind); + +/** + * @brief Sets the parameters for a memcpy node in the given graphExec to copy from a symbol on the + * * device. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - instance of the node to set parameters to. + * @param [in] dst - pointer to memory address to the destination. + * @param [in] symbol - Device symbol address. + * @param [in] count - the size of the memory to copy. + * @param [in] offset - Offset from start of symbol in bytes. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecMemcpyNodeSetParamsFromSymbol(hipGraphExec_t hGraphExec, hipGraphNode_t node, + void* dst, const void* symbol, size_t count, + size_t offset, hipMemcpyKind kind); + +/** + * @brief Creates a memcpy node to copy to a symbol on the device and adds it to a graph. + * + * @param [out] pGraphNode - pointer to graph node to create. + * @param [in] graph - instance of graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memcpy execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] symbol - Device symbol address. + * @param [in] src - pointer to memory address of the src. + * @param [in] count - the size of the memory to copy. + * @param [in] offset - Offset from start of symbol in bytes. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddMemcpyNodeToSymbol(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, const void* symbol, + const void* src, size_t count, size_t offset, + hipMemcpyKind kind); + +/** + * @brief Sets a memcpy node's parameters to copy to a symbol on the device. + * + * @param [in] node - instance of the node to set parameters to. + * @param [in] symbol - Device symbol address. + * @param [in] src - pointer to memory address of the src. + * @param [in] count - the size of the memory to copy. + * @param [in] offset - Offset from start of symbol in bytes. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemcpyNodeSetParamsToSymbol(hipGraphNode_t node, const void* symbol, + const void* src, size_t count, size_t offset, + hipMemcpyKind kind); + + +/** + * @brief Sets the parameters for a memcpy node in the given graphExec to copy to a symbol on the + * device. + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - instance of the node to set parameters to. + * @param [in] symbol - Device symbol address. + * @param [in] src - pointer to memory address of the src. + * @param [in] count - the size of the memory to copy. + * @param [in] offset - Offset from start of symbol in bytes. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecMemcpyNodeSetParamsToSymbol(hipGraphExec_t hGraphExec, hipGraphNode_t node, + const void* symbol, const void* src, + size_t count, size_t offset, hipMemcpyKind kind); + +/** + * @brief Creates a memset node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create. + * @param [in] graph - instance of the graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memset execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] pMemsetParams - const pointer to the parameters for the memory set. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddMemsetNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + const hipMemsetParams* pMemsetParams); + +/** + * @brief Gets a memset node's parameters. + * + * @param [in] node - instane of the node to get parameters from. + * @param [out] pNodeParams - pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemsetNodeGetParams(hipGraphNode_t node, hipMemsetParams* pNodeParams); + +/** + * @brief Sets a memset node's parameters. + * + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemsetNodeSetParams(hipGraphNode_t node, const hipMemsetParams* pNodeParams); + +/** + * @brief Sets the parameters for a memset node in the given graphExec. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecMemsetNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t node, + const hipMemsetParams* pNodeParams); + +/** + * @brief Creates a host execution node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create. + * @param [in] graph - instance of the graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memset execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] pNodeParams -pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddHostNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + const hipHostNodeParams* pNodeParams); + +/** + * @brief Returns a host node's parameters. + * + * @param [in] node - instane of the node to get parameters from. + * @param [out] pNodeParams - pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphHostNodeGetParams(hipGraphNode_t node, hipHostNodeParams* pNodeParams); + +/** + * @brief Sets a host node's parameters. + * + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphHostNodeSetParams(hipGraphNode_t node, const hipHostNodeParams* pNodeParams); + +/** + * @brief Sets the parameters for a host node in the given graphExec. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecHostNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t node, + const hipHostNodeParams* pNodeParams); + +/** + * @brief Creates a child graph node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create. + * @param [in] graph - instance of the graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memset execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] childGraph - the graph to clone into this node + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddChildGraphNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + hipGraph_t childGraph); + +/** + * @brief Gets a handle to the embedded graph of a child graph node. + * + * @param [in] node - instane of the node to get child graph. + * @param [out] pGraph - pointer to get the graph. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphChildGraphNodeGetGraph(hipGraphNode_t node, hipGraph_t* pGraph); + +/** + * @brief Updates node parameters in the child graph node in the given graphExec. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - node from the graph which was used to instantiate graphExec. + * @param [in] childGraph - child graph with updated parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecChildGraphNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t node, + hipGraph_t childGraph); + +/** + * @brief Creates an empty node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create and add to the graph. + * @param [in] graph - instane of the graph the node is add to. + * @param [in] pDependencies - const pointer to the node dependenties. + * @param [in] numDependencies - the number of dependencies. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddEmptyNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies); + + +/** + * @brief Creates an event record node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create and add to the graph. + * @param [in] graph - instane of the graph the node to be added. + * @param [in] pDependencies - const pointer to the node dependenties. + * @param [in] numDependencies - the number of dependencies. + * @param [in] event - Event for the node. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddEventRecordNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + hipEvent_t event); + +/** + * @brief Returns the event associated with an event record node. + * + * @param [in] node - instane of the node to get event from. + * @param [out] event_out - Pointer to return the event. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphEventRecordNodeGetEvent(hipGraphNode_t node, hipEvent_t* event_out); + +/** + * @brief Sets an event record node's event. + * + * @param [in] node - instane of the node to set event to. + * @param [in] event - pointer to the event. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphEventRecordNodeSetEvent(hipGraphNode_t node, hipEvent_t event); + +/** + * @brief Sets the event for an event record node in the given graphExec. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] hNode - node from the graph which was used to instantiate graphExec. + * @param [in] event - pointer to the event. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecEventRecordNodeSetEvent(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, + hipEvent_t event); + +/** + * @brief Creates an event wait node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create and add to the graph. + * @param [in] graph - instane of the graph the node to be added. + * @param [in] pDependencies - const pointer to the node dependenties. + * @param [in] numDependencies - the number of dependencies. + * @param [in] event - Event for the node. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddEventWaitNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + hipEvent_t event); + + +/** + * @brief Returns the event associated with an event wait node. + * + * @param [in] node - instane of the node to get event from. + * @param [out] event_out - Pointer to return the event. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphEventWaitNodeGetEvent(hipGraphNode_t node, hipEvent_t* event_out); + +/** + * @brief Sets an event wait node's event. + * + * @param [in] node - instane of the node to set event to. + * @param [in] event - pointer to the event. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphEventWaitNodeSetEvent(hipGraphNode_t node, hipEvent_t event); + +/** + * @brief Sets the event for an event record node in the given graphExec. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] hNode - node from the graph which was used to instantiate graphExec. + * @param [in] event - pointer to the event. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecEventWaitNodeSetEvent(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, + hipEvent_t event); + +/** + * @brief Creates a memory allocation node and adds it to a graph + * + * @param [out] pGraphNode - Pointer to the graph node to create and add to the graph + * @param [in] graph - Instane of the graph the node to be added + * @param [in] pDependencies - Const pointer to the node dependenties + * @param [in] numDependencies - The number of dependencies + * @param [in] pNodeParams - Node parameters for memory allocation + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddMemAllocNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, hipMemAllocNodeParams* pNodeParams); + +/** + * @brief Returns parameters for memory allocation node + * + * @param [in] node - Memory allocation node for a query + * @param [out] pNodeParams - Parameters for the specified memory allocation node + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemAllocNodeGetParams(hipGraphNode_t node, hipMemAllocNodeParams* pNodeParams); + +/** + * @brief Creates a memory free node and adds it to a graph + * + * @param [out] pGraphNode - Pointer to the graph node to create and add to the graph + * @param [in] graph - Instane of the graph the node to be added + * @param [in] pDependencies - Const pointer to the node dependenties + * @param [in] numDependencies - The number of dependencies + * @param [in] dev_ptr - Pointer to the memory to be freed + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddMemFreeNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, void* dev_ptr); + +/** + * @brief Returns parameters for memory free node + * + * @param [in] node - Memory free node for a query + * @param [out] dev_ptr - Device pointer for the specified memory free node + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemFreeNodeGetParams(hipGraphNode_t node, void* dev_ptr); + +/** + * @brief Get the mem attribute for graphs. + * + * @param [in] device - device the attr is get for. + * @param [in] attr - attr to get. + * @param [out] value - value for specific attr. + * @returns #hipSuccess, #hipErrorInvalidDevice + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDeviceGetGraphMemAttribute(int device, hipGraphMemAttributeType attr, void* value); + +/** + * @brief Set the mem attribute for graphs. + * + * @param [in] device - device the attr is set for. + * @param [in] attr - attr to set. + * @param [in] value - value for specific attr. + * @returns #hipSuccess, #hipErrorInvalidDevice + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDeviceSetGraphMemAttribute(int device, hipGraphMemAttributeType attr, void* value); + +/** + * @brief Free unused memory on specific device used for graph back to OS. + * + * @param [in] device - device the memory is used for graphs + * @returns #hipSuccess, #hipErrorInvalidDevice + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDeviceGraphMemTrim(int device); + +/** + * @brief Create an instance of userObject to manage lifetime of a resource. + * + * @param [out] object_out - pointer to instace of userobj. + * @param [in] ptr - pointer to pass to destroy function. + * @param [in] destroy - destroy callback to remove resource. + * @param [in] initialRefcount - reference to resource. + * @param [in] flags - flags passed to API. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipUserObjectCreate(hipUserObject_t* object_out, void* ptr, hipHostFn_t destroy, + unsigned int initialRefcount, unsigned int flags); + +/** + * @brief Release number of references to resource. + * + * @param [in] object - pointer to instace of userobj. + * @param [in] count - reference to resource to be retained. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipUserObjectRelease(hipUserObject_t object, unsigned int count __dparm(1)); + +/** + * @brief Retain number of references to resource. + * + * @param [in] object - pointer to instace of userobj. + * @param [in] count - reference to resource to be retained. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipUserObjectRetain(hipUserObject_t object, unsigned int count __dparm(1)); + +/** + * @brief Retain user object for graphs. + * + * @param [in] graph - pointer to graph to retain the user object for. + * @param [in] object - pointer to instace of userobj. + * @param [in] count - reference to resource to be retained. + * @param [in] flags - flags passed to API. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphRetainUserObject(hipGraph_t graph, hipUserObject_t object, + unsigned int count __dparm(1), unsigned int flags __dparm(0)); + +/** + * @brief Release user object from graphs. + * + * @param [in] graph - pointer to graph to retain the user object for. + * @param [in] object - pointer to instace of userobj. + * @param [in] count - reference to resource to be retained. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphReleaseUserObject(hipGraph_t graph, hipUserObject_t object, + unsigned int count __dparm(1)); + +/** + * @brief Write a DOT file describing graph structure. + * + * @param [in] graph - graph object for which DOT file has to be generated. + * @param [in] path - path to write the DOT file. + * @param [in] flags - Flags from hipGraphDebugDotFlags to get additional node information. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorOperatingSystem + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphDebugDotPrint(hipGraph_t graph, const char* path, unsigned int flags); + +/** + * @brief Copies attributes from source node to destination node. + * + * Copies attributes from source node to destination node. + * Both node must have the same context. + * + * @param [out] hDst - Destination node. + * @param [in] hSrc - Source node. + * For list of attributes see ::hipKernelNodeAttrID. + * + * @returns #hipSuccess, #hipErrorInvalidContext + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphKernelNodeCopyAttributes(hipGraphNode_t hSrc, hipGraphNode_t hDst); + +/** + * @brief Enables or disables the specified node in the given graphExec + * + * Sets hNode to be either enabled or disabled. Disabled nodes are functionally equivalent + * to empty nodes until they are reenabled. Existing node parameters are not affected by + * disabling/enabling the node. + * + * The node is identified by the corresponding hNode in the non-executable graph, from which the + * executable graph was instantiated. + * + * hNode must not have been removed from the original graph. + * + * @note Currently only kernel, memset and memcpy nodes are supported. + * + * @param [in] hGraphExec - The executable graph in which to set the specified node. + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [in] isEnabled - Node is enabled if != 0, otherwise the node is disabled. + * + * @returns #hipSuccess, #hipErrorInvalidValue, + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphNodeSetEnabled(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, + unsigned int isEnabled); +/** + * @brief Query whether a node in the given graphExec is enabled + * + * Sets isEnabled to 1 if hNode is enabled, or 0 if it is disabled. + * + * The node is identified by the corresponding node in the non-executable graph, from which the + * executable graph was instantiated. + * + * hNode must not have been removed from the original graph. + * + * @note Currently only kernel, memset and memcpy nodes are supported. + * + * @param [in] hGraphExec - The executable graph in which to set the specified node. + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [out] isEnabled - Location to return the enabled status of the node. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphNodeGetEnabled(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, + unsigned int* isEnabled); + +/** + * @brief Creates a external semaphor wait node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create. + * @param [in] graph - instance of the graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memset execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] nodeParams -pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddExternalSemaphoresWaitNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + const hipExternalSemaphoreWaitNodeParams* nodeParams); + +/** + * @brief Creates a external semaphor signal node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create. + * @param [in] graph - instance of the graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memset execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] nodeParams -pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddExternalSemaphoresSignalNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + const hipExternalSemaphoreSignalNodeParams* nodeParams); +/** + * @brief Updates node parameters in the external semaphore signal node. + * + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [in] nodeParams - Pointer to the params to be set. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExternalSemaphoresSignalNodeSetParams(hipGraphNode_t hNode, + const hipExternalSemaphoreSignalNodeParams* nodeParams); +/** + * @brief Updates node parameters in the external semaphore wait node. + * + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [in] nodeParams - Pointer to the params to be set. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExternalSemaphoresWaitNodeSetParams(hipGraphNode_t hNode, + const hipExternalSemaphoreWaitNodeParams* nodeParams); +/** + * @brief Returns external semaphore signal node params. + * + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [out] params_out - Pointer to params. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExternalSemaphoresSignalNodeGetParams(hipGraphNode_t hNode, + hipExternalSemaphoreSignalNodeParams* params_out); +/** + * @brief Returns external semaphore wait node params. + * + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [out] params_out - Pointer to params. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExternalSemaphoresWaitNodeGetParams(hipGraphNode_t hNode, + hipExternalSemaphoreWaitNodeParams* params_out); +/** + * @brief Updates node parameters in the external semaphore signal node in the given graphExec. + * + * @param [in] hGraphExec - The executable graph in which to set the specified node. + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [in] nodeParams - Pointer to the params to be set. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecExternalSemaphoresSignalNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, + const hipExternalSemaphoreSignalNodeParams* nodeParams); +/** + * @brief Updates node parameters in the external semaphore wait node in the given graphExec. + * + * @param [in] hGraphExec - The executable graph in which to set the specified node. + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [in] nodeParams - Pointer to the params to be set. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecExternalSemaphoresWaitNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, + const hipExternalSemaphoreWaitNodeParams* nodeParams); + +/** + * @brief Creates a memset node and adds it to a graph. + * + * @param [out] phGraphNode - pointer to graph node to create. + * @param [in] hGraph - instance of graph to add the created node to. + * @param [in] dependencies - const pointer to the dependencies on the memset execution node. + * @param [in] numDependencies - number of the dependencies. + * @param [in] memsetParams - const pointer to the parameters for the memory set. + * @param [in] ctx - cotext related to current device. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDrvGraphAddMemsetNode(hipGraphNode_t* phGraphNode, hipGraph_t hGraph, + const hipGraphNode_t* dependencies, size_t numDependencies, + const HIP_MEMSET_NODE_PARAMS* memsetParams, hipCtx_t ctx); + +// doxygen end graph API +/** + * @} + */ + + +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Virtual Virtual Memory Management + * @{ + * This section describes the virtual memory management functions of HIP runtime API. + * + * @note Please note, the virtual memory management functions of HIP runtime API are implemented + * on Linux, under development on Windows. + */ + +/** + * @brief Frees an address range reservation made via hipMemAddressReserve + * + * @param [in] devPtr - starting address of the range. + * @param [in] size - size of the range. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemAddressFree(void* devPtr, size_t size); + +/** + * @brief Reserves an address range + * + * @param [out] ptr - starting address of the reserved range. + * @param [in] size - size of the reservation. + * @param [in] alignment - alignment of the address. + * @param [in] addr - requested starting address of the range. + * @param [in] flags - currently unused, must be zero. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemAddressReserve(void** ptr, size_t size, size_t alignment, void* addr, unsigned long long flags); + +/** + * @brief Creates a memory allocation described by the properties and size + * + * @param [out] handle - value of the returned handle. + * @param [in] size - size of the allocation. + * @param [in] prop - properties of the allocation. + * @param [in] flags - currently unused, must be zero. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemCreate(hipMemGenericAllocationHandle_t* handle, size_t size, const hipMemAllocationProp* prop, unsigned long long flags); + +/** + * @brief Exports an allocation to a requested shareable handle type. + * + * @param [out] shareableHandle - value of the returned handle. + * @param [in] handle - handle to share. + * @param [in] handleType - type of the shareable handle. + * @param [in] flags - currently unused, must be zero. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemExportToShareableHandle(void* shareableHandle, hipMemGenericAllocationHandle_t handle, hipMemAllocationHandleType handleType, unsigned long long flags); + +/** + * @brief Get the access flags set for the given location and ptr. + * + * @param [out] flags - flags for this location. + * @param [in] location - target location. + * @param [in] ptr - address to check the access flags. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemGetAccess(unsigned long long* flags, const hipMemLocation* location, void* ptr); + +/** + * @brief Calculates either the minimal or recommended granularity. + * + * @param [out] granularity - returned granularity. + * @param [in] prop - location properties. + * @param [in] option - determines which granularity to return. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + * + */ +hipError_t hipMemGetAllocationGranularity(size_t* granularity, const hipMemAllocationProp* prop, hipMemAllocationGranularity_flags option); + +/** + * @brief Retrieve the property structure of the given handle. + * + * @param [out] prop - properties of the given handle. + * @param [in] handle - handle to perform the query on. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux under development on Windows. + */ +hipError_t hipMemGetAllocationPropertiesFromHandle(hipMemAllocationProp* prop, hipMemGenericAllocationHandle_t handle); + +/** + * @brief Imports an allocation from a requested shareable handle type. + * + * @param [out] handle - returned value. + * @param [in] osHandle - shareable handle representing the memory allocation. + * @param [in] shHandleType - handle type. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemImportFromShareableHandle(hipMemGenericAllocationHandle_t* handle, void* osHandle, hipMemAllocationHandleType shHandleType); + +/** + * @brief Maps an allocation handle to a reserved virtual address range. + * + * @param [in] ptr - address where the memory will be mapped. + * @param [in] size - size of the mapping. + * @param [in] offset - offset into the memory, currently must be zero. + * @param [in] handle - memory allocation to be mapped. + * @param [in] flags - currently unused, must be zero. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemMap(void* ptr, size_t size, size_t offset, hipMemGenericAllocationHandle_t handle, unsigned long long flags); + +/** + * @brief Maps or unmaps subregions of sparse HIP arrays and sparse HIP mipmapped arrays. + * + * @param [in] mapInfoList - list of hipArrayMapInfo. + * @param [in] count - number of hipArrayMapInfo in mapInfoList. + * @param [in] stream - stream identifier for the stream to use for map or unmap operations. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemMapArrayAsync(hipArrayMapInfo* mapInfoList, unsigned int count, hipStream_t stream); + +/** + * @brief Release a memory handle representing a memory allocation which was previously allocated through hipMemCreate. + * + * @param [in] handle - handle of the memory allocation. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemRelease(hipMemGenericAllocationHandle_t handle); + +/** + * @brief Returns the allocation handle of the backing memory allocation given the address. + * + * @param [out] handle - handle representing addr. + * @param [in] addr - address to look up. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemRetainAllocationHandle(hipMemGenericAllocationHandle_t* handle, void* addr); + +/** + * @brief Set the access flags for each location specified in desc for the given virtual address range. + * + * @param [in] ptr - starting address of the virtual address range. + * @param [in] size - size of the range. + * @param [in] desc - array of hipMemAccessDesc. + * @param [in] count - number of hipMemAccessDesc in desc. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemSetAccess(void* ptr, size_t size, const hipMemAccessDesc* desc, size_t count); + +/** + * @brief Unmap memory allocation of a given address range. + * + * @param [in] ptr - starting address of the range to unmap. + * @param [in] size - size of the virtual address range. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemUnmap(void* ptr, size_t size); + +// doxygen end virtual memory management API +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup GL OpenGL Interop + * @{ + * This section describes the OpenGL and graphics interoperability functions of HIP runtime API. + */ + +/** + * @brief Maps a graphics resource for access. + * + * @param [in] count - Number of resources to map. + * @param [in] resources - Pointer of resources to map. + * @param [in] stream - Stream for synchronization. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown, #hipErrorInvalidResourceHandle + * + */ +hipError_t hipGraphicsMapResources(int count, hipGraphicsResource_t* resources, + hipStream_t stream __dparm(0) ); +/** + * @brief Get an array through which to access a subresource of a mapped graphics resource. + * + * @param [out] array - Pointer of array through which a subresource of resource may be accessed. + * @param [in] resource - Mapped resource to access. + * @param [in] arrayIndex - Array index for the subresource to access. + * @param [in] mipLevel - Mipmap level for the subresource to access. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note In this API, the value of arrayIndex higher than zero is currently not supported. + * + */ +hipError_t hipGraphicsSubResourceGetMappedArray(hipArray_t* array, hipGraphicsResource_t resource, + unsigned int arrayIndex, unsigned int mipLevel); +/** + * @brief Gets device accessible address of a graphics resource. + * + * @param [out] devPtr - Pointer of device through which graphic resource may be accessed. + * @param [out] size - Size of the buffer accessible from devPtr. + * @param [in] resource - Mapped resource to access. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipGraphicsResourceGetMappedPointer(void** devPtr, size_t* size, + hipGraphicsResource_t resource); +/** + * @brief Unmaps graphics resources. + * + * @param [in] count - Number of resources to unmap. + * @param [in] resources - Pointer of resources to unmap. + * @param [in] stream - Stream for synchronization. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown, #hipErrorContextIsDestroyed + * + */ +hipError_t hipGraphicsUnmapResources(int count, hipGraphicsResource_t* resources, + hipStream_t stream __dparm(0)); +/** + * @brief Unregisters a graphics resource. + * + * @param [in] resource - Graphics resources to unregister. + * + * @returns #hipSuccess + * + */ +hipError_t hipGraphicsUnregisterResource(hipGraphicsResource_t resource); +// doxygen end GL Interop +/** + * @} + */ + +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Surface Surface Object + * @{ + * + * This section describes surface object functions of HIP runtime API. + * + * @note APIs in this section are under development. + * + */ + +/** + * @brief Create a surface object. + * + * @param [out] pSurfObject Pointer of surface object to be created. + * @param [in] pResDesc Pointer of suface object descriptor. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipCreateSurfaceObject(hipSurfaceObject_t* pSurfObject, const hipResourceDesc* pResDesc); +/** + * @brief Destroy a surface object. + * + * @param [in] surfaceObject Surface object to be destroyed. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipDestroySurfaceObject(hipSurfaceObject_t surfaceObject); +// end of surface +/** +* @} +*/ +#ifdef __cplusplus +} /* extern "c" */ +#endif +#ifdef __cplusplus +#if defined(__clang__) && defined(__HIP__) +template +static hipError_t __host__ inline hipOccupancyMaxPotentialBlockSize(int* gridSize, int* blockSize, + T f, size_t dynSharedMemPerBlk = 0, int blockSizeLimit = 0) { + return hipOccupancyMaxPotentialBlockSize(gridSize, blockSize, reinterpret_cast(f),dynSharedMemPerBlk,blockSizeLimit); +} +template +static hipError_t __host__ inline hipOccupancyMaxPotentialBlockSizeWithFlags(int* gridSize, int* blockSize, + T f, size_t dynSharedMemPerBlk = 0, int blockSizeLimit = 0, unsigned int flags = 0 ) { + return hipOccupancyMaxPotentialBlockSize(gridSize, blockSize, reinterpret_cast(f),dynSharedMemPerBlk,blockSizeLimit); +} +#endif // defined(__clang__) && defined(__HIP__) + +/** + * @brief Gets the address of a symbol. + * @ingroup Memory + * @param [out] devPtr - Returns device pointer associated with symbol. + * @param [in] symbol - Device symbol. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +template +hipError_t hipGetSymbolAddress(void** devPtr, const T &symbol) { + return ::hipGetSymbolAddress(devPtr, (const void *)&symbol); +} +/** + * @ingroup Memory + * @brief Gets the size of a symbol. + * + * @param [out] size - Returns the size of a symbol. + * @param [in] symbol - Device symbol address. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +template +hipError_t hipGetSymbolSize(size_t* size, const T &symbol) { + return ::hipGetSymbolSize(size, (const void *)&symbol); +} + +/** + * @ingroup Memory + * @brief Copies data to the given symbol on the device. + * + * @returns #hipSuccess, #hipErrorInvalidMemcpyDirection, #hipErrorInvalidValue + * + * @see hipMemcpyToSymbol + */ +template +hipError_t hipMemcpyToSymbol(const T& symbol, const void* src, size_t sizeBytes, + size_t offset __dparm(0), + hipMemcpyKind kind __dparm(hipMemcpyHostToDevice)) { + return ::hipMemcpyToSymbol((const void*)&symbol, src, sizeBytes, offset, kind); +} +/** + * @ingroup Memory + * @brief Copies data to the given symbol on the device asynchronously on the stream. + * + * @returns #hipSuccess, #hipErrorInvalidMemcpyDirection, #hipErrorInvalidValue + * + * @see hipMemcpyToSymbolAsync + */ +template +hipError_t hipMemcpyToSymbolAsync(const T& symbol, const void* src, size_t sizeBytes, size_t offset, + hipMemcpyKind kind, hipStream_t stream __dparm(0)) { + return ::hipMemcpyToSymbolAsync((const void*)&symbol, src, sizeBytes, offset, kind, stream); +} +/** + * @brief Copies data from the given symbol on the device. + * @ingroup Memory + * @returns #hipSuccess, #hipErrorInvalidMemcpyDirection, #hipErrorInvalidValue + * + * @see hipMemcpyFromSymbol + */ +template +hipError_t hipMemcpyFromSymbol(void* dst, const T &symbol, + size_t sizeBytes, size_t offset __dparm(0), + hipMemcpyKind kind __dparm(hipMemcpyDeviceToHost)) { + return ::hipMemcpyFromSymbol(dst, (const void*)&symbol, sizeBytes, offset, kind); +} +/** + * @brief Copies data from the given symbol on the device asynchronously on the stream. + * @ingroup Memory + * @returns #hipSuccess, #hipErrorInvalidMemcpyDirection, #hipErrorInvalidValue + * + * @see hipMemcpyFromSymbolAsync + */ +template +hipError_t hipMemcpyFromSymbolAsync(void* dst, const T& symbol, size_t sizeBytes, size_t offset, + hipMemcpyKind kind, hipStream_t stream __dparm(0)) { + return ::hipMemcpyFromSymbolAsync(dst, (const void*)&symbol, sizeBytes, offset, kind, stream); +} + +/** + * @brief Returns occupancy for a kernel function. + * @ingroup Occupancy + * @param [out] numBlocks - Pointer of occupancy in number of blocks. + * @param [in] f - The kernel function to launch on the device. + * @param [in] blockSize - The block size as kernel launched. + * @param [in] dynSharedMemPerBlk - Dynamic shared memory in bytes per block. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +template +inline hipError_t hipOccupancyMaxActiveBlocksPerMultiprocessor( + int* numBlocks, T f, int blockSize, size_t dynSharedMemPerBlk) { + return hipOccupancyMaxActiveBlocksPerMultiprocessor( + numBlocks, reinterpret_cast(f), blockSize, dynSharedMemPerBlk); +} +/** + * @brief Returns occupancy for a device function with the specified flags. + * + * @ingroup Occupancy + * @param [out] numBlocks - Pointer of occupancy in number of blocks. + * @param [in] f - The kernel function to launch on the device. + * @param [in] blockSize - The block size as kernel launched. + * @param [in] dynSharedMemPerBlk - Dynamic shared memory in bytes per block. + * @param [in] flags - Flag to handle the behavior for the occupancy calculator. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +template +inline hipError_t hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( + int* numBlocks, T f, int blockSize, size_t dynSharedMemPerBlk, unsigned int flags) { + return hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( + numBlocks, reinterpret_cast(f), blockSize, dynSharedMemPerBlk, flags); +} +/** + * @brief Returns grid and block size that achieves maximum potential occupancy for a device function + * + * @ingroup Occupancy + * Returns in \p *min_grid_size and \p *block_size a suggested grid / + * block size pair that achieves the best potential occupancy + * (i.e. the maximum number of active warps on the current device with the smallest number + * of blocks for a particular function). + * + * @param [out] min_grid_size minimum grid size needed to achieve the best potential occupancy + * @param [out] block_size block size required for the best potential occupancy + * @param [in] func device function symbol + * @param [in] block_size_to_dynamic_smem_size - a unary function/functor that takes block size, + * and returns the size, in bytes, of dynamic shared memory needed for a block + * @param [in] block_size_limit the maximum block size \p func is designed to work with. 0 means no limit. + * @param [in] flags reserved + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidDeviceFunction, #hipErrorInvalidValue, + * #hipErrorUnknown + */ +template +static hipError_t __host__ inline hipOccupancyMaxPotentialBlockSizeVariableSMemWithFlags( + int* min_grid_size, + int* block_size, + T func, + UnaryFunction block_size_to_dynamic_smem_size, + int block_size_limit = 0, + unsigned int flags = 0) { + if (min_grid_size == nullptr || block_size == nullptr || + reinterpret_cast(func) == nullptr) { + return hipErrorInvalidValue; + } + + int dev; + hipError_t status; + if ((status = hipGetDevice(&dev)) != hipSuccess) { + return status; + } + + int max_threads_per_cu; + if ((status = hipDeviceGetAttribute(&max_threads_per_cu, + hipDeviceAttributeMaxThreadsPerMultiProcessor, dev)) != hipSuccess) { + return status; + } + + int warp_size; + if ((status = hipDeviceGetAttribute(&warp_size, + hipDeviceAttributeWarpSize, dev)) != hipSuccess) { + return status; + } + + int max_cu_count; + if ((status = hipDeviceGetAttribute(&max_cu_count, + hipDeviceAttributeMultiprocessorCount, dev)) != hipSuccess) { + return status; + } + + struct hipFuncAttributes attr; + if ((status = hipFuncGetAttributes(&attr, reinterpret_cast(func))) != hipSuccess) { + return status; + } + + // Initial limits for the execution + const int func_max_threads_per_block = attr.maxThreadsPerBlock; + if (block_size_limit == 0) { + block_size_limit = func_max_threads_per_block; + } + + if (func_max_threads_per_block < block_size_limit) { + block_size_limit = func_max_threads_per_block; + } + + const int block_size_limit_aligned = + ((block_size_limit + (warp_size - 1)) / warp_size) * warp_size; + + // For maximum search + int max_threads = 0; + int max_block_size{}; + int max_num_blocks{}; + for (int block_size_check_aligned = block_size_limit_aligned; + block_size_check_aligned > 0; + block_size_check_aligned -= warp_size) { + // Make sure the logic uses the requested limit and not aligned + int block_size_check = (block_size_limit < block_size_check_aligned) ? + block_size_limit : block_size_check_aligned; + + size_t dyn_smem_size = block_size_to_dynamic_smem_size(block_size_check); + int optimal_blocks; + if ((status = hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( + &optimal_blocks, func, block_size_check, dyn_smem_size, flags)) != hipSuccess) { + return status; + } + + int total_threads = block_size_check * optimal_blocks; + if (total_threads > max_threads) { + max_block_size = block_size_check; + max_num_blocks = optimal_blocks; + max_threads = total_threads; + } + + // Break if the logic reached possible maximum + if (max_threads_per_cu == max_threads) { + break; + } + } + + // Grid size is the number of blocks per CU * CU count + *min_grid_size = max_num_blocks * max_cu_count; + *block_size = max_block_size; + + return status; +} + +/** + * @brief Returns grid and block size that achieves maximum potential occupancy for a device function + * + * @ingroup Occupancy + * Returns in \p *min_grid_size and \p *block_size a suggested grid / + * block size pair that achieves the best potential occupancy + * (i.e. the maximum number of active warps on the current device with the smallest number + * of blocks for a particular function). + * + * @param [out] min_grid_size minimum grid size needed to achieve the best potential occupancy + * @param [out] block_size block size required for the best potential occupancy + * @param [in] func device function symbol + * @param [in] block_size_to_dynamic_smem_size - a unary function/functor that takes block size, + * and returns the size, in bytes, of dynamic shared memory needed for a block + * @param [in] block_size_limit the maximum block size \p func is designed to work with. 0 means no limit. + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidDeviceFunction, #hipErrorInvalidValue, + * #hipErrorUnknown + */ +template +static hipError_t __host__ inline hipOccupancyMaxPotentialBlockSizeVariableSMem( + int* min_grid_size, + int* block_size, + T func, + UnaryFunction block_size_to_dynamic_smem_size, + int block_size_limit = 0) +{ + return hipOccupancyMaxPotentialBlockSizeVariableSMemWithFlags(min_grid_size, block_size, func, + block_size_to_dynamic_smem_size, block_size_limit); +} +/** + * @brief Returns grid and block size that achieves maximum potential occupancy for a device function + * + * @ingroup Occupancy + * + * Returns in \p *min_grid_size and \p *block_size a suggested grid / + * block size pair that achieves the best potential occupancy + * (i.e. the maximum number of active warps on the current device with the smallest number + * of blocks for a particular function). + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @see hipOccupancyMaxPotentialBlockSize + */ +template +inline hipError_t hipOccupancyMaxPotentialBlockSize(int* gridSize, int* blockSize, + F kernel, size_t dynSharedMemPerBlk, uint32_t blockSizeLimit) { +return hipOccupancyMaxPotentialBlockSize(gridSize, blockSize,(hipFunction_t)kernel, dynSharedMemPerBlk, blockSizeLimit); +} +/** + * @brief Launches a device function + * + * @ingroup Execution + * + * @param [in] f device function symbol + * @param [in] gridDim grid dimentions + * @param [in] blockDim block dimentions + * @param [in] kernelParams kernel parameters + * @param [in] sharedMemBytes shared memory in bytes + * @param [in] stream stream on which kernel launched + * + * @return #hipSuccess, #hipErrorLaunchFailure, #hipErrorInvalidValue, + * #hipErrorInvalidResourceHandle + * + */ +template +inline hipError_t hipLaunchCooperativeKernel(T f, dim3 gridDim, dim3 blockDim, + void** kernelParams, unsigned int sharedMemBytes, hipStream_t stream) { + return hipLaunchCooperativeKernel(reinterpret_cast(f), gridDim, + blockDim, kernelParams, sharedMemBytes, stream); +} +/** + * @brief Launches device function on multiple devices where thread blocks can cooperate and + * synchronize on execution. + * + * @ingroup Execution + * + * @param [in] launchParamsList list of kernel launch parameters, one per device + * @param [in] numDevices size of launchParamsList array + * @param [in] flags flag to handle launch behavior + * + * @return #hipSuccess, #hipErrorLaunchFailure, #hipErrorInvalidValue, + * #hipErrorInvalidResourceHandle + * + */ +template +inline hipError_t hipLaunchCooperativeKernelMultiDevice(hipLaunchParams* launchParamsList, + unsigned int numDevices, unsigned int flags = 0) { + return hipLaunchCooperativeKernelMultiDevice(launchParamsList, numDevices, flags); +} +/** + * + * @ingroup Module + * + * @brief Launches kernels on multiple devices and guarantees all specified kernels are dispatched + * on respective streams before enqueuing any other work on the specified streams from any other threads + * + * + * @param [in] launchParamsList List of launch parameters, one per device. + * @param [in] numDevices Size of the launchParamsList array. + * @param [in] flags Flags to control launch behavior. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +template +inline hipError_t hipExtLaunchMultiKernelMultiDevice(hipLaunchParams* launchParamsList, + unsigned int numDevices, unsigned int flags = 0) { + return hipExtLaunchMultiKernelMultiDevice(launchParamsList, numDevices, flags); +} +/** + * @brief Binds a memory area to a texture. + * + * @ingroup TextureD + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of memory on the device. + * @param [in] size Size of memory in bites. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipBindTexture(size_t* offset, const struct texture& tex, + const void* devPtr, size_t size = UINT_MAX) { + return hipBindTexture(offset, &tex, devPtr, &tex.channelDesc, size); +} +/** + * @brief Binds a memory area to a texture. + * + * @ingroup TextureD + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of memory on the device. + * @param [in] desc Texture channel format. + * @param [in] size Size of memory in bites. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t + hipBindTexture(size_t* offset, const struct texture& tex, const void* devPtr, + const struct hipChannelFormatDesc& desc, size_t size = UINT_MAX) { + return hipBindTexture(offset, &tex, devPtr, &desc, size); +} +/** + * @brief Binds a 2D memory area to a texture. + * + * @ingroup TextureD + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of 2D memory area on the device. + * @param [in] width Width in texel units. + * @param [in] height Height in texel units. + * @param [in] pitch Pitch in bytes. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipBindTexture2D( + size_t *offset, + const struct texture &tex, + const void *devPtr, + size_t width, + size_t height, + size_t pitch) +{ + return hipBindTexture2D(offset, &tex, devPtr, &tex.channelDesc, width, height, pitch); +} +/** + * @brief Binds a 2D memory area to a texture. + * + * @ingroup TextureD + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of 2D memory area on the device. + * @param [in] desc Texture channel format. + * @param [in] width Width in texel units. + * @param [in] height Height in texel units. + * @param [in] pitch Pitch in bytes. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipBindTexture2D( + size_t *offset, + const struct texture &tex, + const void *devPtr, + const struct hipChannelFormatDesc &desc, + size_t width, + size_t height, + size_t pitch) +{ + return hipBindTexture2D(offset, &tex, devPtr, &desc, width, height, pitch); +} +/** + * @brief Binds an array to a texture. + * + * @ingroup TextureD + * + * @param [in] tex Texture to bind. + * @param [in] array Array of memory on the device. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipBindTextureToArray( + const struct texture &tex, + hipArray_const_t array) +{ + struct hipChannelFormatDesc desc; + hipError_t err = hipGetChannelDesc(&desc, array); + return (err == hipSuccess) ? hipBindTextureToArray(&tex, array, &desc) : err; +} +/** + * @brief Binds an array to a texture. + * + * @ingroup TextureD + * + * @param [in] tex Texture to bind. + * @param [in] array Array of memory on the device. + * @param [in] desc Texture channel format. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipBindTextureToArray( + const struct texture &tex, + hipArray_const_t array, + const struct hipChannelFormatDesc &desc) +{ + return hipBindTextureToArray(&tex, array, &desc); +} +/** + * @brief Binds a mipmapped array to a texture. + * + * @ingroup TextureD + * + * @param [in] tex Texture to bind. + * @param [in] mipmappedArray Mipmapped Array of memory on the device. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipBindTextureToMipmappedArray( + const struct texture &tex, + hipMipmappedArray_const_t mipmappedArray) +{ + struct hipChannelFormatDesc desc; + hipArray_t levelArray; + hipError_t err = hipGetMipmappedArrayLevel(&levelArray, mipmappedArray, 0); + if (err != hipSuccess) { + return err; + } + err = hipGetChannelDesc(&desc, levelArray); + return (err == hipSuccess) ? hipBindTextureToMipmappedArray(&tex, mipmappedArray, &desc) : err; +} +/** + * @brief Binds a mipmapped array to a texture. + * + * @ingroup TextureD + * + * @param [in] tex Texture to bind. + * @param [in] mipmappedArray Mipmapped Array of memory on the device. + * @param [in] desc Texture channel format. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipBindTextureToMipmappedArray( + const struct texture &tex, + hipMipmappedArray_const_t mipmappedArray, + const struct hipChannelFormatDesc &desc) +{ + return hipBindTextureToMipmappedArray(&tex, mipmappedArray, &desc); +} +/** + * @brief Unbinds a texture. + * + * @ingroup TextureD + * + * @param [in] tex Texture to unbind. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipUnbindTexture( + const struct texture &tex) +{ + return hipUnbindTexture(&tex); +} +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @ingroup StreamO + * @{ + * + * This section describes wrappers for stream Ordered allocation from memory pool functions of + * HIP runtime API. + * + * @note APIs in this section are implemented on Linux, under development on Windows. + * + */ + +/** + * @brief C++ wrappers for allocations from a memory pool + * + * This is an alternate C++ calls for @p hipMallocFromPoolAsync made available through + * function overloading. + * + * @see hipMallocFromPoolAsync + * + * @note This API is implemented on Linux, under development on Windows. + */ +static inline hipError_t hipMallocAsync( + void** dev_ptr, + size_t size, + hipMemPool_t mem_pool, + hipStream_t stream) { + return hipMallocFromPoolAsync(dev_ptr, size, mem_pool, stream); +} +/** + * @brief C++ wrappers for allocations from a memory pool on the stream + * + * This is an alternate C++ calls for @p hipMallocFromPoolAsync made available through + * function overloading. + * + * @see hipMallocFromPoolAsync + * + * @note This API is implemented on Linux, under development on Windows. + */ +template +static inline hipError_t hipMallocAsync( + T** dev_ptr, + size_t size, + hipMemPool_t mem_pool, + hipStream_t stream) { + return hipMallocFromPoolAsync(reinterpret_cast(dev_ptr), size, mem_pool, stream); +} +/** + * @brief C++ wrappers for allocations from a memory pool + * + * This is an alternate C++ calls for @p hipMallocFromPoolAsync made available through + * function overloading. + * + * @see hipMallocFromPoolAsync + * + * @note This API is implemented on Linux, under development on Windows. + */ +template +static inline hipError_t hipMallocAsync( + T** dev_ptr, + size_t size, + hipStream_t stream) { + return hipMallocAsync(reinterpret_cast(dev_ptr), size, stream); +} +/** + * @brief C++ wrappers for allocations from a memory pool + * + * This is an alternate C++ calls for @p hipMallocFromPoolAsync made available through + * function overloading. + * + * @see hipMallocFromPoolAsync + * + * @note This API is implemented on Linux, under development on Windows. + */ +template +static inline hipError_t hipMallocFromPoolAsync( + T** dev_ptr, + size_t size, + hipMemPool_t mem_pool, + hipStream_t stream) { + return hipMallocFromPoolAsync(reinterpret_cast(dev_ptr), size, mem_pool, stream); +} +/** +* @} +*/ + + +#endif // __cplusplus + +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + + +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include "hip/nvidia_detail/nvidia_hip_runtime_api.h" +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif + + +/** + * @brief: C++ wrapper for hipMalloc + * @ingroup Memory + * Perform automatic type conversion to eliminate need for excessive typecasting (ie void**) + * + * __HIP_DISABLE_CPP_FUNCTIONS__ macro can be defined to suppress these + * wrappers. It is useful for applications which need to obtain decltypes of + * HIP runtime APIs. + * + * @see hipMalloc + */ +#if defined(__cplusplus) && !defined(__HIP_DISABLE_CPP_FUNCTIONS__) +template +static inline hipError_t hipMalloc(T** devPtr, size_t size) { + return hipMalloc((void**)devPtr, size); +} +/** + * @brief: C++ wrapper for hipHostMalloc + * @ingroup Memory + * Provide an override to automatically typecast the pointer type from void**, and also provide a + * default for the flags. + * + * __HIP_DISABLE_CPP_FUNCTIONS__ macro can be defined to suppress these + * wrappers. It is useful for applications which need to obtain decltypes of + * HIP runtime APIs. + * + * @see hipHostMalloc + */ +template +static inline hipError_t hipHostMalloc(T** ptr, size_t size, + unsigned int flags = hipHostMallocDefault) { + return hipHostMalloc((void**)ptr, size, flags); +} +/** + * @brief: C++ wrapper for hipMallocManaged + * + * @ingroup MemoryM + * Provide an override to automatically typecast the pointer type from void**, and also provide a + * default for the flags. + * + * __HIP_DISABLE_CPP_FUNCTIONS__ macro can be defined to suppress these + * wrappers. It is useful for applications which need to obtain decltypes of + * HIP runtime APIs. + * + * @see hipMallocManaged + * + */ +template +static inline hipError_t hipMallocManaged(T** devPtr, size_t size, + unsigned int flags = hipMemAttachGlobal) { + return hipMallocManaged((void**)devPtr, size, flags); +} + + +#endif +#endif +// doxygen end HIP API +/** + * @} + */ +#include + +#if USE_PROF_API +#include +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_texture_types.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_texture_types.h new file mode 100644 index 0000000000000000000000000000000000000000..9cefbe674b2108da2807dd979654c526ee92316e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_texture_types.h @@ -0,0 +1,29 @@ +/* +Copyright (c) 2015 - 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_HIP_TEXTURE_TYPES_H +#define HIP_INCLUDE_HIP_HIP_TEXTURE_TYPES_H + +#include + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_vector_types.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_vector_types.h new file mode 100644 index 0000000000000000000000000000000000000000..cea4e92cd675a56929c54e9f73cdfe578cb080cb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_vector_types.h @@ -0,0 +1,41 @@ +/* +Copyright (c) 2015 - 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. +*/ + +//! hip_vector_types.h : Defines the HIP vector types. + +#ifndef HIP_INCLUDE_HIP_HIP_VECTOR_TYPES_H +#define HIP_INCLUDE_HIP_HIP_VECTOR_TYPES_H + +#include + + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +#if __cplusplus +#include +#endif +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_version.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_version.h new file mode 100644 index 0000000000000000000000000000000000000000..bab5288f806fcee459e87fb71f09c7364a9e81e3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hip_version.h @@ -0,0 +1,17 @@ +// Auto-generated by cmake + +#ifndef HIP_VERSION_H +#define HIP_VERSION_H + +#define HIP_VERSION_MAJOR 6 +#define HIP_VERSION_MINOR 2 +#define HIP_VERSION_PATCH 41134 +#define HIP_VERSION_GITHASH "65d174c3e" +#define HIP_VERSION_BUILD_ID 0 +#define HIP_VERSION_BUILD_NAME "" +#define HIP_VERSION (HIP_VERSION_MAJOR * 10000000 + HIP_VERSION_MINOR * 100000 + HIP_VERSION_PATCH) + +#define __HIP_HAS_GET_PCH 1 + +#endif + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hiprtc.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hiprtc.h new file mode 100644 index 0000000000000000000000000000000000000000..e10acbfe09c01b3e6004518618117e17e132ee5f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/hiprtc.h @@ -0,0 +1,421 @@ +/* +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. +*/ +#pragma once + +#include + +#if !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include +#elif defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#include + +#if !defined(_WIN32) +#pragma GCC visibility push(default) +#endif + +/** + * + * @addtogroup GlobalDefs + * @{ + * + */ + /** + * hiprtc error code + */ +typedef enum hiprtcResult { + HIPRTC_SUCCESS = 0, ///< Success + HIPRTC_ERROR_OUT_OF_MEMORY = 1, ///< Out of memory + HIPRTC_ERROR_PROGRAM_CREATION_FAILURE = 2, ///< Failed to create program + HIPRTC_ERROR_INVALID_INPUT = 3, ///< Invalid input + HIPRTC_ERROR_INVALID_PROGRAM = 4, ///< Invalid program + HIPRTC_ERROR_INVALID_OPTION = 5, ///< Invalid option + HIPRTC_ERROR_COMPILATION = 6, ///< Compilation error + HIPRTC_ERROR_BUILTIN_OPERATION_FAILURE = 7, ///< Failed in builtin operation + HIPRTC_ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION = 8, ///< No name expression after compilation + HIPRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION = 9, ///< No lowered names before compilation + HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID = 10, ///< Invalid name expression + HIPRTC_ERROR_INTERNAL_ERROR = 11, ///< Internal error + HIPRTC_ERROR_LINKING = 100 ///< Error in linking +} hiprtcResult; + +/** + * hiprtc JIT option + */ + +typedef enum hiprtcJIT_option { + HIPRTC_JIT_MAX_REGISTERS = 0, ///< CUDA Only Maximum registers may be used in a thread, passed to compiler + HIPRTC_JIT_THREADS_PER_BLOCK, ///< CUDA Only Number of thread per block + HIPRTC_JIT_WALL_TIME, ///< CUDA Only Value for total wall clock time + HIPRTC_JIT_INFO_LOG_BUFFER, ///< CUDA Only Pointer to the buffer with logged information + HIPRTC_JIT_INFO_LOG_BUFFER_SIZE_BYTES, ///< CUDA Only Size of the buffer in bytes for logged info + HIPRTC_JIT_ERROR_LOG_BUFFER, ///< CUDA Only Pointer to the buffer with logged error(s) + HIPRTC_JIT_ERROR_LOG_BUFFER_SIZE_BYTES, ///< CUDA Only Size of the buffer in bytes for logged error(s) + HIPRTC_JIT_OPTIMIZATION_LEVEL, ///< Value of optimization level for generated codes, acceptable options -O0, -O1, -O2, -O3 + HIPRTC_JIT_TARGET_FROM_HIPCONTEXT, ///< CUDA Only The target context, which is the default + HIPRTC_JIT_TARGET, ///< CUDA Only JIT target + HIPRTC_JIT_FALLBACK_STRATEGY, ///< CUDA Only Fallback strategy + HIPRTC_JIT_GENERATE_DEBUG_INFO, ///< CUDA Only Generate debug information + HIPRTC_JIT_LOG_VERBOSE, ///< CUDA Only Generate log verbose + HIPRTC_JIT_GENERATE_LINE_INFO, ///< CUDA Only Generate line number information + HIPRTC_JIT_CACHE_MODE, ///< CUDA Only Set cache mode + HIPRTC_JIT_NEW_SM3X_OPT, ///< @deprecated CUDA Only New SM3X option. + HIPRTC_JIT_FAST_COMPILE, ///< CUDA Only Set fast compile + HIPRTC_JIT_GLOBAL_SYMBOL_NAMES, ///< CUDA Only Array of device symbol names to be relocated to the host + HIPRTC_JIT_GLOBAL_SYMBOL_ADDRESS, ///< CUDA Only Array of host addresses to be relocated to the device + HIPRTC_JIT_GLOBAL_SYMBOL_COUNT, ///< CUDA Only Number of symbol count. + HIPRTC_JIT_LTO, ///< @deprecated CUDA Only Enable link-time optimization for device code + HIPRTC_JIT_FTZ, ///< @deprecated CUDA Only Set single-precision denormals. + HIPRTC_JIT_PREC_DIV, ///< @deprecated CUDA Only Set single-precision floating-point division and + ///< reciprocals + HIPRTC_JIT_PREC_SQRT, ///< @deprecated CUDA Only Set single-precision floating-point square root + HIPRTC_JIT_FMA, ///< @deprecated CUDA Only Enable floating-point multiplies and adds/subtracts operations + HIPRTC_JIT_NUM_OPTIONS, ///< Number of options + HIPRTC_JIT_IR_TO_ISA_OPT_EXT = 10000, ///< Linker options to be passed on to compiler + /// @note Only supported for the AMD platform. + HIPRTC_JIT_IR_TO_ISA_OPT_COUNT_EXT, ///< Count of linker options to be passed on to + ///< compiler @note Only supported for the AMD platform +} hiprtcJIT_option; + +/** + * hiprtc JIT input type + */ +typedef enum hiprtcJITInputType { + HIPRTC_JIT_INPUT_CUBIN = 0, ///< Input cubin + HIPRTC_JIT_INPUT_PTX, ///< Input PTX + HIPRTC_JIT_INPUT_FATBINARY, ///< Input fat binary + HIPRTC_JIT_INPUT_OBJECT, ///< Input object + HIPRTC_JIT_INPUT_LIBRARY, ///< Input library + HIPRTC_JIT_INPUT_NVVM, ///< Input NVVM + HIPRTC_JIT_NUM_LEGACY_INPUT_TYPES, ///< Number of legacy input type + HIPRTC_JIT_INPUT_LLVM_BITCODE = 100, ///< LLVM bitcode or IR assembly + HIPRTC_JIT_INPUT_LLVM_BUNDLED_BITCODE = 101, ///< LLVM bundled bitcode + HIPRTC_JIT_INPUT_LLVM_ARCHIVES_OF_BUNDLED_BITCODE = 102, ///< LLVM archives of boundled bitcode + HIPRTC_JIT_NUM_INPUT_TYPES = (HIPRTC_JIT_NUM_LEGACY_INPUT_TYPES + 3) +} hiprtcJITInputType; +/** +* @} +*/ + +/** + * hiprtc link state + * + */ +typedef struct ihiprtcLinkState* hiprtcLinkState; +/** + * @ingroup Runtime + * + * @brief Returns text string message to explain the error which occurred + * + * @param [in] result code to convert to string. + * @returns const char pointer to the NULL-terminated error string + * + * @warning In HIP, this function returns the name of the error, + * if the hiprtc result is defined, it will return "Invalid HIPRTC error code" + * + * @see hiprtcResult + */ +const char* hiprtcGetErrorString(hiprtcResult result); + +/** + * @ingroup Runtime + * @brief Sets the parameters as major and minor version. + * + * @param [out] major HIP Runtime Compilation major version. + * @param [out] minor HIP Runtime Compilation minor version. + * + * @returns #HIPRTC_ERROR_INVALID_INPUT, #HIPRTC_SUCCESS + * + */ +hiprtcResult hiprtcVersion(int* major, int* minor); + +/** + * hiprtc program + * + */ +typedef struct _hiprtcProgram* hiprtcProgram; + +/** + * @ingroup Runtime + * @brief Adds the given name exprssion to the runtime compilation program. + * + * @param [in] prog runtime compilation program instance. + * @param [in] name_expression const char pointer to the name expression. + * @returns #HIPRTC_SUCCESS + * + * If const char pointer is NULL, it will return #HIPRTC_ERROR_INVALID_INPUT. + * + * @see hiprtcResult + */ +hiprtcResult hiprtcAddNameExpression(hiprtcProgram prog, + const char* name_expression); + +/** + * @ingroup Runtime + * @brief Compiles the given runtime compilation program. + * + * @param [in] prog runtime compilation program instance. + * @param [in] numOptions number of compiler options. + * @param [in] options compiler options as const array of strins. + * @returns #HIPRTC_SUCCESS + * + * If the compiler failed to build the runtime compilation program, + * it will return #HIPRTC_ERROR_COMPILATION. + * + * @see hiprtcResult + */ +hiprtcResult hiprtcCompileProgram(hiprtcProgram prog, + int numOptions, + const char** options); + +/** + * @ingroup Runtime + * @brief Creates an instance of hiprtcProgram with the given input parameters, + * and sets the output hiprtcProgram prog with it. + * + * @param [in, out] prog runtime compilation program instance. + * @param [in] src const char pointer to the program source. + * @param [in] name const char pointer to the program name. + * @param [in] numHeaders number of headers. + * @param [in] headers array of strings pointing to headers. + * @param [in] includeNames array of strings pointing to names included in program source. + * @returns #HIPRTC_SUCCESS + * + * Any invalide input parameter, it will return #HIPRTC_ERROR_INVALID_INPUT + * or #HIPRTC_ERROR_INVALID_PROGRAM. + * + * If failed to create the program, it will return #HIPRTC_ERROR_PROGRAM_CREATION_FAILURE. + * + * @see hiprtcResult + */ +hiprtcResult hiprtcCreateProgram(hiprtcProgram* prog, + const char* src, + const char* name, + int numHeaders, + const char** headers, + const char** includeNames); + +/** + * @brief Destroys an instance of given hiprtcProgram. + * @ingroup Runtime + * @param [in] prog runtime compilation program instance. + * @returns #HIPRTC_SUCCESS + * + * If prog is NULL, it will return #HIPRTC_ERROR_INVALID_INPUT. + * + * @see hiprtcResult + */ +hiprtcResult hiprtcDestroyProgram(hiprtcProgram* prog); + +/** + * @brief Gets the lowered (mangled) name from an instance of hiprtcProgram with the given input parameters, + * and sets the output lowered_name with it. + * @ingroup Runtime + * @param [in] prog runtime compilation program instance. + * @param [in] name_expression const char pointer to the name expression. + * @param [in, out] lowered_name const char array to the lowered (mangled) name. + * @returns #HIPRTC_SUCCESS + * + * If any invalide nullptr input parameters, it will return #HIPRTC_ERROR_INVALID_INPUT + * + * If name_expression is not found, it will return #HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID + * + * If failed to get lowered_name from the program, it will return #HIPRTC_ERROR_COMPILATION. + * + * @see hiprtcResult + */ +hiprtcResult hiprtcGetLoweredName(hiprtcProgram prog, + const char* name_expression, + const char** lowered_name); + +/** + * @brief Gets the log generated by the runtime compilation program instance. + * @ingroup Runtime + * @param [in] prog runtime compilation program instance. + * @param [out] log memory pointer to the generated log. + * @returns #HIPRTC_SUCCESS + * + * @see hiprtcResult + */ +hiprtcResult hiprtcGetProgramLog(hiprtcProgram prog, char* log); + +/** + * @brief Gets the size of log generated by the runtime compilation program instance. + * + * @param [in] prog runtime compilation program instance. + * @param [out] logSizeRet size of generated log. + * @returns #HIPRTC_SUCCESS + * + * @see hiprtcResult + */ +hiprtcResult hiprtcGetProgramLogSize(hiprtcProgram prog, + size_t* logSizeRet); + +/** + * @brief Gets the pointer of compilation binary by the runtime compilation program instance. + * @ingroup Runtime + * @param [in] prog runtime compilation program instance. + * @param [out] code char pointer to binary. + * @returns #HIPRTC_SUCCESS + * + * @see hiprtcResult + */ +hiprtcResult hiprtcGetCode(hiprtcProgram prog, char* code); + +/** + * @brief Gets the size of compilation binary by the runtime compilation program instance. + * @ingroup Runtime + * @param [in] prog runtime compilation program instance. + * @param [out] codeSizeRet the size of binary. + * @returns #HIPRTC_SUCCESS + * + * @see hiprtcResult + */ +hiprtcResult hiprtcGetCodeSize(hiprtcProgram prog, size_t* codeSizeRet); + +/** + * @brief Gets the pointer of compiled bitcode by the runtime compilation program instance. + * + * @param [in] prog runtime compilation program instance. + * @param [out] bitcode char pointer to bitcode. + * @return HIPRTC_SUCCESS + * + * @see hiprtcResult + */ +hiprtcResult hiprtcGetBitcode(hiprtcProgram prog, char* bitcode); + +/** + * @brief Gets the size of compiled bitcode by the runtime compilation program instance. + * @ingroup Runtime + * + * @param [in] prog runtime compilation program instance. + * @param [out] bitcode_size the size of bitcode. + * @returns #HIPRTC_SUCCESS + * + * @see hiprtcResult + */ +hiprtcResult hiprtcGetBitcodeSize(hiprtcProgram prog, size_t* bitcode_size); + +/** + * @brief Creates the link instance via hiprtc APIs. + * @ingroup Runtime + * @param [in] num_options Number of options + * @param [in] option_ptr Array of options + * @param [in] option_vals_pptr Array of option values cast to void* + * @param [out] hip_link_state_ptr hiprtc link state created upon success + * + * @returns #HIPRTC_SUCCESS, #HIPRTC_ERROR_INVALID_INPUT, #HIPRTC_ERROR_INVALID_OPTION + * + * @see hiprtcResult + */ +hiprtcResult hiprtcLinkCreate(unsigned int num_options, hiprtcJIT_option* option_ptr, + void** option_vals_pptr, hiprtcLinkState* hip_link_state_ptr); + +/** + * @brief Adds a file with bit code to be linked with options + * @ingroup Runtime + * @param [in] hip_link_state hiprtc link state + * @param [in] input_type Type of the input data or bitcode + * @param [in] file_path Path to the input file where bitcode is present + * @param [in] num_options Size of the options + * @param [in] options_ptr Array of options applied to this input + * @param [in] option_values Array of option values cast to void* + * + * @returns #HIPRTC_SUCCESS + * + * If input values are invalid, it will + * @return #HIPRTC_ERROR_INVALID_INPUT + * + * @see hiprtcResult + */ + +hiprtcResult hiprtcLinkAddFile(hiprtcLinkState hip_link_state, hiprtcJITInputType input_type, + const char* file_path, unsigned int num_options, + hiprtcJIT_option* options_ptr, void** option_values); + +/** + * @brief Completes the linking of the given program. + * @ingroup Runtime + * @param [in] hip_link_state hiprtc link state + * @param [in] input_type Type of the input data or bitcode + * @param [in] image Input data which is null terminated + * @param [in] image_size Size of the input data + * @param [in] name Optional name for this input + * @param [in] num_options Size of the options + * @param [in] options_ptr Array of options applied to this input + * @param [in] option_values Array of option values cast to void* + * + * @returns #HIPRTC_SUCCESS, #HIPRTC_ERROR_INVALID_INPUT + * + * If adding the file fails, it will + * @return #HIPRTC_ERROR_PROGRAM_CREATION_FAILURE + * + * @see hiprtcResult + */ + +hiprtcResult hiprtcLinkAddData(hiprtcLinkState hip_link_state, hiprtcJITInputType input_type, + void* image, size_t image_size, const char* name, + unsigned int num_options, hiprtcJIT_option* options_ptr, + void** option_values); + +/** + * @brief Completes the linking of the given program. + * @ingroup Runtime + * @param [in] hip_link_state hiprtc link state + * @param [out] bin_out Upon success, points to the output binary + * @param [out] size_out Size of the binary is stored (optional) + * + * @returns #HIPRTC_SUCCESS + * + * If adding the data fails, it will + * @return #HIPRTC_ERROR_LINKING + * + * @see hiprtcResult + */ +hiprtcResult hiprtcLinkComplete(hiprtcLinkState hip_link_state, void** bin_out, size_t* size_out); + +/** + * @brief Deletes the link instance via hiprtc APIs. + * @ingroup Runtime + * @param [in] hip_link_state link state instance + * + * @returns #HIPRTC_SUCCESS + * + * @see hiprtcResult + */ +hiprtcResult hiprtcLinkDestroy(hiprtcLinkState hip_link_state); + +#if !defined(_WIN32) +#pragma GCC visibility pop +#endif + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/library_types.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/library_types.h new file mode 100644 index 0000000000000000000000000000000000000000..f5570d5e9e91b5fb22a8adde6d12d0f8aa605617 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/library_types.h @@ -0,0 +1,78 @@ +/* +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_LIBRARY_TYPES_H +#define HIP_INCLUDE_HIP_LIBRARY_TYPES_H + +#if !defined(__HIPCC_RTC__) +#include +#endif + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) + +typedef enum hipDataType { + HIP_R_32F = 0, + HIP_R_64F = 1, + HIP_R_16F = 2, + HIP_R_8I = 3, + HIP_C_32F = 4, + HIP_C_64F = 5, + HIP_C_16F = 6, + HIP_C_8I = 7, + HIP_R_8U = 8, + HIP_C_8U = 9, + HIP_R_32I = 10, + HIP_C_32I = 11, + HIP_R_32U = 12, + HIP_C_32U = 13, + HIP_R_16BF = 14, + HIP_C_16BF = 15, + HIP_R_4I = 16, + HIP_C_4I = 17, + HIP_R_4U = 18, + HIP_C_4U = 19, + HIP_R_16I = 20, + HIP_C_16I = 21, + HIP_R_16U = 22, + HIP_C_16U = 23, + HIP_R_64I = 24, + HIP_C_64I = 25, + HIP_R_64U = 26, + HIP_C_64U = 27, + // HIP specific Data Types + HIP_R_8F_E4M3_FNUZ = 1000, + HIP_R_8F_E5M2_FNUZ = 1001 +} hipDataType; + +typedef enum hipLibraryPropertyType { + HIP_LIBRARY_MAJOR_VERSION, + HIP_LIBRARY_MINOR_VERSION, + HIP_LIBRARY_PATCH_LEVEL +} hipLibraryPropertyType; + +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include "library_types.h" +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/math_functions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/math_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..967fdb47aa9493c53ea1a1b471d0e9bcd4af0520 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/math_functions.h @@ -0,0 +1,42 @@ +/* +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_MATH_FUNCTIONS_H +#define HIP_INCLUDE_HIP_MATH_FUNCTIONS_H + +// Some standard header files, these are included by hc.hpp and so want to make them avail on both +// paths to provide a consistent include env and avoid "missing symbol" errors that only appears +// on NVCC path: + +#if !defined(__HIPCC_RTC__) +#include +#endif + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +#include +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +//#include +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/surface_types.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/surface_types.h new file mode 100644 index 0000000000000000000000000000000000000000..62fb681111c041a0f470a20b8bc4c1cd6d90ec27 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/surface_types.h @@ -0,0 +1,63 @@ +/* +Copyright (c) 2022 - 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 surface_types.h + * @brief Defines surface types for HIP runtime. + */ + +#ifndef HIP_INCLUDE_HIP_SURFACE_TYPES_H +#define HIP_INCLUDE_HIP_SURFACE_TYPES_H + +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreserved-identifier" +#endif + +#if !defined(__HIPCC_RTC__) +#include +#endif + +/** + * An opaque value that represents a hip surface object + */ +struct __hip_surface; +typedef struct __hip_surface* hipSurfaceObject_t; + +/** + * hip surface reference + */ +struct surfaceReference { + hipSurfaceObject_t surfaceObject; +}; + +/** + * hip surface boundary modes + */ +enum hipSurfaceBoundaryMode { + hipBoundaryModeZero = 0, + hipBoundaryModeTrap = 1, + hipBoundaryModeClamp = 2 +}; + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#endif /* !HIP_INCLUDE_HIP_SURFACE_TYPES_H */ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/texture_types.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/texture_types.h new file mode 100644 index 0000000000000000000000000000000000000000..3473c8188637995720d20e614e85d06d8bdf7d59 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/texture_types.h @@ -0,0 +1,194 @@ +/* +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_TEXTURE_TYPES_H +#define HIP_INCLUDE_HIP_TEXTURE_TYPES_H + +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreserved-identifier" +#pragma clang diagnostic ignored "-Wreserved-macro-identifier" +#pragma clang diagnostic ignored "-Wc++98-compat" +#endif + +#if !defined(__HIPCC_RTC__) +#include +#endif + +#if !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include "texture_types.h" +#elif defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +/******************************************************************************* + * * + * * + * * + *******************************************************************************/ +#if !defined(__HIPCC_RTC__) +#include +#include +#include +#endif // !defined(__HIPCC_RTC__) + +#define hipTextureType1D 0x01 +#define hipTextureType2D 0x02 +#define hipTextureType3D 0x03 +#define hipTextureTypeCubemap 0x0C +#define hipTextureType1DLayered 0xF1 +#define hipTextureType2DLayered 0xF2 +#define hipTextureTypeCubemapLayered 0xFC + +/** + * Should be same as HSA_IMAGE_OBJECT_SIZE_DWORD/HSA_SAMPLER_OBJECT_SIZE_DWORD + */ +#define HIP_IMAGE_OBJECT_SIZE_DWORD 12 +#define HIP_SAMPLER_OBJECT_SIZE_DWORD 8 +#define HIP_SAMPLER_OBJECT_OFFSET_DWORD HIP_IMAGE_OBJECT_SIZE_DWORD +#define HIP_TEXTURE_OBJECT_SIZE_DWORD (HIP_IMAGE_OBJECT_SIZE_DWORD + HIP_SAMPLER_OBJECT_SIZE_DWORD) + +/** + * An opaque value that represents a hip texture object + */ +struct __hip_texture; +typedef struct __hip_texture* hipTextureObject_t; + +/** + * hip texture address modes + */ +enum hipTextureAddressMode { + hipAddressModeWrap = 0, + hipAddressModeClamp = 1, + hipAddressModeMirror = 2, + hipAddressModeBorder = 3 +}; + +/** + * hip texture filter modes + */ +enum hipTextureFilterMode { hipFilterModePoint = 0, hipFilterModeLinear = 1 }; + +/** + * hip texture read modes + */ +enum hipTextureReadMode { hipReadModeElementType = 0, hipReadModeNormalizedFloat = 1 }; + +/** + * hip texture reference + */ +typedef struct textureReference { + int normalized; + enum hipTextureReadMode readMode;// used only for driver API's + enum hipTextureFilterMode filterMode; + enum hipTextureAddressMode addressMode[3]; // Texture address mode for up to 3 dimensions + struct hipChannelFormatDesc channelDesc; + int sRGB; // Perform sRGB->linear conversion during texture read + unsigned int maxAnisotropy; // Limit to the anisotropy ratio + enum hipTextureFilterMode mipmapFilterMode; + float mipmapLevelBias; + float minMipmapLevelClamp; + float maxMipmapLevelClamp; + + hipTextureObject_t textureObject; + int numChannels; + enum hipArray_Format format; +}textureReference; + +/** + * hip texture descriptor + */ +typedef struct hipTextureDesc { + enum hipTextureAddressMode addressMode[3]; // Texture address mode for up to 3 dimensions + enum hipTextureFilterMode filterMode; + enum hipTextureReadMode readMode; + int sRGB; // Perform sRGB->linear conversion during texture read + float borderColor[4]; + int normalizedCoords; + unsigned int maxAnisotropy; + enum hipTextureFilterMode mipmapFilterMode; + float mipmapLevelBias; + float minMipmapLevelClamp; + float maxMipmapLevelClamp; +}hipTextureDesc; + +#if __cplusplus + +/******************************************************************************* + * * + * * + * * + *******************************************************************************/ +#if __HIP__ +#define __HIP_TEXTURE_ATTRIB __attribute__((device_builtin_texture_type)) +#else +#define __HIP_TEXTURE_ATTRIB +#endif + +typedef textureReference* hipTexRef; + +template +struct __HIP_TEXTURE_ATTRIB texture : public textureReference { + texture(int norm = 0, enum hipTextureFilterMode fMode = hipFilterModePoint, + enum hipTextureAddressMode aMode = hipAddressModeClamp) { + normalized = norm; + readMode = mode; + filterMode = fMode; + addressMode[0] = aMode; + addressMode[1] = aMode; + addressMode[2] = aMode; + channelDesc = hipCreateChannelDesc(); + sRGB = 0; + textureObject = nullptr; + maxAnisotropy = 0; + mipmapLevelBias = 0; + minMipmapLevelClamp = 0; + maxMipmapLevelClamp = 0; + } + + texture(int norm, enum hipTextureFilterMode fMode, enum hipTextureAddressMode aMode, + struct hipChannelFormatDesc desc) { + normalized = norm; + readMode = mode; + filterMode = fMode; + addressMode[0] = aMode; + addressMode[1] = aMode; + addressMode[2] = aMode; + channelDesc = desc; + sRGB = 0; + textureObject = nullptr; + maxAnisotropy = 0; + mipmapLevelBias = 0; + minMipmapLevelClamp = 0; + maxMipmapLevelClamp = 0; + } +}; + +#endif /* __cplusplus */ + +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/Brig.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/Brig.h new file mode 100644 index 0000000000000000000000000000000000000000..4f34bd1d5012c1fca9a01417be4e4d025fa1ff15 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/Brig.h @@ -0,0 +1,1131 @@ +// University of Illinois/NCSA +// Open Source License +// +// Copyright (c) 2013-2015, Advanced Micro Devices, Inc. +// All rights reserved. +// +// Developed by: +// +// HSA Team +// +// Advanced Micro Devices, Inc +// +// www.amd.com +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal with +// 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: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimers in the +// documentation and/or other materials provided with the distribution. +// +// * Neither the names of the LLVM Team, University of Illinois at +// Urbana-Champaign, nor the names of its contributors may be used to +// endorse or promote products derived from this Software without specific +// prior written permission. +// +// 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 +// CONTRIBUTORS 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 WITH THE +// SOFTWARE. + +#ifndef INCLUDED_BRIG_H +#define INCLUDED_BRIG_H + +#include /* size_t */ +#include /* uintXX_t */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/*========================================================================================*/ +/* =======================================================================================*/ +/* =======================================================================================*/ +/* =======================================================================================*/ + +typedef uint32_t BrigCodeOffset32_t; +typedef uint32_t BrigOperandOffset32_t; +typedef uint32_t BrigDataOffset32_t; + +typedef BrigDataOffset32_t BrigDataOffsetCodeList32_t; +typedef BrigDataOffset32_t BrigDataOffsetOperandList32_t; +typedef BrigDataOffset32_t BrigDataOffsetString32_t; + +typedef uint32_t BrigVersion32_t; +enum BrigVersion { + BRIG_VERSION_HSAIL_MAJOR = 1, + BRIG_VERSION_HSAIL_MINOR = 0, + BRIG_VERSION_BRIG_MAJOR = 1, + BRIG_VERSION_BRIG_MINOR = 0 +}; + +typedef uint16_t BrigKind16_t; +enum BrigKind { + BRIG_KIND_NONE = 0x0000, + + BRIG_KIND_DIRECTIVE_BEGIN = 0x1000, + BRIG_KIND_DIRECTIVE_ARG_BLOCK_END = 0x1000, + BRIG_KIND_DIRECTIVE_ARG_BLOCK_START = 0x1001, + BRIG_KIND_DIRECTIVE_COMMENT = 0x1002, + BRIG_KIND_DIRECTIVE_CONTROL = 0x1003, + BRIG_KIND_DIRECTIVE_EXTENSION = 0x1004, + BRIG_KIND_DIRECTIVE_FBARRIER = 0x1005, + BRIG_KIND_DIRECTIVE_FUNCTION = 0x1006, + BRIG_KIND_DIRECTIVE_INDIRECT_FUNCTION = 0x1007, + BRIG_KIND_DIRECTIVE_KERNEL = 0x1008, + BRIG_KIND_DIRECTIVE_LABEL = 0x1009, + BRIG_KIND_DIRECTIVE_LOC = 0x100a, + BRIG_KIND_DIRECTIVE_MODULE = 0x100b, + BRIG_KIND_DIRECTIVE_PRAGMA = 0x100c, + BRIG_KIND_DIRECTIVE_SIGNATURE = 0x100d, + BRIG_KIND_DIRECTIVE_VARIABLE = 0x100e, + BRIG_KIND_DIRECTIVE_END = 0x100f, + + BRIG_KIND_INST_BEGIN = 0x2000, + BRIG_KIND_INST_ADDR = 0x2000, + BRIG_KIND_INST_ATOMIC = 0x2001, + BRIG_KIND_INST_BASIC = 0x2002, + BRIG_KIND_INST_BR = 0x2003, + BRIG_KIND_INST_CMP = 0x2004, + BRIG_KIND_INST_CVT = 0x2005, + BRIG_KIND_INST_IMAGE = 0x2006, + BRIG_KIND_INST_LANE = 0x2007, + BRIG_KIND_INST_MEM = 0x2008, + BRIG_KIND_INST_MEM_FENCE = 0x2009, + BRIG_KIND_INST_MOD = 0x200a, + BRIG_KIND_INST_QUERY_IMAGE = 0x200b, + BRIG_KIND_INST_QUERY_SAMPLER = 0x200c, + BRIG_KIND_INST_QUEUE = 0x200d, + BRIG_KIND_INST_SEG = 0x200e, + BRIG_KIND_INST_SEG_CVT = 0x200f, + BRIG_KIND_INST_SIGNAL = 0x2010, + BRIG_KIND_INST_SOURCE_TYPE = 0x2011, + BRIG_KIND_INST_END = 0x2012, + + BRIG_KIND_OPERAND_BEGIN = 0x3000, + BRIG_KIND_OPERAND_ADDRESS = 0x3000, + BRIG_KIND_OPERAND_ALIGN = 0x3001, + BRIG_KIND_OPERAND_CODE_LIST = 0x3002, + BRIG_KIND_OPERAND_CODE_REF = 0x3003, + BRIG_KIND_OPERAND_CONSTANT_BYTES = 0x3004, + BRIG_KIND_OPERAND_RESERVED = 0x3005, + BRIG_KIND_OPERAND_CONSTANT_IMAGE = 0x3006, + BRIG_KIND_OPERAND_CONSTANT_OPERAND_LIST = 0x3007, + BRIG_KIND_OPERAND_CONSTANT_SAMPLER = 0x3008, + BRIG_KIND_OPERAND_OPERAND_LIST = 0x3009, + BRIG_KIND_OPERAND_REGISTER = 0x300a, + BRIG_KIND_OPERAND_STRING = 0x300b, + BRIG_KIND_OPERAND_WAVESIZE = 0x300c, + BRIG_KIND_OPERAND_END = 0x300d +}; + +typedef uint8_t BrigAlignment8_t; +enum BrigAlignment { + BRIG_ALIGNMENT_NONE = 0, + BRIG_ALIGNMENT_1 = 1, + BRIG_ALIGNMENT_2 = 2, + BRIG_ALIGNMENT_4 = 3, + BRIG_ALIGNMENT_8 = 4, + BRIG_ALIGNMENT_16 = 5, + BRIG_ALIGNMENT_32 = 6, + BRIG_ALIGNMENT_64 = 7, + BRIG_ALIGNMENT_128 = 8, + BRIG_ALIGNMENT_256 = 9, + BRIG_ALIGNMENT_MAX = BRIG_ALIGNMENT_256 +}; + +typedef uint8_t BrigAllocation8_t; +enum BrigAllocation { + BRIG_ALLOCATION_NONE = 0, + BRIG_ALLOCATION_PROGRAM = 1, + BRIG_ALLOCATION_AGENT = 2, + BRIG_ALLOCATION_AUTOMATIC = 3 +}; + +typedef uint8_t BrigAluModifier8_t; +enum BrigAluModifierMask { + BRIG_ALU_FTZ = 1 +}; + +typedef uint8_t BrigAtomicOperation8_t; +enum BrigAtomicOperation { + BRIG_ATOMIC_ADD = 0, + BRIG_ATOMIC_AND = 1, + BRIG_ATOMIC_CAS = 2, + BRIG_ATOMIC_EXCH = 3, + BRIG_ATOMIC_LD = 4, + BRIG_ATOMIC_MAX = 5, + BRIG_ATOMIC_MIN = 6, + BRIG_ATOMIC_OR = 7, + BRIG_ATOMIC_ST = 8, + BRIG_ATOMIC_SUB = 9, + BRIG_ATOMIC_WRAPDEC = 10, + BRIG_ATOMIC_WRAPINC = 11, + BRIG_ATOMIC_XOR = 12, + BRIG_ATOMIC_WAIT_EQ = 13, + BRIG_ATOMIC_WAIT_NE = 14, + BRIG_ATOMIC_WAIT_LT = 15, + BRIG_ATOMIC_WAIT_GTE = 16, + BRIG_ATOMIC_WAITTIMEOUT_EQ = 17, + BRIG_ATOMIC_WAITTIMEOUT_NE = 18, + BRIG_ATOMIC_WAITTIMEOUT_LT = 19, + BRIG_ATOMIC_WAITTIMEOUT_GTE = 20 +}; + +typedef uint8_t BrigCompareOperation8_t; +enum BrigCompareOperation { + BRIG_COMPARE_EQ = 0, + BRIG_COMPARE_NE = 1, + BRIG_COMPARE_LT = 2, + BRIG_COMPARE_LE = 3, + BRIG_COMPARE_GT = 4, + BRIG_COMPARE_GE = 5, + BRIG_COMPARE_EQU = 6, + BRIG_COMPARE_NEU = 7, + BRIG_COMPARE_LTU = 8, + BRIG_COMPARE_LEU = 9, + BRIG_COMPARE_GTU = 10, + BRIG_COMPARE_GEU = 11, + BRIG_COMPARE_NUM = 12, + BRIG_COMPARE_NAN = 13, + BRIG_COMPARE_SEQ = 14, + BRIG_COMPARE_SNE = 15, + BRIG_COMPARE_SLT = 16, + BRIG_COMPARE_SLE = 17, + BRIG_COMPARE_SGT = 18, + BRIG_COMPARE_SGE = 19, + BRIG_COMPARE_SGEU = 20, + BRIG_COMPARE_SEQU = 21, + BRIG_COMPARE_SNEU = 22, + BRIG_COMPARE_SLTU = 23, + BRIG_COMPARE_SLEU = 24, + BRIG_COMPARE_SNUM = 25, + BRIG_COMPARE_SNAN = 26, + BRIG_COMPARE_SGTU = 27 +}; + +typedef uint16_t BrigControlDirective16_t; +enum BrigControlDirective { + BRIG_CONTROL_NONE = 0, + BRIG_CONTROL_ENABLEBREAKEXCEPTIONS = 1, + BRIG_CONTROL_ENABLEDETECTEXCEPTIONS = 2, + BRIG_CONTROL_MAXDYNAMICGROUPSIZE = 3, + BRIG_CONTROL_MAXFLATGRIDSIZE = 4, + BRIG_CONTROL_MAXFLATWORKGROUPSIZE = 5, + BRIG_CONTROL_REQUIREDDIM = 6, + BRIG_CONTROL_REQUIREDGRIDSIZE = 7, + BRIG_CONTROL_REQUIREDWORKGROUPSIZE = 8, + BRIG_CONTROL_REQUIRENOPARTIALWORKGROUPS = 9 +}; + +typedef uint8_t BrigExecutableModifier8_t; +enum BrigExecutableModifierMask { + BRIG_EXECUTABLE_DEFINITION = 1 +}; + +typedef uint8_t BrigImageChannelOrder8_t; +enum BrigImageChannelOrder { + BRIG_CHANNEL_ORDER_A = 0, + BRIG_CHANNEL_ORDER_R = 1, + BRIG_CHANNEL_ORDER_RX = 2, + BRIG_CHANNEL_ORDER_RG = 3, + BRIG_CHANNEL_ORDER_RGX = 4, + BRIG_CHANNEL_ORDER_RA = 5, + BRIG_CHANNEL_ORDER_RGB = 6, + BRIG_CHANNEL_ORDER_RGBX = 7, + BRIG_CHANNEL_ORDER_RGBA = 8, + BRIG_CHANNEL_ORDER_BGRA = 9, + BRIG_CHANNEL_ORDER_ARGB = 10, + BRIG_CHANNEL_ORDER_ABGR = 11, + BRIG_CHANNEL_ORDER_SRGB = 12, + BRIG_CHANNEL_ORDER_SRGBX = 13, + BRIG_CHANNEL_ORDER_SRGBA = 14, + BRIG_CHANNEL_ORDER_SBGRA = 15, + BRIG_CHANNEL_ORDER_INTENSITY = 16, + BRIG_CHANNEL_ORDER_LUMINANCE = 17, + BRIG_CHANNEL_ORDER_DEPTH = 18, + BRIG_CHANNEL_ORDER_DEPTH_STENCIL = 19, + + BRIG_CHANNEL_ORDER_FIRST_USER_DEFINED = 128 +}; + +typedef uint8_t BrigImageChannelType8_t; +enum BrigImageChannelType { + BRIG_CHANNEL_TYPE_SNORM_INT8 = 0, + BRIG_CHANNEL_TYPE_SNORM_INT16 = 1, + BRIG_CHANNEL_TYPE_UNORM_INT8 = 2, + BRIG_CHANNEL_TYPE_UNORM_INT16 = 3, + BRIG_CHANNEL_TYPE_UNORM_INT24 = 4, + BRIG_CHANNEL_TYPE_UNORM_SHORT_555 = 5, + BRIG_CHANNEL_TYPE_UNORM_SHORT_565 = 6, + BRIG_CHANNEL_TYPE_UNORM_INT_101010 = 7, + BRIG_CHANNEL_TYPE_SIGNED_INT8 = 8, + BRIG_CHANNEL_TYPE_SIGNED_INT16 = 9, + BRIG_CHANNEL_TYPE_SIGNED_INT32 = 10, + BRIG_CHANNEL_TYPE_UNSIGNED_INT8 = 11, + BRIG_CHANNEL_TYPE_UNSIGNED_INT16 = 12, + BRIG_CHANNEL_TYPE_UNSIGNED_INT32 = 13, + BRIG_CHANNEL_TYPE_HALF_FLOAT = 14, + BRIG_CHANNEL_TYPE_FLOAT = 15, + + BRIG_CHANNEL_TYPE_FIRST_USER_DEFINED = 128 +}; + +typedef uint8_t BrigImageGeometry8_t; +enum BrigImageGeometry { + BRIG_GEOMETRY_1D = 0, + BRIG_GEOMETRY_2D = 1, + BRIG_GEOMETRY_3D = 2, + BRIG_GEOMETRY_1DA = 3, + BRIG_GEOMETRY_2DA = 4, + BRIG_GEOMETRY_1DB = 5, + BRIG_GEOMETRY_2DDEPTH = 6, + BRIG_GEOMETRY_2DADEPTH = 7, + + BRIG_GEOMETRY_FIRST_USER_DEFINED = 128 +}; + +typedef uint8_t BrigImageQuery8_t; +enum BrigImageQuery { + BRIG_IMAGE_QUERY_WIDTH = 0, + BRIG_IMAGE_QUERY_HEIGHT = 1, + BRIG_IMAGE_QUERY_DEPTH = 2, + BRIG_IMAGE_QUERY_ARRAY = 3, + BRIG_IMAGE_QUERY_CHANNELORDER = 4, + BRIG_IMAGE_QUERY_CHANNELTYPE = 5, + + BRIG_IMAGE_QUERY_FIRST_USER_DEFINED = 6 +}; + +typedef uint8_t BrigLinkage8_t; +enum BrigLinkage { + BRIG_LINKAGE_NONE = 0, + BRIG_LINKAGE_PROGRAM = 1, + BRIG_LINKAGE_MODULE = 2, + BRIG_LINKAGE_FUNCTION = 3, + BRIG_LINKAGE_ARG = 4 +}; + +typedef uint8_t BrigMachineModel8_t; +enum BrigMachineModel { + BRIG_MACHINE_SMALL = 0, + BRIG_MACHINE_LARGE = 1, +}; + +typedef uint8_t BrigMemoryModifier8_t; +enum BrigMemoryModifierMask { + BRIG_MEMORY_CONST = 1 +}; + +typedef uint8_t BrigMemoryOrder8_t; +enum BrigMemoryOrder { + BRIG_MEMORY_ORDER_NONE = 0, + BRIG_MEMORY_ORDER_RELAXED = 1, + BRIG_MEMORY_ORDER_SC_ACQUIRE = 2, + BRIG_MEMORY_ORDER_SC_RELEASE = 3, + BRIG_MEMORY_ORDER_SC_ACQUIRE_RELEASE = 4, +}; + +typedef uint8_t BrigMemoryScope8_t; +enum BrigMemoryScope { + BRIG_MEMORY_SCOPE_NONE = 0, + BRIG_MEMORY_SCOPE_WORKITEM = 1, + BRIG_MEMORY_SCOPE_WAVEFRONT = 2, + BRIG_MEMORY_SCOPE_WORKGROUP = 3, + BRIG_MEMORY_SCOPE_AGENT = 4, + BRIG_MEMORY_SCOPE_SYSTEM = 5, +}; + +typedef uint16_t BrigOpcode16_t; +enum BrigOpcode { + BRIG_OPCODE_NOP = 0, + BRIG_OPCODE_ABS = 1, + BRIG_OPCODE_ADD = 2, + BRIG_OPCODE_BORROW = 3, + BRIG_OPCODE_CARRY = 4, + BRIG_OPCODE_CEIL = 5, + BRIG_OPCODE_COPYSIGN = 6, + BRIG_OPCODE_DIV = 7, + BRIG_OPCODE_FLOOR = 8, + BRIG_OPCODE_FMA = 9, + BRIG_OPCODE_FRACT = 10, + BRIG_OPCODE_MAD = 11, + BRIG_OPCODE_MAX = 12, + BRIG_OPCODE_MIN = 13, + BRIG_OPCODE_MUL = 14, + BRIG_OPCODE_MULHI = 15, + BRIG_OPCODE_NEG = 16, + BRIG_OPCODE_REM = 17, + BRIG_OPCODE_RINT = 18, + BRIG_OPCODE_SQRT = 19, + BRIG_OPCODE_SUB = 20, + BRIG_OPCODE_TRUNC = 21, + BRIG_OPCODE_MAD24 = 22, + BRIG_OPCODE_MAD24HI = 23, + BRIG_OPCODE_MUL24 = 24, + BRIG_OPCODE_MUL24HI = 25, + BRIG_OPCODE_SHL = 26, + BRIG_OPCODE_SHR = 27, + BRIG_OPCODE_AND = 28, + BRIG_OPCODE_NOT = 29, + BRIG_OPCODE_OR = 30, + BRIG_OPCODE_POPCOUNT = 31, + BRIG_OPCODE_XOR = 32, + BRIG_OPCODE_BITEXTRACT = 33, + BRIG_OPCODE_BITINSERT = 34, + BRIG_OPCODE_BITMASK = 35, + BRIG_OPCODE_BITREV = 36, + BRIG_OPCODE_BITSELECT = 37, + BRIG_OPCODE_FIRSTBIT = 38, + BRIG_OPCODE_LASTBIT = 39, + BRIG_OPCODE_COMBINE = 40, + BRIG_OPCODE_EXPAND = 41, + BRIG_OPCODE_LDA = 42, + BRIG_OPCODE_MOV = 43, + BRIG_OPCODE_SHUFFLE = 44, + BRIG_OPCODE_UNPACKHI = 45, + BRIG_OPCODE_UNPACKLO = 46, + BRIG_OPCODE_PACK = 47, + BRIG_OPCODE_UNPACK = 48, + BRIG_OPCODE_CMOV = 49, + BRIG_OPCODE_CLASS = 50, + BRIG_OPCODE_NCOS = 51, + BRIG_OPCODE_NEXP2 = 52, + BRIG_OPCODE_NFMA = 53, + BRIG_OPCODE_NLOG2 = 54, + BRIG_OPCODE_NRCP = 55, + BRIG_OPCODE_NRSQRT = 56, + BRIG_OPCODE_NSIN = 57, + BRIG_OPCODE_NSQRT = 58, + BRIG_OPCODE_BITALIGN = 59, + BRIG_OPCODE_BYTEALIGN = 60, + BRIG_OPCODE_PACKCVT = 61, + BRIG_OPCODE_UNPACKCVT = 62, + BRIG_OPCODE_LERP = 63, + BRIG_OPCODE_SAD = 64, + BRIG_OPCODE_SADHI = 65, + BRIG_OPCODE_SEGMENTP = 66, + BRIG_OPCODE_FTOS = 67, + BRIG_OPCODE_STOF = 68, + BRIG_OPCODE_CMP = 69, + BRIG_OPCODE_CVT = 70, + BRIG_OPCODE_LD = 71, + BRIG_OPCODE_ST = 72, + BRIG_OPCODE_ATOMIC = 73, + BRIG_OPCODE_ATOMICNORET = 74, + BRIG_OPCODE_SIGNAL = 75, + BRIG_OPCODE_SIGNALNORET = 76, + BRIG_OPCODE_MEMFENCE = 77, + BRIG_OPCODE_RDIMAGE = 78, + BRIG_OPCODE_LDIMAGE = 79, + BRIG_OPCODE_STIMAGE = 80, + BRIG_OPCODE_IMAGEFENCE = 81, + BRIG_OPCODE_QUERYIMAGE = 82, + BRIG_OPCODE_QUERYSAMPLER = 83, + BRIG_OPCODE_CBR = 84, + BRIG_OPCODE_BR = 85, + BRIG_OPCODE_SBR = 86, + BRIG_OPCODE_BARRIER = 87, + BRIG_OPCODE_WAVEBARRIER = 88, + BRIG_OPCODE_ARRIVEFBAR = 89, + BRIG_OPCODE_INITFBAR = 90, + BRIG_OPCODE_JOINFBAR = 91, + BRIG_OPCODE_LEAVEFBAR = 92, + BRIG_OPCODE_RELEASEFBAR = 93, + BRIG_OPCODE_WAITFBAR = 94, + BRIG_OPCODE_LDF = 95, + BRIG_OPCODE_ACTIVELANECOUNT = 96, + BRIG_OPCODE_ACTIVELANEID = 97, + BRIG_OPCODE_ACTIVELANEMASK = 98, + BRIG_OPCODE_ACTIVELANEPERMUTE = 99, + BRIG_OPCODE_CALL = 100, + BRIG_OPCODE_SCALL = 101, + BRIG_OPCODE_ICALL = 102, + BRIG_OPCODE_RET = 103, + BRIG_OPCODE_ALLOCA = 104, + BRIG_OPCODE_CURRENTWORKGROUPSIZE = 105, + BRIG_OPCODE_CURRENTWORKITEMFLATID = 106, + BRIG_OPCODE_DIM = 107, + BRIG_OPCODE_GRIDGROUPS = 108, + BRIG_OPCODE_GRIDSIZE = 109, + BRIG_OPCODE_PACKETCOMPLETIONSIG = 110, + BRIG_OPCODE_PACKETID = 111, + BRIG_OPCODE_WORKGROUPID = 112, + BRIG_OPCODE_WORKGROUPSIZE = 113, + BRIG_OPCODE_WORKITEMABSID = 114, + BRIG_OPCODE_WORKITEMFLATABSID = 115, + BRIG_OPCODE_WORKITEMFLATID = 116, + BRIG_OPCODE_WORKITEMID = 117, + BRIG_OPCODE_CLEARDETECTEXCEPT = 118, + BRIG_OPCODE_GETDETECTEXCEPT = 119, + BRIG_OPCODE_SETDETECTEXCEPT = 120, + BRIG_OPCODE_ADDQUEUEWRITEINDEX = 121, + BRIG_OPCODE_CASQUEUEWRITEINDEX = 122, + BRIG_OPCODE_LDQUEUEREADINDEX = 123, + BRIG_OPCODE_LDQUEUEWRITEINDEX = 124, + BRIG_OPCODE_STQUEUEREADINDEX = 125, + BRIG_OPCODE_STQUEUEWRITEINDEX = 126, + BRIG_OPCODE_CLOCK = 127, + BRIG_OPCODE_CUID = 128, + BRIG_OPCODE_DEBUGTRAP = 129, + BRIG_OPCODE_GROUPBASEPTR = 130, + BRIG_OPCODE_KERNARGBASEPTR = 131, + BRIG_OPCODE_LANEID = 132, + BRIG_OPCODE_MAXCUID = 133, + BRIG_OPCODE_MAXWAVEID = 134, + BRIG_OPCODE_NULLPTR = 135, + BRIG_OPCODE_WAVEID = 136, + + BRIG_OPCODE_FIRST_USER_DEFINED = 32768, +}; + +typedef uint8_t BrigPack8_t; +enum BrigPack { + BRIG_PACK_NONE = 0, + BRIG_PACK_PP = 1, + BRIG_PACK_PS = 2, + BRIG_PACK_SP = 3, + BRIG_PACK_SS = 4, + BRIG_PACK_S = 5, + BRIG_PACK_P = 6, + BRIG_PACK_PPSAT = 7, + BRIG_PACK_PSSAT = 8, + BRIG_PACK_SPSAT = 9, + BRIG_PACK_SSSAT = 10, + BRIG_PACK_SSAT = 11, + BRIG_PACK_PSAT = 12 +}; + +typedef uint8_t BrigProfile8_t; +enum BrigProfile { + BRIG_PROFILE_BASE = 0, + BRIG_PROFILE_FULL = 1, +}; + +typedef uint16_t BrigRegisterKind16_t; +enum BrigRegisterKind { + BRIG_REGISTER_KIND_CONTROL = 0, + BRIG_REGISTER_KIND_SINGLE = 1, + BRIG_REGISTER_KIND_DOUBLE = 2, + BRIG_REGISTER_KIND_QUAD = 3 +}; + +typedef uint8_t BrigRound8_t; +enum BrigRound { + BRIG_ROUND_NONE = 0, + BRIG_ROUND_FLOAT_DEFAULT = 1, + BRIG_ROUND_FLOAT_NEAR_EVEN = 2, + BRIG_ROUND_FLOAT_ZERO = 3, + BRIG_ROUND_FLOAT_PLUS_INFINITY = 4, + BRIG_ROUND_FLOAT_MINUS_INFINITY = 5, + BRIG_ROUND_INTEGER_NEAR_EVEN = 6, + BRIG_ROUND_INTEGER_ZERO = 7, + BRIG_ROUND_INTEGER_PLUS_INFINITY = 8, + BRIG_ROUND_INTEGER_MINUS_INFINITY = 9, + BRIG_ROUND_INTEGER_NEAR_EVEN_SAT = 10, + BRIG_ROUND_INTEGER_ZERO_SAT = 11, + BRIG_ROUND_INTEGER_PLUS_INFINITY_SAT = 12, + BRIG_ROUND_INTEGER_MINUS_INFINITY_SAT = 13, + BRIG_ROUND_INTEGER_SIGNALING_NEAR_EVEN = 14, + BRIG_ROUND_INTEGER_SIGNALING_ZERO = 15, + BRIG_ROUND_INTEGER_SIGNALING_PLUS_INFINITY = 16, + BRIG_ROUND_INTEGER_SIGNALING_MINUS_INFINITY = 17, + BRIG_ROUND_INTEGER_SIGNALING_NEAR_EVEN_SAT = 18, + BRIG_ROUND_INTEGER_SIGNALING_ZERO_SAT = 19, + BRIG_ROUND_INTEGER_SIGNALING_PLUS_INFINITY_SAT = 20, + BRIG_ROUND_INTEGER_SIGNALING_MINUS_INFINITY_SAT = 21 +}; + +typedef uint8_t BrigSamplerAddressing8_t; +enum BrigSamplerAddressing { + BRIG_ADDRESSING_UNDEFINED = 0, + BRIG_ADDRESSING_CLAMP_TO_EDGE = 1, + BRIG_ADDRESSING_CLAMP_TO_BORDER = 2, + BRIG_ADDRESSING_REPEAT = 3, + BRIG_ADDRESSING_MIRRORED_REPEAT = 4, + + BRIG_ADDRESSING_FIRST_USER_DEFINED = 128 +}; + +typedef uint8_t BrigSamplerCoordNormalization8_t; +enum BrigSamplerCoordNormalization { + BRIG_COORD_UNNORMALIZED = 0, + BRIG_COORD_NORMALIZED = 1 +}; + +typedef uint8_t BrigSamplerFilter8_t; +enum BrigSamplerFilter { + BRIG_FILTER_NEAREST = 0, + BRIG_FILTER_LINEAR = 1, + + BRIG_FILTER_FIRST_USER_DEFINED = 128 +}; + +typedef uint8_t BrigSamplerQuery8_t; +enum BrigSamplerQuery { + BRIG_SAMPLER_QUERY_ADDRESSING = 0, + BRIG_SAMPLER_QUERY_COORD = 1, + BRIG_SAMPLER_QUERY_FILTER = 2 +}; + +typedef uint32_t BrigSectionIndex32_t; +enum BrigSectionIndex { + BRIG_SECTION_INDEX_DATA = 0, + BRIG_SECTION_INDEX_CODE = 1, + BRIG_SECTION_INDEX_OPERAND = 2, + + BRIG_SECTION_INDEX_BEGIN_IMPLEMENTATION_DEFINED = 3, +}; + +typedef uint8_t BrigSegCvtModifier8_t; +enum BrigSegCvtModifierMask { + BRIG_SEG_CVT_NONULL = 1 +}; + +typedef uint8_t BrigSegment8_t; +enum BrigSegment { + BRIG_SEGMENT_NONE = 0, + BRIG_SEGMENT_FLAT = 1, + BRIG_SEGMENT_GLOBAL = 2, + BRIG_SEGMENT_READONLY = 3, + BRIG_SEGMENT_KERNARG = 4, + BRIG_SEGMENT_GROUP = 5, + BRIG_SEGMENT_PRIVATE = 6, + BRIG_SEGMENT_SPILL = 7, + BRIG_SEGMENT_ARG = 8, + + BRIG_SEGMENT_FIRST_USER_DEFINED = 128 +}; + +enum { + BRIG_TYPE_BASE_SIZE = 5, + BRIG_TYPE_PACK_SIZE = 2, + BRIG_TYPE_ARRAY_SIZE = 1, + + BRIG_TYPE_BASE_SHIFT = 0, + BRIG_TYPE_PACK_SHIFT = BRIG_TYPE_BASE_SHIFT + BRIG_TYPE_BASE_SIZE, + BRIG_TYPE_ARRAY_SHIFT = BRIG_TYPE_PACK_SHIFT + BRIG_TYPE_PACK_SIZE, + + BRIG_TYPE_BASE_MASK = ((1 << BRIG_TYPE_BASE_SIZE) - 1) << BRIG_TYPE_BASE_SHIFT, + BRIG_TYPE_PACK_MASK = ((1 << BRIG_TYPE_PACK_SIZE) - 1) << BRIG_TYPE_PACK_SHIFT, + BRIG_TYPE_ARRAY_MASK = ((1 << BRIG_TYPE_ARRAY_SIZE) - 1) << BRIG_TYPE_ARRAY_SHIFT, + + BRIG_TYPE_PACK_NONE = 0 << BRIG_TYPE_PACK_SHIFT, + BRIG_TYPE_PACK_32 = 1 << BRIG_TYPE_PACK_SHIFT, + BRIG_TYPE_PACK_64 = 2 << BRIG_TYPE_PACK_SHIFT, + BRIG_TYPE_PACK_128 = 3 << BRIG_TYPE_PACK_SHIFT, + + BRIG_TYPE_ARRAY = 1 << BRIG_TYPE_ARRAY_SHIFT +}; + +typedef uint16_t BrigType16_t; +enum BrigType { + BRIG_TYPE_NONE = 0, + BRIG_TYPE_U8 = 1, + BRIG_TYPE_U16 = 2, + BRIG_TYPE_U32 = 3, + BRIG_TYPE_U64 = 4, + BRIG_TYPE_S8 = 5, + BRIG_TYPE_S16 = 6, + BRIG_TYPE_S32 = 7, + BRIG_TYPE_S64 = 8, + BRIG_TYPE_F16 = 9, + BRIG_TYPE_F32 = 10, + BRIG_TYPE_F64 = 11, + BRIG_TYPE_B1 = 12, + BRIG_TYPE_B8 = 13, + BRIG_TYPE_B16 = 14, + BRIG_TYPE_B32 = 15, + BRIG_TYPE_B64 = 16, + BRIG_TYPE_B128 = 17, + BRIG_TYPE_SAMP = 18, + BRIG_TYPE_ROIMG = 19, + BRIG_TYPE_WOIMG = 20, + BRIG_TYPE_RWIMG = 21, + BRIG_TYPE_SIG32 = 22, + BRIG_TYPE_SIG64 = 23, + + BRIG_TYPE_U8X4 = BRIG_TYPE_U8 | BRIG_TYPE_PACK_32, + BRIG_TYPE_U8X8 = BRIG_TYPE_U8 | BRIG_TYPE_PACK_64, + BRIG_TYPE_U8X16 = BRIG_TYPE_U8 | BRIG_TYPE_PACK_128, + BRIG_TYPE_U16X2 = BRIG_TYPE_U16 | BRIG_TYPE_PACK_32, + BRIG_TYPE_U16X4 = BRIG_TYPE_U16 | BRIG_TYPE_PACK_64, + BRIG_TYPE_U16X8 = BRIG_TYPE_U16 | BRIG_TYPE_PACK_128, + BRIG_TYPE_U32X2 = BRIG_TYPE_U32 | BRIG_TYPE_PACK_64, + BRIG_TYPE_U32X4 = BRIG_TYPE_U32 | BRIG_TYPE_PACK_128, + BRIG_TYPE_U64X2 = BRIG_TYPE_U64 | BRIG_TYPE_PACK_128, + BRIG_TYPE_S8X4 = BRIG_TYPE_S8 | BRIG_TYPE_PACK_32, + BRIG_TYPE_S8X8 = BRIG_TYPE_S8 | BRIG_TYPE_PACK_64, + BRIG_TYPE_S8X16 = BRIG_TYPE_S8 | BRIG_TYPE_PACK_128, + BRIG_TYPE_S16X2 = BRIG_TYPE_S16 | BRIG_TYPE_PACK_32, + BRIG_TYPE_S16X4 = BRIG_TYPE_S16 | BRIG_TYPE_PACK_64, + BRIG_TYPE_S16X8 = BRIG_TYPE_S16 | BRIG_TYPE_PACK_128, + BRIG_TYPE_S32X2 = BRIG_TYPE_S32 | BRIG_TYPE_PACK_64, + BRIG_TYPE_S32X4 = BRIG_TYPE_S32 | BRIG_TYPE_PACK_128, + BRIG_TYPE_S64X2 = BRIG_TYPE_S64 | BRIG_TYPE_PACK_128, + BRIG_TYPE_F16X2 = BRIG_TYPE_F16 | BRIG_TYPE_PACK_32, + BRIG_TYPE_F16X4 = BRIG_TYPE_F16 | BRIG_TYPE_PACK_64, + BRIG_TYPE_F16X8 = BRIG_TYPE_F16 | BRIG_TYPE_PACK_128, + BRIG_TYPE_F32X2 = BRIG_TYPE_F32 | BRIG_TYPE_PACK_64, + BRIG_TYPE_F32X4 = BRIG_TYPE_F32 | BRIG_TYPE_PACK_128, + BRIG_TYPE_F64X2 = BRIG_TYPE_F64 | BRIG_TYPE_PACK_128, + + BRIG_TYPE_U8_ARRAY = BRIG_TYPE_U8 | BRIG_TYPE_ARRAY, + BRIG_TYPE_U16_ARRAY = BRIG_TYPE_U16 | BRIG_TYPE_ARRAY, + BRIG_TYPE_U32_ARRAY = BRIG_TYPE_U32 | BRIG_TYPE_ARRAY, + BRIG_TYPE_U64_ARRAY = BRIG_TYPE_U64 | BRIG_TYPE_ARRAY, + BRIG_TYPE_S8_ARRAY = BRIG_TYPE_S8 | BRIG_TYPE_ARRAY, + BRIG_TYPE_S16_ARRAY = BRIG_TYPE_S16 | BRIG_TYPE_ARRAY, + BRIG_TYPE_S32_ARRAY = BRIG_TYPE_S32 | BRIG_TYPE_ARRAY, + BRIG_TYPE_S64_ARRAY = BRIG_TYPE_S64 | BRIG_TYPE_ARRAY, + BRIG_TYPE_F16_ARRAY = BRIG_TYPE_F16 | BRIG_TYPE_ARRAY, + BRIG_TYPE_F32_ARRAY = BRIG_TYPE_F32 | BRIG_TYPE_ARRAY, + BRIG_TYPE_F64_ARRAY = BRIG_TYPE_F64 | BRIG_TYPE_ARRAY, + BRIG_TYPE_B8_ARRAY = BRIG_TYPE_B8 | BRIG_TYPE_ARRAY, + BRIG_TYPE_B16_ARRAY = BRIG_TYPE_B16 | BRIG_TYPE_ARRAY, + BRIG_TYPE_B32_ARRAY = BRIG_TYPE_B32 | BRIG_TYPE_ARRAY, + BRIG_TYPE_B64_ARRAY = BRIG_TYPE_B64 | BRIG_TYPE_ARRAY, + BRIG_TYPE_B128_ARRAY = BRIG_TYPE_B128 | BRIG_TYPE_ARRAY, + BRIG_TYPE_SAMP_ARRAY = BRIG_TYPE_SAMP | BRIG_TYPE_ARRAY, + BRIG_TYPE_ROIMG_ARRAY = BRIG_TYPE_ROIMG | BRIG_TYPE_ARRAY, + BRIG_TYPE_WOIMG_ARRAY = BRIG_TYPE_WOIMG | BRIG_TYPE_ARRAY, + BRIG_TYPE_RWIMG_ARRAY = BRIG_TYPE_RWIMG | BRIG_TYPE_ARRAY, + BRIG_TYPE_SIG32_ARRAY = BRIG_TYPE_SIG32 | BRIG_TYPE_ARRAY, + BRIG_TYPE_SIG64_ARRAY = BRIG_TYPE_SIG64 | BRIG_TYPE_ARRAY, + BRIG_TYPE_U8X4_ARRAY = BRIG_TYPE_U8X4 | BRIG_TYPE_ARRAY, + BRIG_TYPE_U8X8_ARRAY = BRIG_TYPE_U8X8 | BRIG_TYPE_ARRAY, + BRIG_TYPE_U8X16_ARRAY = BRIG_TYPE_U8X16 | BRIG_TYPE_ARRAY, + BRIG_TYPE_U16X2_ARRAY = BRIG_TYPE_U16X2 | BRIG_TYPE_ARRAY, + BRIG_TYPE_U16X4_ARRAY = BRIG_TYPE_U16X4 | BRIG_TYPE_ARRAY, + BRIG_TYPE_U16X8_ARRAY = BRIG_TYPE_U16X8 | BRIG_TYPE_ARRAY, + BRIG_TYPE_U32X2_ARRAY = BRIG_TYPE_U32X2 | BRIG_TYPE_ARRAY, + BRIG_TYPE_U32X4_ARRAY = BRIG_TYPE_U32X4 | BRIG_TYPE_ARRAY, + BRIG_TYPE_U64X2_ARRAY = BRIG_TYPE_U64X2 | BRIG_TYPE_ARRAY, + BRIG_TYPE_S8X4_ARRAY = BRIG_TYPE_S8X4 | BRIG_TYPE_ARRAY, + BRIG_TYPE_S8X8_ARRAY = BRIG_TYPE_S8X8 | BRIG_TYPE_ARRAY, + BRIG_TYPE_S8X16_ARRAY = BRIG_TYPE_S8X16 | BRIG_TYPE_ARRAY, + BRIG_TYPE_S16X2_ARRAY = BRIG_TYPE_S16X2 | BRIG_TYPE_ARRAY, + BRIG_TYPE_S16X4_ARRAY = BRIG_TYPE_S16X4 | BRIG_TYPE_ARRAY, + BRIG_TYPE_S16X8_ARRAY = BRIG_TYPE_S16X8 | BRIG_TYPE_ARRAY, + BRIG_TYPE_S32X2_ARRAY = BRIG_TYPE_S32X2 | BRIG_TYPE_ARRAY, + BRIG_TYPE_S32X4_ARRAY = BRIG_TYPE_S32X4 | BRIG_TYPE_ARRAY, + BRIG_TYPE_S64X2_ARRAY = BRIG_TYPE_S64X2 | BRIG_TYPE_ARRAY, + BRIG_TYPE_F16X2_ARRAY = BRIG_TYPE_F16X2 | BRIG_TYPE_ARRAY, + BRIG_TYPE_F16X4_ARRAY = BRIG_TYPE_F16X4 | BRIG_TYPE_ARRAY, + BRIG_TYPE_F16X8_ARRAY = BRIG_TYPE_F16X8 | BRIG_TYPE_ARRAY, + BRIG_TYPE_F32X2_ARRAY = BRIG_TYPE_F32X2 | BRIG_TYPE_ARRAY, + BRIG_TYPE_F32X4_ARRAY = BRIG_TYPE_F32X4 | BRIG_TYPE_ARRAY, + BRIG_TYPE_F64X2_ARRAY = BRIG_TYPE_F64X2 | BRIG_TYPE_ARRAY, +}; + +typedef uint8_t BrigVariableModifier8_t; +enum BrigVariableModifierMask { + BRIG_VARIABLE_DEFINITION = 1, + BRIG_VARIABLE_CONST = 2 +}; + +typedef uint8_t BrigWidth8_t; +enum BrigWidth { + BRIG_WIDTH_NONE = 0, + BRIG_WIDTH_1 = 1, + BRIG_WIDTH_2 = 2, + BRIG_WIDTH_4 = 3, + BRIG_WIDTH_8 = 4, + BRIG_WIDTH_16 = 5, + BRIG_WIDTH_32 = 6, + BRIG_WIDTH_64 = 7, + BRIG_WIDTH_128 = 8, + BRIG_WIDTH_256 = 9, + BRIG_WIDTH_512 = 10, + BRIG_WIDTH_1024 = 11, + BRIG_WIDTH_2048 = 12, + BRIG_WIDTH_4096 = 13, + BRIG_WIDTH_8192 = 14, + BRIG_WIDTH_16384 = 15, + BRIG_WIDTH_32768 = 16, + BRIG_WIDTH_65536 = 17, + BRIG_WIDTH_131072 = 18, + BRIG_WIDTH_262144 = 19, + BRIG_WIDTH_524288 = 20, + BRIG_WIDTH_1048576 = 21, + BRIG_WIDTH_2097152 = 22, + BRIG_WIDTH_4194304 = 23, + BRIG_WIDTH_8388608 = 24, + BRIG_WIDTH_16777216 = 25, + BRIG_WIDTH_33554432 = 26, + BRIG_WIDTH_67108864 = 27, + BRIG_WIDTH_134217728 = 28, + BRIG_WIDTH_268435456 = 29, + BRIG_WIDTH_536870912 = 30, + BRIG_WIDTH_1073741824 = 31, + BRIG_WIDTH_2147483648 = 32, + BRIG_WIDTH_WAVESIZE = 33, + BRIG_WIDTH_ALL = 34, +}; + +struct BrigUInt64 { + uint32_t lo; + uint32_t hi; +}; + +struct BrigBase { + uint16_t byteCount; + BrigKind16_t kind; +}; + +struct BrigData { + uint32_t byteCount; + uint8_t bytes[1]; +}; + +struct BrigDirectiveArgBlock { + BrigBase base; +}; + +struct BrigDirectiveComment { + BrigBase base; + BrigDataOffsetString32_t name; +}; + +struct BrigDirectiveControl { + BrigBase base; + BrigControlDirective16_t control; + uint16_t reserved; + BrigDataOffsetOperandList32_t operands; +}; + +struct BrigDirectiveExecutable { + BrigBase base; + BrigDataOffsetString32_t name; + uint16_t outArgCount; + uint16_t inArgCount; + BrigCodeOffset32_t firstInArg; + BrigCodeOffset32_t firstCodeBlockEntry; + BrigCodeOffset32_t nextModuleEntry; + BrigExecutableModifier8_t modifier; + BrigLinkage8_t linkage; + uint16_t reserved; +}; + +struct BrigDirectiveExtension { + BrigBase base; + BrigDataOffsetString32_t name; +}; + +struct BrigDirectiveFbarrier { + BrigBase base; + BrigDataOffsetString32_t name; + BrigVariableModifier8_t modifier; + BrigLinkage8_t linkage; + uint16_t reserved; +}; + +struct BrigDirectiveLabel { + BrigBase base; + BrigDataOffsetString32_t name; +}; + +struct BrigDirectiveLoc { + BrigBase base; + BrigDataOffsetString32_t filename; + uint32_t line; + uint32_t column; +}; + +struct BrigDirectiveNone { + BrigBase base; +}; + +struct BrigDirectivePragma { + BrigBase base; + BrigDataOffsetOperandList32_t operands; +}; + +struct BrigDirectiveVariable { + BrigBase base; + BrigDataOffsetString32_t name; + BrigOperandOffset32_t init; + BrigType16_t type; + BrigSegment8_t segment; + BrigAlignment8_t align; + BrigUInt64 dim; + BrigVariableModifier8_t modifier; + BrigLinkage8_t linkage; + BrigAllocation8_t allocation; + uint8_t reserved; +}; + +struct BrigDirectiveModule { + BrigBase base; + BrigDataOffsetString32_t name; + BrigVersion32_t hsailMajor; + BrigVersion32_t hsailMinor; + BrigProfile8_t profile; + BrigMachineModel8_t machineModel; + BrigRound8_t defaultFloatRound; + uint8_t reserved; +}; + +struct BrigInstBase { + BrigBase base; + BrigOpcode16_t opcode; + BrigType16_t type; + BrigDataOffsetOperandList32_t operands; +}; + +struct BrigInstAddr { + BrigInstBase base; + BrigSegment8_t segment; + uint8_t reserved[3]; +}; + +struct BrigInstAtomic { + BrigInstBase base; + BrigSegment8_t segment; + BrigMemoryOrder8_t memoryOrder; + BrigMemoryScope8_t memoryScope; + BrigAtomicOperation8_t atomicOperation; + uint8_t equivClass; + uint8_t reserved[3]; +}; + +struct BrigInstBasic { + BrigInstBase base; +}; + +struct BrigInstBr { + BrigInstBase base; + BrigWidth8_t width; + uint8_t reserved[3]; +}; + +struct BrigInstCmp { + BrigInstBase base; + BrigType16_t sourceType; + BrigAluModifier8_t modifier; + BrigCompareOperation8_t compare; + BrigPack8_t pack; + uint8_t reserved[3]; +}; + +struct BrigInstCvt { + BrigInstBase base; + BrigType16_t sourceType; + BrigAluModifier8_t modifier; + BrigRound8_t round; +}; + +struct BrigInstImage { + BrigInstBase base; + BrigType16_t imageType; + BrigType16_t coordType; + BrigImageGeometry8_t geometry; + uint8_t equivClass; + uint16_t reserved; +}; + +struct BrigInstLane { + BrigInstBase base; + BrigType16_t sourceType; + BrigWidth8_t width; + uint8_t reserved; +}; + +struct BrigInstMem { + BrigInstBase base; + BrigSegment8_t segment; + BrigAlignment8_t align; + uint8_t equivClass; + BrigWidth8_t width; + BrigMemoryModifier8_t modifier; + uint8_t reserved[3]; +}; + +struct BrigInstMemFence { + BrigInstBase base; + BrigMemoryOrder8_t memoryOrder; + BrigMemoryScope8_t globalSegmentMemoryScope; + BrigMemoryScope8_t groupSegmentMemoryScope; + BrigMemoryScope8_t imageSegmentMemoryScope; +}; + +struct BrigInstMod { + BrigInstBase base; + BrigAluModifier8_t modifier; + BrigRound8_t round; + BrigPack8_t pack; + uint8_t reserved; +}; + +struct BrigInstQueryImage { + BrigInstBase base; + BrigType16_t imageType; + BrigImageGeometry8_t geometry; + BrigImageQuery8_t query; +}; + +struct BrigInstQuerySampler { + BrigInstBase base; + BrigSamplerQuery8_t query; + uint8_t reserved[3]; +}; + +struct BrigInstQueue { + BrigInstBase base; + BrigSegment8_t segment; + BrigMemoryOrder8_t memoryOrder; + uint16_t reserved; +}; + +struct BrigInstSeg { + BrigInstBase base; + BrigSegment8_t segment; + uint8_t reserved[3]; +}; + +struct BrigInstSegCvt { + BrigInstBase base; + BrigType16_t sourceType; + BrigSegment8_t segment; + BrigSegCvtModifier8_t modifier; +}; + +struct BrigInstSignal { + BrigInstBase base; + BrigType16_t signalType; + BrigMemoryOrder8_t memoryOrder; + BrigAtomicOperation8_t signalOperation; +}; + +struct BrigInstSourceType { + BrigInstBase base; + BrigType16_t sourceType; + uint16_t reserved; +}; + +struct BrigOperandAddress { + BrigBase base; + BrigCodeOffset32_t symbol; + BrigOperandOffset32_t reg; + BrigUInt64 offset; +}; + +struct BrigOperandAlign { + BrigBase base; + BrigAlignment8_t align; + uint8_t reserved[3]; +}; + +struct BrigOperandCodeList { + BrigBase base; + BrigDataOffsetCodeList32_t elements; +}; + +struct BrigOperandCodeRef { + BrigBase base; + BrigCodeOffset32_t ref; +}; + +struct BrigOperandConstantBytes { + BrigBase base; + BrigType16_t type; + uint16_t reserved; + BrigDataOffsetString32_t bytes; +}; + +struct BrigOperandConstantOperandList { + BrigBase base; + BrigType16_t type; + uint16_t reserved; + BrigDataOffsetOperandList32_t elements; +}; + +struct BrigOperandConstantImage { + BrigBase base; + BrigType16_t type; + BrigImageGeometry8_t geometry; + BrigImageChannelOrder8_t channelOrder; + BrigImageChannelType8_t channelType; + uint8_t reserved[3]; + BrigUInt64 width; + BrigUInt64 height; + BrigUInt64 depth; + BrigUInt64 array; +}; + +struct BrigOperandOperandList { + BrigBase base; + BrigDataOffsetOperandList32_t elements; +}; + +struct BrigOperandRegister { + BrigBase base; + BrigRegisterKind16_t regKind; + uint16_t regNum; +}; + +struct BrigOperandConstantSampler { + BrigBase base; + BrigType16_t type; + BrigSamplerCoordNormalization8_t coord; + BrigSamplerFilter8_t filter; + BrigSamplerAddressing8_t addressing; + uint8_t reserved[3]; +}; + +struct BrigOperandString { + BrigBase base; + BrigDataOffsetString32_t string; +}; + +struct BrigOperandWavesize { + BrigBase base; +}; + +typedef uint32_t BrigExceptions32_t; +enum BrigExceptionsMask { + BRIG_EXCEPTIONS_INVALID_OPERATION = 1 << 0, + BRIG_EXCEPTIONS_DIVIDE_BY_ZERO = 1 << 1, + BRIG_EXCEPTIONS_OVERFLOW = 1 << 2, + BRIG_EXCEPTIONS_UNDERFLOW = 1 << 3, + BRIG_EXCEPTIONS_INEXACT = 1 << 4, + + BRIG_EXCEPTIONS_FIRST_USER_DEFINED = 1 << 16 +}; + +struct BrigSectionHeader { + uint64_t byteCount; + uint32_t headerByteCount; + uint32_t nameLength; + uint8_t name[1]; +}; + +struct BrigModuleHeader { + char identification[8]; + BrigVersion32_t brigMajor; + BrigVersion32_t brigMinor; + uint64_t byteCount; + uint8_t hash[64]; + uint32_t reserved; + uint32_t sectionCount; + uint64_t sectionIndex; +}; + +typedef BrigModuleHeader* BrigModule_t; + +#ifdef __cplusplus +} +#endif /*__cplusplus*/ + +#endif // defined(INCLUDED_BRIG_H) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/amd_hsa_common.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/amd_hsa_common.h new file mode 100644 index 0000000000000000000000000000000000000000..7c4ed3eea47298374b78d1f770aeb0ed8aba9936 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/amd_hsa_common.h @@ -0,0 +1,91 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// The University of Illinois/NCSA +// Open Source License (NCSA) +// +// Copyright (c) 2014-2020, Advanced Micro Devices, Inc. All rights reserved. +// +// Developed by: +// +// AMD Research and AMD HSA Software Development +// +// Advanced Micro Devices, Inc. +// +// www.amd.com +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal with 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: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimers in +// the documentation and/or other materials provided with the distribution. +// - Neither the names of Advanced Micro Devices, Inc, +// nor the names of its contributors may be used to endorse or promote +// products derived from this Software without specific prior written +// permission. +// +// 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 CONTRIBUTORS 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 WITH THE SOFTWARE. +// +//////////////////////////////////////////////////////////////////////////////// + +// The following set of header files provides definitions for AMD GPU +// Architecture: +// - amd_hsa_common.h +// - amd_hsa_elf.h +// - amd_hsa_kernel_code.h +// - amd_hsa_queue.h +// - amd_hsa_signal.h +// +// Refer to "HSA Application Binary Interface: AMD GPU Architecture" for more +// information. + +#ifndef AMD_HSA_COMMON_H +#define AMD_HSA_COMMON_H + +#include +#include + +// Descriptive version of the HSA Application Binary Interface. +#define AMD_HSA_ABI_VERSION "AMD GPU Architecture v0.35 (June 25, 2015)" + +// Alignment attribute that specifies a minimum alignment (in bytes) for +// variables of the specified type. +#if defined(__GNUC__) +# define __ALIGNED__(x) __attribute__((aligned(x))) +#elif defined(_MSC_VER) +# define __ALIGNED__(x) __declspec(align(x)) +#elif defined(RC_INVOKED) +# define __ALIGNED__(x) +#else +# error +#endif + +// Creates enumeration entries for packed types. Enumeration entries include +// bit shift amount, bit width, and bit mask. +#define AMD_HSA_BITS_CREATE_ENUM_ENTRIES(name, shift, width) \ + name##_SHIFT = (shift), \ + name##_WIDTH = (width), \ + name = (((1 << (width)) - 1) << (shift)) \ + +// Gets bits for specified mask from specified src packed instance. +#define AMD_HSA_BITS_GET(src, mask) \ + ((src & mask) >> mask ## _SHIFT) \ + +// Sets val bits for specified mask in specified dst packed instance. +#define AMD_HSA_BITS_SET(dst, mask, val) \ + dst &= (~(1 << mask##_SHIFT) & ~mask); \ + dst |= (((val) << mask##_SHIFT) & mask) \ + +#endif // AMD_HSA_COMMON_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/amd_hsa_elf.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/amd_hsa_elf.h new file mode 100644 index 0000000000000000000000000000000000000000..65a77f041bf3bc9c93321d0e40a59b4139243c54 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/amd_hsa_elf.h @@ -0,0 +1,462 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// The University of Illinois/NCSA +// Open Source License (NCSA) +// +// Copyright (c) 2014-2020, Advanced Micro Devices, Inc. All rights reserved. +// +// Developed by: +// +// AMD Research and AMD HSA Software Development +// +// Advanced Micro Devices, Inc. +// +// www.amd.com +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal with 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: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimers in +// the documentation and/or other materials provided with the distribution. +// - Neither the names of Advanced Micro Devices, Inc, +// nor the names of its contributors may be used to endorse or promote +// products derived from this Software without specific prior written +// permission. +// +// 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 CONTRIBUTORS 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 WITH THE SOFTWARE. +// +//////////////////////////////////////////////////////////////////////////////// + +// Undefine the macro in case it is defined in the system elf.h. +#undef EM_AMDGPU + +#ifndef AMD_HSA_ELF_H +#define AMD_HSA_ELF_H + +// AMD GPU Specific ELF Header Enumeration Values. +// +// Values are copied from LLVM BinaryFormat/ELF.h . This file also contains +// code object V1 defintions which are not part of the LLVM header. Code object +// V1 was only supported by the Finalizer which is now deprecated and removed. +// +// TODO: Deprecate and remove V1 support and replace this header with using the +// LLVM header. +namespace ELF { + +// Machine architectures +// See current registered ELF machine architectures at: +// http://www.uxsglobal.com/developers/gabi/latest/ch4.eheader.html +enum { + EM_AMDGPU = 224, // AMD GPU architecture +}; + +// OS ABI identification. +enum { + ELFOSABI_AMDGPU_HSA = 64, // AMD HSA runtime +}; + +// AMDGPU OS ABI Version identification. +enum { + // ELFABIVERSION_AMDGPU_HSA_V1 does not exist because OS ABI identification + // was never defined for V1. + ELFABIVERSION_AMDGPU_HSA_V2 = 0, + ELFABIVERSION_AMDGPU_HSA_V3 = 1, + ELFABIVERSION_AMDGPU_HSA_V4 = 2, + ELFABIVERSION_AMDGPU_HSA_V5 = 3, + ELFABIVERSION_AMDGPU_HSA_V6 = 4, +}; + +// AMDGPU specific e_flags. +enum : unsigned { + // Processor selection mask for EF_AMDGPU_MACH_* values. + EF_AMDGPU_MACH = 0x0ff, + + // Not specified processor. + EF_AMDGPU_MACH_NONE = 0x000, + + // AMDGCN-based processors. + // clang-format off + EF_AMDGPU_MACH_AMDGCN_GFX600 = 0x020, + EF_AMDGPU_MACH_AMDGCN_GFX601 = 0x021, + EF_AMDGPU_MACH_AMDGCN_GFX700 = 0x022, + EF_AMDGPU_MACH_AMDGCN_GFX701 = 0x023, + EF_AMDGPU_MACH_AMDGCN_GFX702 = 0x024, + EF_AMDGPU_MACH_AMDGCN_GFX703 = 0x025, + EF_AMDGPU_MACH_AMDGCN_GFX704 = 0x026, + EF_AMDGPU_MACH_AMDGCN_RESERVED_0X27 = 0x027, + EF_AMDGPU_MACH_AMDGCN_GFX801 = 0x028, + EF_AMDGPU_MACH_AMDGCN_GFX802 = 0x029, + EF_AMDGPU_MACH_AMDGCN_GFX803 = 0x02a, + EF_AMDGPU_MACH_AMDGCN_GFX810 = 0x02b, + EF_AMDGPU_MACH_AMDGCN_GFX900 = 0x02c, + EF_AMDGPU_MACH_AMDGCN_GFX902 = 0x02d, + EF_AMDGPU_MACH_AMDGCN_GFX904 = 0x02e, + EF_AMDGPU_MACH_AMDGCN_GFX906 = 0x02f, + EF_AMDGPU_MACH_AMDGCN_GFX908 = 0x030, + EF_AMDGPU_MACH_AMDGCN_GFX909 = 0x031, + EF_AMDGPU_MACH_AMDGCN_GFX90C = 0x032, + EF_AMDGPU_MACH_AMDGCN_GFX1010 = 0x033, + EF_AMDGPU_MACH_AMDGCN_GFX1011 = 0x034, + EF_AMDGPU_MACH_AMDGCN_GFX1012 = 0x035, + EF_AMDGPU_MACH_AMDGCN_GFX1030 = 0x036, + EF_AMDGPU_MACH_AMDGCN_GFX1031 = 0x037, + EF_AMDGPU_MACH_AMDGCN_GFX1032 = 0x038, + EF_AMDGPU_MACH_AMDGCN_GFX1033 = 0x039, + EF_AMDGPU_MACH_AMDGCN_GFX602 = 0x03a, + EF_AMDGPU_MACH_AMDGCN_GFX705 = 0x03b, + EF_AMDGPU_MACH_AMDGCN_GFX805 = 0x03c, + EF_AMDGPU_MACH_AMDGCN_GFX1035 = 0x03d, + EF_AMDGPU_MACH_AMDGCN_GFX1034 = 0x03e, + EF_AMDGPU_MACH_AMDGCN_GFX90A = 0x03f, + EF_AMDGPU_MACH_AMDGCN_GFX940 = 0x040, + EF_AMDGPU_MACH_AMDGCN_GFX1100 = 0x041, + EF_AMDGPU_MACH_AMDGCN_GFX1013 = 0x042, + EF_AMDGPU_MACH_AMDGCN_GFX1150 = 0x043, + EF_AMDGPU_MACH_AMDGCN_GFX1103 = 0x044, + EF_AMDGPU_MACH_AMDGCN_GFX1036 = 0x045, + EF_AMDGPU_MACH_AMDGCN_GFX1101 = 0x046, + EF_AMDGPU_MACH_AMDGCN_GFX1102 = 0x047, + EF_AMDGPU_MACH_AMDGCN_GFX1200 = 0x048, + EF_AMDGPU_MACH_AMDGCN_RESERVED_0X49 = 0x049, + EF_AMDGPU_MACH_AMDGCN_GFX1151 = 0x04a, + EF_AMDGPU_MACH_AMDGCN_GFX941 = 0x04b, + EF_AMDGPU_MACH_AMDGCN_GFX942 = 0x04c, + EF_AMDGPU_MACH_AMDGCN_RESERVED_0X4D = 0x04d, + EF_AMDGPU_MACH_AMDGCN_GFX1201 = 0x04e, + EF_AMDGPU_MACH_AMDGCN_GFX950 = 0x04f, + EF_AMDGPU_MACH_AMDGCN_RESERVED_0X50 = 0x050, + EF_AMDGPU_MACH_AMDGCN_GFX9_GENERIC = 0x051, + EF_AMDGPU_MACH_AMDGCN_GFX10_1_GENERIC = 0x052, + EF_AMDGPU_MACH_AMDGCN_GFX10_3_GENERIC = 0x053, + EF_AMDGPU_MACH_AMDGCN_GFX11_GENERIC = 0x054, + EF_AMDGPU_MACH_AMDGCN_RESERVED_0X55 = 0x055, + // clang-format on + + // First/last AMDGCN-based processors. + EF_AMDGPU_MACH_AMDGCN_FIRST = EF_AMDGPU_MACH_AMDGCN_GFX600, + EF_AMDGPU_MACH_AMDGCN_LAST = EF_AMDGPU_MACH_AMDGCN_GFX11_GENERIC, + + // Indicates if the "xnack" target feature is enabled for all code contained + // in the object. + // + // Only valid for ELFOSABI_AMDGPU_HSA and ELFABIVERSION_AMDGPU_HSA_V2. + EF_AMDGPU_FEATURE_XNACK_V2 = 0x01, + // Indicates if the trap handler is enabled for all code contained + // in the object. + // + // Only valid for ELFOSABI_AMDGPU_HSA and ELFABIVERSION_AMDGPU_HSA_V2. + EF_AMDGPU_FEATURE_TRAP_HANDLER_V2 = 0x02, + + // Indicates if the "xnack" target feature is enabled for all code contained + // in the object. + // + // Only valid for ELFOSABI_AMDGPU_HSA and ELFABIVERSION_AMDGPU_HSA_V3. + EF_AMDGPU_FEATURE_XNACK_V3 = 0x100, + // Indicates if the "sramecc" target feature is enabled for all code + // contained in the object. + // + // Only valid for ELFOSABI_AMDGPU_HSA and ELFABIVERSION_AMDGPU_HSA_V3. + EF_AMDGPU_FEATURE_SRAMECC_V3 = 0x200, + + // XNACK selection mask for EF_AMDGPU_FEATURE_XNACK_* values. + // + // Only valid for ELFOSABI_AMDGPU_HSA and ELFABIVERSION_AMDGPU_HSA_V4. + EF_AMDGPU_FEATURE_XNACK_V4 = 0x300, + // XNACK is not supported. + EF_AMDGPU_FEATURE_XNACK_UNSUPPORTED_V4 = 0x000, + // XNACK is any/default/unspecified. + EF_AMDGPU_FEATURE_XNACK_ANY_V4 = 0x100, + // XNACK is off. + EF_AMDGPU_FEATURE_XNACK_OFF_V4 = 0x200, + // XNACK is on. + EF_AMDGPU_FEATURE_XNACK_ON_V4 = 0x300, + + // SRAMECC selection mask for EF_AMDGPU_FEATURE_SRAMECC_* values. + // + // Only valid for ELFOSABI_AMDGPU_HSA and ELFABIVERSION_AMDGPU_HSA_V4. + EF_AMDGPU_FEATURE_SRAMECC_V4 = 0xc00, + // SRAMECC is not supported. + EF_AMDGPU_FEATURE_SRAMECC_UNSUPPORTED_V4 = 0x000, + // SRAMECC is any/default/unspecified. + EF_AMDGPU_FEATURE_SRAMECC_ANY_V4 = 0x400, + // SRAMECC is off. + EF_AMDGPU_FEATURE_SRAMECC_OFF_V4 = 0x800, + // SRAMECC is on. + EF_AMDGPU_FEATURE_SRAMECC_ON_V4 = 0xc00, + + // Generic target versioning. This is contained in the list byte of EFLAGS. + EF_AMDGPU_GENERIC_VERSION = 0xff000000, + EF_AMDGPU_GENERIC_VERSION_OFFSET = 24, + EF_AMDGPU_GENERIC_VERSION_MIN = 1, + EF_AMDGPU_GENERIC_VERSION_MAX = 0xff, +}; + +// ELF Relocation types for AMDGPU. +enum : unsigned { + R_AMDGPU_ABS32_LO = 1, + R_AMDGPU_ABS32_HI = 2, + R_AMDGPU_ABS64 = 3, + R_AMDGPU_ABS32 = 6, + R_AMDGPU_RELATIVE64 = 13, +}; + +} // end namespace ELF + +// ELF Section Header Flag Enumeration Values. +#define SHF_AMDGPU_HSA_GLOBAL (0x00100000 & SHF_MASKOS) +#define SHF_AMDGPU_HSA_READONLY (0x00200000 & SHF_MASKOS) +#define SHF_AMDGPU_HSA_CODE (0x00400000 & SHF_MASKOS) +#define SHF_AMDGPU_HSA_AGENT (0x00800000 & SHF_MASKOS) + +// +typedef enum { + AMDGPU_HSA_SEGMENT_GLOBAL_PROGRAM = 0, + AMDGPU_HSA_SEGMENT_GLOBAL_AGENT = 1, + AMDGPU_HSA_SEGMENT_READONLY_AGENT = 2, + AMDGPU_HSA_SEGMENT_CODE_AGENT = 3, + AMDGPU_HSA_SEGMENT_LAST, +} amdgpu_hsa_elf_segment_t; + +// ELF Program Header Type Enumeration Values. +#define PT_AMDGPU_HSA_LOAD_GLOBAL_PROGRAM (PT_LOOS + AMDGPU_HSA_SEGMENT_GLOBAL_PROGRAM) +#define PT_AMDGPU_HSA_LOAD_GLOBAL_AGENT (PT_LOOS + AMDGPU_HSA_SEGMENT_GLOBAL_AGENT) +#define PT_AMDGPU_HSA_LOAD_READONLY_AGENT (PT_LOOS + AMDGPU_HSA_SEGMENT_READONLY_AGENT) +#define PT_AMDGPU_HSA_LOAD_CODE_AGENT (PT_LOOS + AMDGPU_HSA_SEGMENT_CODE_AGENT) + +// ELF Symbol Type Enumeration Values. +#define STT_AMDGPU_HSA_KERNEL (STT_LOOS + 0) +#define STT_AMDGPU_HSA_INDIRECT_FUNCTION (STT_LOOS + 1) +#define STT_AMDGPU_HSA_METADATA (STT_LOOS + 2) + +// ELF Symbol Binding Enumeration Values. +#define STB_AMDGPU_HSA_EXTERNAL (STB_LOOS + 0) + +// ELF Symbol Other Information Creation/Retrieval. +#define ELF64_ST_AMDGPU_ALLOCATION(o) (((o) >> 2) & 0x3) +#define ELF64_ST_AMDGPU_FLAGS(o) ((o) >> 4) +#define ELF64_ST_AMDGPU_OTHER(f, a, v) (((f) << 4) + (((a) & 0x3) << 2) + ((v) & 0x3)) + +typedef enum { + AMDGPU_HSA_SYMBOL_ALLOCATION_DEFAULT = 0, + AMDGPU_HSA_SYMBOL_ALLOCATION_GLOBAL_PROGRAM = 1, + AMDGPU_HSA_SYMBOL_ALLOCATION_GLOBAL_AGENT = 2, + AMDGPU_HSA_SYMBOL_ALLOCATION_READONLY_AGENT = 3, + AMDGPU_HSA_SYMBOL_ALLOCATION_LAST, +} amdgpu_hsa_symbol_allocation_t; + +// ELF Symbol Allocation Enumeration Values. +#define STA_AMDGPU_HSA_DEFAULT AMDGPU_HSA_SYMBOL_ALLOCATION_DEFAULT +#define STA_AMDGPU_HSA_GLOBAL_PROGRAM AMDGPU_HSA_SYMBOL_ALLOCATION_GLOBAL_PROGRAM +#define STA_AMDGPU_HSA_GLOBAL_AGENT AMDGPU_HSA_SYMBOL_ALLOCATION_GLOBAL_AGENT +#define STA_AMDGPU_HSA_READONLY_AGENT AMDGPU_HSA_SYMBOL_ALLOCATION_READONLY_AGENT + +typedef enum { + AMDGPU_HSA_SYMBOL_FLAG_DEFAULT = 0, + AMDGPU_HSA_SYMBOL_FLAG_CONST = 1, + AMDGPU_HSA_SYMBOL_FLAG_LAST, +} amdgpu_hsa_symbol_flag_t; + +// ELF Symbol Flag Enumeration Values. +#define STF_AMDGPU_HSA_CONST AMDGPU_HSA_SYMBOL_FLAG_CONST + +// Legacy/V1 AMD GPU Relocation Type Enumeration Values. +#define R_AMDGPU_V1_NONE 0 +#define R_AMDGPU_V1_32_LOW 1 +#define R_AMDGPU_V1_32_HIGH 2 +#define R_AMDGPU_V1_64 3 +#define R_AMDGPU_V1_INIT_SAMPLER 4 +#define R_AMDGPU_V1_INIT_IMAGE 5 +#define R_AMDGPU_V1_RELATIVE64 13 + +// AMD GPU Note Type Enumeration Values. +#define NT_AMD_HSA_CODE_OBJECT_VERSION 1 +#define NT_AMD_HSA_HSAIL 2 +#define NT_AMD_HSA_ISA_VERSION 3 +#define NT_AMD_HSA_PRODUCER 4 +#define NT_AMD_HSA_PRODUCER_OPTIONS 5 +#define NT_AMD_HSA_EXTENSION 6 +#define NT_AMD_HSA_ISA_NAME 11 +/* AMDGPU snapshots of runtime, agent and queues state for use in core dump */ +#define NT_AMDGPU_CORE_STATE 33 +#define NT_AMD_HSA_HLDEBUG_DEBUG 101 +#define NT_AMD_HSA_HLDEBUG_TARGET 102 + +// AMD GPU Metadata Kind Enumeration Values. +typedef uint16_t amdgpu_hsa_metadata_kind16_t; +typedef enum { + AMDGPU_HSA_METADATA_KIND_NONE = 0, + AMDGPU_HSA_METADATA_KIND_INIT_SAMP = 1, + AMDGPU_HSA_METADATA_KIND_INIT_ROIMG = 2, + AMDGPU_HSA_METADATA_KIND_INIT_WOIMG = 3, + AMDGPU_HSA_METADATA_KIND_INIT_RWIMG = 4 +} amdgpu_hsa_metadata_kind_t; + +// AMD GPU Sampler Coordinate Normalization Enumeration Values. +typedef uint8_t amdgpu_hsa_sampler_coord8_t; +typedef enum { + AMDGPU_HSA_SAMPLER_COORD_UNNORMALIZED = 0, + AMDGPU_HSA_SAMPLER_COORD_NORMALIZED = 1 +} amdgpu_hsa_sampler_coord_t; + +// AMD GPU Sampler Filter Enumeration Values. +typedef uint8_t amdgpu_hsa_sampler_filter8_t; +typedef enum { + AMDGPU_HSA_SAMPLER_FILTER_NEAREST = 0, + AMDGPU_HSA_SAMPLER_FILTER_LINEAR = 1 +} amdgpu_hsa_sampler_filter_t; + +// AMD GPU Sampler Addressing Enumeration Values. +typedef uint8_t amdgpu_hsa_sampler_addressing8_t; +typedef enum { + AMDGPU_HSA_SAMPLER_ADDRESSING_UNDEFINED = 0, + AMDGPU_HSA_SAMPLER_ADDRESSING_CLAMP_TO_EDGE = 1, + AMDGPU_HSA_SAMPLER_ADDRESSING_CLAMP_TO_BORDER = 2, + AMDGPU_HSA_SAMPLER_ADDRESSING_REPEAT = 3, + AMDGPU_HSA_SAMPLER_ADDRESSING_MIRRORED_REPEAT = 4 +} amdgpu_hsa_sampler_addressing_t; + +// AMD GPU Sampler Descriptor. +typedef struct amdgpu_hsa_sampler_descriptor_s { + uint16_t size; + amdgpu_hsa_metadata_kind16_t kind; + amdgpu_hsa_sampler_coord8_t coord; + amdgpu_hsa_sampler_filter8_t filter; + amdgpu_hsa_sampler_addressing8_t addressing; + uint8_t reserved1; +} amdgpu_hsa_sampler_descriptor_t; + +// AMD GPU Image Geometry Enumeration Values. +typedef uint8_t amdgpu_hsa_image_geometry8_t; +typedef enum { + AMDGPU_HSA_IMAGE_GEOMETRY_1D = 0, + AMDGPU_HSA_IMAGE_GEOMETRY_2D = 1, + AMDGPU_HSA_IMAGE_GEOMETRY_3D = 2, + AMDGPU_HSA_IMAGE_GEOMETRY_1DA = 3, + AMDGPU_HSA_IMAGE_GEOMETRY_2DA = 4, + AMDGPU_HSA_IMAGE_GEOMETRY_1DB = 5, + AMDGPU_HSA_IMAGE_GEOMETRY_2DDEPTH = 6, + AMDGPU_HSA_IMAGE_GEOMETRY_2DADEPTH = 7 +} amdgpu_hsa_image_geometry_t; + +// AMD GPU Image Channel Order Enumeration Values. +typedef uint8_t amdgpu_hsa_image_channel_order8_t; +typedef enum { + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_A = 0, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_R = 1, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_RX = 2, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_RG = 3, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_RGX = 4, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_RA = 5, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_RGB = 6, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_RGBX = 7, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_RGBA = 8, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_BGRA = 9, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_ARGB = 10, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_ABGR = 11, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_SRGB = 12, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_SRGBX = 13, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_SRGBA = 14, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_SBGRA = 15, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_INTENSITY = 16, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_LUMINANCE = 17, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_DEPTH = 18, + AMDGPU_HSA_IMAGE_CHANNEL_ORDER_DEPTH_STENCIL = 19 +} amdgpu_hsa_image_channel_order_t; + +// AMD GPU Image Channel Type Enumeration Values. +typedef uint8_t amdgpu_hsa_image_channel_type8_t; +typedef enum { + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_SNORM_INT8 = 0, + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_SNORM_INT16 = 1, + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_UNORM_INT8 = 2, + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_UNORM_INT16 = 3, + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_UNORM_INT24 = 4, + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_SHORT_555 = 5, + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_SHORT_565 = 6, + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_INT_101010 = 7, + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_SIGNED_INT8 = 8, + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_SIGNED_INT16 = 9, + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_SIGNED_INT32 = 10, + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_UNSIGNED_INT8 = 11, + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_UNSIGNED_INT16 = 12, + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_UNSIGNED_INT32 = 13, + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_HALF_FLOAT = 14, + AMDGPU_HSA_IMAGE_CHANNEL_TYPE_FLOAT = 15 +} amdgpu_hsa_image_channel_type_t; + +// AMD GPU Image Descriptor. +typedef struct amdgpu_hsa_image_descriptor_s { + uint16_t size; + amdgpu_hsa_metadata_kind16_t kind; + amdgpu_hsa_image_geometry8_t geometry; + amdgpu_hsa_image_channel_order8_t channel_order; + amdgpu_hsa_image_channel_type8_t channel_type; + uint8_t reserved1; + uint64_t width; + uint64_t height; + uint64_t depth; + uint64_t array; +} amdgpu_hsa_image_descriptor_t; + +typedef struct amdgpu_hsa_note_code_object_version_s { + uint32_t major_version; + uint32_t minor_version; +} amdgpu_hsa_note_code_object_version_t; + +typedef struct amdgpu_hsa_note_hsail_s { + uint32_t hsail_major_version; + uint32_t hsail_minor_version; + uint8_t profile; + uint8_t machine_model; + uint8_t default_float_round; +} amdgpu_hsa_note_hsail_t; + +typedef struct amdgpu_hsa_note_isa_s { + uint16_t vendor_name_size; + uint16_t architecture_name_size; + uint32_t major; + uint32_t minor; + uint32_t stepping; + char vendor_and_architecture_name[1]; +} amdgpu_hsa_note_isa_t; + +typedef struct amdgpu_hsa_note_producer_s { + uint16_t producer_name_size; + uint16_t reserved; + uint32_t producer_major_version; + uint32_t producer_minor_version; + char producer_name[1]; +} amdgpu_hsa_note_producer_t; + +typedef struct amdgpu_hsa_note_producer_options_s { + uint16_t producer_options_size; + char producer_options[1]; +} amdgpu_hsa_note_producer_options_t; + +typedef enum { + AMDGPU_HSA_RODATA_GLOBAL_PROGRAM = 0, + AMDGPU_HSA_RODATA_GLOBAL_AGENT, + AMDGPU_HSA_RODATA_READONLY_AGENT, + AMDGPU_HSA_DATA_GLOBAL_PROGRAM, + AMDGPU_HSA_DATA_GLOBAL_AGENT, + AMDGPU_HSA_DATA_READONLY_AGENT, + AMDGPU_HSA_BSS_GLOBAL_PROGRAM, + AMDGPU_HSA_BSS_GLOBAL_AGENT, + AMDGPU_HSA_BSS_READONLY_AGENT, + AMDGPU_HSA_SECTION_LAST, +} amdgpu_hsa_elf_section_t; + +#endif // AMD_HSA_ELF_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/amd_hsa_kernel_code.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/amd_hsa_kernel_code.h new file mode 100644 index 0000000000000000000000000000000000000000..901e49c8dd1d9d5624fb95ada6d695cf9b64e17d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/amd_hsa_kernel_code.h @@ -0,0 +1,269 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// The University of Illinois/NCSA +// Open Source License (NCSA) +// +// Copyright (c) 2014-2020, Advanced Micro Devices, Inc. All rights reserved. +// +// Developed by: +// +// AMD Research and AMD HSA Software Development +// +// Advanced Micro Devices, Inc. +// +// www.amd.com +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal with 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: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimers in +// the documentation and/or other materials provided with the distribution. +// - Neither the names of Advanced Micro Devices, Inc, +// nor the names of its contributors may be used to endorse or promote +// products derived from this Software without specific prior written +// permission. +// +// 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 CONTRIBUTORS 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 WITH THE SOFTWARE. +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef AMD_HSA_KERNEL_CODE_H +#define AMD_HSA_KERNEL_CODE_H + +#include "amd_hsa_common.h" +#include "hsa.h" + +// AMD Kernel Code Version Enumeration Values. +typedef uint32_t amd_kernel_code_version32_t; +enum amd_kernel_code_version_t { + AMD_KERNEL_CODE_VERSION_MAJOR = 1, + AMD_KERNEL_CODE_VERSION_MINOR = 1 +}; + +// AMD Machine Kind Enumeration Values. +typedef uint16_t amd_machine_kind16_t; +enum amd_machine_kind_t { + AMD_MACHINE_KIND_UNDEFINED = 0, + AMD_MACHINE_KIND_AMDGPU = 1 +}; + +// AMD Machine Version. +typedef uint16_t amd_machine_version16_t; + +// AMD Float Round Mode Enumeration Values. +enum amd_float_round_mode_t { + AMD_FLOAT_ROUND_MODE_NEAREST_EVEN = 0, + AMD_FLOAT_ROUND_MODE_PLUS_INFINITY = 1, + AMD_FLOAT_ROUND_MODE_MINUS_INFINITY = 2, + AMD_FLOAT_ROUND_MODE_ZERO = 3 +}; + +// AMD Float Denorm Mode Enumeration Values. +enum amd_float_denorm_mode_t { + AMD_FLOAT_DENORM_MODE_FLUSH_SOURCE_OUTPUT = 0, + AMD_FLOAT_DENORM_MODE_FLUSH_OUTPUT = 1, + AMD_FLOAT_DENORM_MODE_FLUSH_SOURCE = 2, + AMD_FLOAT_DENORM_MODE_NO_FLUSH = 3 +}; + +// AMD Compute Program Resource Register One. +typedef uint32_t amd_compute_pgm_rsrc_one32_t; +enum amd_compute_pgm_rsrc_one_t { + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_GRANULATED_WORKITEM_VGPR_COUNT, 0, 6), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_GRANULATED_WAVEFRONT_SGPR_COUNT, 6, 4), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_PRIORITY, 10, 2), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_FLOAT_ROUND_MODE_32, 12, 2), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_FLOAT_ROUND_MODE_16_64, 14, 2), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_FLOAT_DENORM_MODE_32, 16, 2), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_FLOAT_DENORM_MODE_16_64, 18, 2), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_PRIV, 20, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_ENABLE_DX10_CLAMP, 21, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_DEBUG_MODE, 22, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_ENABLE_IEEE_MODE, 23, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_BULKY, 24, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_CDBG_USER, 25, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_ONE_RESERVED1, 26, 6) +}; + +// AMD System VGPR Workitem ID Enumeration Values. +enum amd_system_vgpr_workitem_id_t { + AMD_SYSTEM_VGPR_WORKITEM_ID_X = 0, + AMD_SYSTEM_VGPR_WORKITEM_ID_X_Y = 1, + AMD_SYSTEM_VGPR_WORKITEM_ID_X_Y_Z = 2, + AMD_SYSTEM_VGPR_WORKITEM_ID_UNDEFINED = 3 +}; + +// AMD Compute Program Resource Register Two. +typedef uint32_t amd_compute_pgm_rsrc_two32_t; +enum amd_compute_pgm_rsrc_two_t { + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_SGPR_PRIVATE_SEGMENT_WAVE_BYTE_OFFSET, 0, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_USER_SGPR_COUNT, 1, 5), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_TRAP_HANDLER, 6, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_SGPR_WORKGROUP_ID_X, 7, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_SGPR_WORKGROUP_ID_Y, 8, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_SGPR_WORKGROUP_ID_Z, 9, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_SGPR_WORKGROUP_INFO, 10, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_VGPR_WORKITEM_ID, 11, 2), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_ADDRESS_WATCH, 13, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_MEMORY_VIOLATION, 14, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_GRANULATED_LDS_SIZE, 15, 9), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_IEEE_754_FP_INVALID_OPERATION, 24, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_FP_DENORMAL_SOURCE, 25, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_IEEE_754_FP_DIVISION_BY_ZERO, 26, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_IEEE_754_FP_OVERFLOW, 27, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_IEEE_754_FP_UNDERFLOW, 28, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_IEEE_754_FP_INEXACT, 29, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_EXCEPTION_INT_DIVISION_BY_ZERO, 30, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_COMPUTE_PGM_RSRC_TWO_RESERVED1, 31, 1) +}; + +// AMD Element Byte Size Enumeration Values. +enum amd_element_byte_size_t { + AMD_ELEMENT_BYTE_SIZE_2 = 0, + AMD_ELEMENT_BYTE_SIZE_4 = 1, + AMD_ELEMENT_BYTE_SIZE_8 = 2, + AMD_ELEMENT_BYTE_SIZE_16 = 3 +}; + +// AMD Kernel Code Properties. +typedef uint32_t amd_kernel_code_properties32_t; +enum amd_kernel_code_properties_t { + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER, 0, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_DISPATCH_PTR, 1, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_QUEUE_PTR, 2, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_KERNARG_SEGMENT_PTR, 3, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_DISPATCH_ID, 4, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_FLAT_SCRATCH_INIT, 5, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_PRIVATE_SEGMENT_SIZE, 6, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_GRID_WORKGROUP_COUNT_X, 7, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Y, 8, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Z, 9, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_RESERVED1, 10, 6), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_ENABLE_ORDERED_APPEND_GDS, 16, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_PRIVATE_ELEMENT_SIZE, 17, 2), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_IS_PTR64, 19, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_IS_DYNAMIC_CALLSTACK, 20, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_IS_DEBUG_ENABLED, 21, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_IS_XNACK_ENABLED, 22, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_KERNEL_CODE_PROPERTIES_RESERVED2, 23, 9) +}; + +// AMD Power Of Two Enumeration Values. +typedef uint8_t amd_powertwo8_t; +enum amd_powertwo_t { + AMD_POWERTWO_1 = 0, + AMD_POWERTWO_2 = 1, + AMD_POWERTWO_4 = 2, + AMD_POWERTWO_8 = 3, + AMD_POWERTWO_16 = 4, + AMD_POWERTWO_32 = 5, + AMD_POWERTWO_64 = 6, + AMD_POWERTWO_128 = 7, + AMD_POWERTWO_256 = 8 +}; + +// AMD Enabled Control Directive Enumeration Values. +typedef uint64_t amd_enabled_control_directive64_t; +enum amd_enabled_control_directive_t { + AMD_ENABLED_CONTROL_DIRECTIVE_ENABLE_BREAK_EXCEPTIONS = 1, + AMD_ENABLED_CONTROL_DIRECTIVE_ENABLE_DETECT_EXCEPTIONS = 2, + AMD_ENABLED_CONTROL_DIRECTIVE_MAX_DYNAMIC_GROUP_SIZE = 4, + AMD_ENABLED_CONTROL_DIRECTIVE_MAX_FLAT_GRID_SIZE = 8, + AMD_ENABLED_CONTROL_DIRECTIVE_MAX_FLAT_WORKGROUP_SIZE = 16, + AMD_ENABLED_CONTROL_DIRECTIVE_REQUIRED_DIM = 32, + AMD_ENABLED_CONTROL_DIRECTIVE_REQUIRED_GRID_SIZE = 64, + AMD_ENABLED_CONTROL_DIRECTIVE_REQUIRED_WORKGROUP_SIZE = 128, + AMD_ENABLED_CONTROL_DIRECTIVE_REQUIRE_NO_PARTIAL_WORKGROUPS = 256 +}; + +// AMD Exception Kind Enumeration Values. +typedef uint16_t amd_exception_kind16_t; +enum amd_exception_kind_t { + AMD_EXCEPTION_KIND_INVALID_OPERATION = 1, + AMD_EXCEPTION_KIND_DIVISION_BY_ZERO = 2, + AMD_EXCEPTION_KIND_OVERFLOW = 4, + AMD_EXCEPTION_KIND_UNDERFLOW = 8, + AMD_EXCEPTION_KIND_INEXACT = 16 +}; + +// AMD Control Directives. +#define AMD_CONTROL_DIRECTIVES_ALIGN_BYTES 64 +#define AMD_CONTROL_DIRECTIVES_ALIGN __ALIGNED__(AMD_CONTROL_DIRECTIVES_ALIGN_BYTES) +typedef AMD_CONTROL_DIRECTIVES_ALIGN struct amd_control_directives_s { + amd_enabled_control_directive64_t enabled_control_directives; + uint16_t enable_break_exceptions; + uint16_t enable_detect_exceptions; + uint32_t max_dynamic_group_size; + uint64_t max_flat_grid_size; + uint32_t max_flat_workgroup_size; + uint8_t required_dim; + uint8_t reserved1[3]; + uint64_t required_grid_size[3]; + uint32_t required_workgroup_size[3]; + uint8_t reserved2[60]; +} amd_control_directives_t; + +// AMD Kernel Code. +#define AMD_ISA_ALIGN_BYTES 256 +#define AMD_KERNEL_CODE_ALIGN_BYTES 64 +#define AMD_KERNEL_CODE_ALIGN __ALIGNED__(AMD_KERNEL_CODE_ALIGN_BYTES) +typedef AMD_KERNEL_CODE_ALIGN struct amd_kernel_code_s { + amd_kernel_code_version32_t amd_kernel_code_version_major; + amd_kernel_code_version32_t amd_kernel_code_version_minor; + amd_machine_kind16_t amd_machine_kind; + amd_machine_version16_t amd_machine_version_major; + amd_machine_version16_t amd_machine_version_minor; + amd_machine_version16_t amd_machine_version_stepping; + int64_t kernel_code_entry_byte_offset; + int64_t kernel_code_prefetch_byte_offset; + uint64_t kernel_code_prefetch_byte_size; + uint64_t max_scratch_backing_memory_byte_size; + amd_compute_pgm_rsrc_one32_t compute_pgm_rsrc1; + amd_compute_pgm_rsrc_two32_t compute_pgm_rsrc2; + amd_kernel_code_properties32_t kernel_code_properties; + uint32_t workitem_private_segment_byte_size; + uint32_t workgroup_group_segment_byte_size; + uint32_t gds_segment_byte_size; + uint64_t kernarg_segment_byte_size; + uint32_t workgroup_fbarrier_count; + uint16_t wavefront_sgpr_count; + uint16_t workitem_vgpr_count; + uint16_t reserved_vgpr_first; + uint16_t reserved_vgpr_count; + uint16_t reserved_sgpr_first; + uint16_t reserved_sgpr_count; + uint16_t debug_wavefront_private_segment_offset_sgpr; + uint16_t debug_private_segment_buffer_sgpr; + amd_powertwo8_t kernarg_segment_alignment; + amd_powertwo8_t group_segment_alignment; + amd_powertwo8_t private_segment_alignment; + amd_powertwo8_t wavefront_size; + int32_t call_convention; + uint8_t reserved1[12]; + uint64_t runtime_loader_kernel_symbol; + amd_control_directives_t control_directives; +} amd_kernel_code_t; + +// TODO: this struct should be completely gone once debugger designs/implements +// Debugger APIs. +typedef struct amd_runtime_loader_debug_info_s { + const void* elf_raw; + size_t elf_size; + const char *kernel_name; + const void *owning_segment; +} amd_runtime_loader_debug_info_t; + +#endif // AMD_HSA_KERNEL_CODE_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/amd_hsa_queue.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/amd_hsa_queue.h new file mode 100644 index 0000000000000000000000000000000000000000..98c6c31423fb76ca5f1335e3723aafeef6871f37 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/amd_hsa_queue.h @@ -0,0 +1,109 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// The University of Illinois/NCSA +// Open Source License (NCSA) +// +// Copyright (c) 2014-2020, Advanced Micro Devices, Inc. All rights reserved. +// +// Developed by: +// +// AMD Research and AMD HSA Software Development +// +// Advanced Micro Devices, Inc. +// +// www.amd.com +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal with 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: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimers in +// the documentation and/or other materials provided with the distribution. +// - Neither the names of Advanced Micro Devices, Inc, +// nor the names of its contributors may be used to endorse or promote +// products derived from this Software without specific prior written +// permission. +// +// 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 CONTRIBUTORS 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 WITH THE SOFTWARE. +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef AMD_HSA_QUEUE_H +#define AMD_HSA_QUEUE_H + +#include "amd_hsa_common.h" +#include "hsa.h" + +// AMD Queue Properties. +typedef uint32_t amd_queue_properties32_t; +enum amd_queue_properties_t { + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_QUEUE_PROPERTIES_ENABLE_TRAP_HANDLER, 0, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_QUEUE_PROPERTIES_IS_PTR64, 1, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_QUEUE_PROPERTIES_ENABLE_TRAP_HANDLER_DEBUG_SGPRS, 2, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_QUEUE_PROPERTIES_ENABLE_PROFILING, 3, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_QUEUE_PROPERTIES_USE_SCRATCH_ONCE, 4, 1), + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_QUEUE_PROPERTIES_RESERVED1, 5, 27) +}; + +// AMD Queue. +#define AMD_QUEUE_ALIGN_BYTES 64 +#define AMD_QUEUE_ALIGN __ALIGNED__(AMD_QUEUE_ALIGN_BYTES) + +// AMD Queue Capabilities. +typedef uint32_t amd_queue_capabilities32_t; +enum amd_queue_capabilities_t { + /* Whether this CP queue supports dual-scratch and async-reclaim */ + AMD_HSA_BITS_CREATE_ENUM_ENTRIES(AMD_QUEUE_CAPS_ASYNC_RECLAIM, 0, 1), +}; + +// Members tagged with "async-reclaim" are ignored by CP FW's that do not support +// AMD_QUEUE_CAPS_ASYNC_RECLAIM. CP FW's that support async-reclaim also support +// dual-scratch (alternate scratch). + +typedef struct AMD_QUEUE_ALIGN amd_queue_s { + hsa_queue_t hsa_queue; + uint32_t caps; + uint32_t reserved1[3]; + volatile uint64_t write_dispatch_id; + uint32_t group_segment_aperture_base_hi; + uint32_t private_segment_aperture_base_hi; + uint32_t max_cu_id; + uint32_t max_wave_id; + volatile uint64_t max_legacy_doorbell_dispatch_id_plus_1; + volatile uint32_t legacy_doorbell_lock; + uint32_t reserved2[9]; + volatile uint64_t read_dispatch_id; + uint32_t read_dispatch_id_field_base_byte_offset; + uint32_t compute_tmpring_size; + uint32_t scratch_resource_descriptor[4]; + uint64_t scratch_backing_memory_location; + uint64_t scratch_backing_memory_byte_size; + uint32_t scratch_wave64_lane_byte_size; + amd_queue_properties32_t queue_properties; + volatile uint64_t scratch_last_used_index; /* async-reclaim */ + hsa_signal_t queue_inactive_signal; + uint32_t reserved4[2]; + volatile uint64_t alt_scratch_last_used_index; /* async-reclaim */ + uint64_t alt_scratch_backing_memory_location; /* async-reclaim */ + uint64_t alt_scratch_backing_memory_byte_size; /* async-reclaim */ + uint32_t alt_scratch_dispatch_limit_x; /* async-reclaim */ + uint32_t alt_scratch_dispatch_limit_y; /* async-reclaim */ + uint32_t alt_scratch_dispatch_limit_z; /* async-reclaim */ + uint32_t alt_scratch_wave64_lane_byte_size; /* async-reclaim */ + uint32_t alt_compute_tmpring_size; /* async-reclaim */ + uint32_t reserved5; +} amd_queue_t; + +#endif // AMD_HSA_QUEUE_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/amd_hsa_signal.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/amd_hsa_signal.h new file mode 100644 index 0000000000000000000000000000000000000000..f9d721f73dd6178b0296abf91f1820502b218b4b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/amd_hsa_signal.h @@ -0,0 +1,80 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// The University of Illinois/NCSA +// Open Source License (NCSA) +// +// Copyright (c) 2014-2020, Advanced Micro Devices, Inc. All rights reserved. +// +// Developed by: +// +// AMD Research and AMD HSA Software Development +// +// Advanced Micro Devices, Inc. +// +// www.amd.com +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal with 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: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimers in +// the documentation and/or other materials provided with the distribution. +// - Neither the names of Advanced Micro Devices, Inc, +// nor the names of its contributors may be used to endorse or promote +// products derived from this Software without specific prior written +// permission. +// +// 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 CONTRIBUTORS 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 WITH THE SOFTWARE. +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef AMD_HSA_SIGNAL_H +#define AMD_HSA_SIGNAL_H + +#include "amd_hsa_common.h" +#include "amd_hsa_queue.h" + +// AMD Signal Kind Enumeration Values. +typedef int64_t amd_signal_kind64_t; +enum amd_signal_kind_t { + AMD_SIGNAL_KIND_INVALID = 0, + AMD_SIGNAL_KIND_USER = 1, + AMD_SIGNAL_KIND_DOORBELL = -1, + AMD_SIGNAL_KIND_LEGACY_DOORBELL = -2 +}; + +// AMD Signal. +#define AMD_SIGNAL_ALIGN_BYTES 64 +#define AMD_SIGNAL_ALIGN __ALIGNED__(AMD_SIGNAL_ALIGN_BYTES) +typedef struct AMD_SIGNAL_ALIGN amd_signal_s { + amd_signal_kind64_t kind; + union { + volatile int64_t value; + volatile uint32_t* legacy_hardware_doorbell_ptr; + volatile uint64_t* hardware_doorbell_ptr; + }; + uint64_t event_mailbox_ptr; + uint32_t event_id; + uint32_t reserved1; + uint64_t start_ts; + uint64_t end_ts; + union { + amd_queue_t* queue_ptr; + uint64_t reserved2; + }; + uint32_t reserved3[2]; +} amd_signal_t; + +#endif // AMD_HSA_SIGNAL_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa.h new file mode 100644 index 0000000000000000000000000000000000000000..e1d999187e9040211f6addb7b0a5bde60285e2c6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa.h @@ -0,0 +1,5738 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// The University of Illinois/NCSA +// Open Source License (NCSA) +// +// Copyright (c) 2014-2020, Advanced Micro Devices, Inc. All rights reserved. +// +// Developed by: +// +// AMD Research and AMD HSA Software Development +// +// Advanced Micro Devices, Inc. +// +// www.amd.com +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal with 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: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimers in +// the documentation and/or other materials provided with the distribution. +// - Neither the names of Advanced Micro Devices, Inc, +// nor the names of its contributors may be used to endorse or promote +// products derived from this Software without specific prior written +// permission. +// +// 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 CONTRIBUTORS 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 WITH THE SOFTWARE. +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef HSA_RUNTIME_INC_HSA_H_ +#define HSA_RUNTIME_INC_HSA_H_ + +#include /* size_t */ +#include /* uintXX_t */ + +#ifndef __cplusplus +#include /* bool */ +#endif /* __cplusplus */ + +// Placeholder for calling convention and import/export macros +#ifndef HSA_CALL +#define HSA_CALL +#endif + +#ifndef HSA_EXPORT_DECORATOR +#ifdef __GNUC__ +#define HSA_EXPORT_DECORATOR __attribute__ ((visibility ("default"))) +#else +#define HSA_EXPORT_DECORATOR +#endif +#endif +#define HSA_API_EXPORT HSA_EXPORT_DECORATOR HSA_CALL +#define HSA_API_IMPORT HSA_CALL + +#if !defined(HSA_API) && defined(HSA_EXPORT) +#define HSA_API HSA_API_EXPORT +#else +#define HSA_API HSA_API_IMPORT +#endif + +// Detect and set large model builds. +#undef HSA_LARGE_MODEL +#if defined(__LP64__) || defined(_M_X64) +#define HSA_LARGE_MODEL +#endif + +// Try to detect CPU endianness +#if !defined(LITTLEENDIAN_CPU) && !defined(BIGENDIAN_CPU) +#if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) +#define LITTLEENDIAN_CPU +#elif defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) +#define BIGENDIAN_CPU +#elif defined(__i386__) || defined(__x86_64__) || defined(_M_IX86) || \ + defined(_M_X64) || defined(__loongarch64) || defined(__riscv) +#define LITTLEENDIAN_CPU +#endif +#endif + +#undef HSA_LITTLE_ENDIAN +#if defined(LITTLEENDIAN_CPU) +#define HSA_LITTLE_ENDIAN +#elif defined(BIGENDIAN_CPU) +#else +#error "BIGENDIAN_CPU or LITTLEENDIAN_CPU must be defined" +#endif + +#ifndef HSA_DEPRECATED +#define HSA_DEPRECATED +//#ifdef __GNUC__ +//#define HSA_DEPRECATED __attribute__((deprecated)) +//#else +//#define HSA_DEPRECATED __declspec(deprecated) +//#endif +#endif + +#define HSA_VERSION_1_0 1 + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** \defgroup status Runtime Notifications + * @{ + */ + +/** + * @brief Status codes. + */ +typedef enum { + /** + * The function has been executed successfully. + */ + HSA_STATUS_SUCCESS = 0x0, + /** + * A traversal over a list of elements has been interrupted by the + * application before completing. + */ + HSA_STATUS_INFO_BREAK = 0x1, + /** + * A generic error has occurred. + */ + HSA_STATUS_ERROR = 0x1000, + /** + * One of the actual arguments does not meet a precondition stated in the + * documentation of the corresponding formal argument. + */ + HSA_STATUS_ERROR_INVALID_ARGUMENT = 0x1001, + /** + * The requested queue creation is not valid. + */ + HSA_STATUS_ERROR_INVALID_QUEUE_CREATION = 0x1002, + /** + * The requested allocation is not valid. + */ + HSA_STATUS_ERROR_INVALID_ALLOCATION = 0x1003, + /** + * The agent is invalid. + */ + HSA_STATUS_ERROR_INVALID_AGENT = 0x1004, + /** + * The memory region is invalid. + */ + HSA_STATUS_ERROR_INVALID_REGION = 0x1005, + /** + * The signal is invalid. + */ + HSA_STATUS_ERROR_INVALID_SIGNAL = 0x1006, + /** + * The queue is invalid. + */ + HSA_STATUS_ERROR_INVALID_QUEUE = 0x1007, + /** + * The HSA runtime failed to allocate the necessary resources. This error + * may also occur when the HSA runtime needs to spawn threads or create + * internal OS-specific events. + */ + HSA_STATUS_ERROR_OUT_OF_RESOURCES = 0x1008, + /** + * The AQL packet is malformed. + */ + HSA_STATUS_ERROR_INVALID_PACKET_FORMAT = 0x1009, + /** + * An error has been detected while releasing a resource. + */ + HSA_STATUS_ERROR_RESOURCE_FREE = 0x100A, + /** + * An API other than ::hsa_init has been invoked while the reference count + * of the HSA runtime is 0. + */ + HSA_STATUS_ERROR_NOT_INITIALIZED = 0x100B, + /** + * The maximum reference count for the object has been reached. + */ + HSA_STATUS_ERROR_REFCOUNT_OVERFLOW = 0x100C, + /** + * The arguments passed to a functions are not compatible. + */ + HSA_STATUS_ERROR_INCOMPATIBLE_ARGUMENTS = 0x100D, + /** + * The index is invalid. + */ + HSA_STATUS_ERROR_INVALID_INDEX = 0x100E, + /** + * The instruction set architecture is invalid. + */ + HSA_STATUS_ERROR_INVALID_ISA = 0x100F, + /** + * The instruction set architecture name is invalid. + */ + HSA_STATUS_ERROR_INVALID_ISA_NAME = 0x1017, + /** + * The code object is invalid. + */ + HSA_STATUS_ERROR_INVALID_CODE_OBJECT = 0x1010, + /** + * The executable is invalid. + */ + HSA_STATUS_ERROR_INVALID_EXECUTABLE = 0x1011, + /** + * The executable is frozen. + */ + HSA_STATUS_ERROR_FROZEN_EXECUTABLE = 0x1012, + /** + * There is no symbol with the given name. + */ + HSA_STATUS_ERROR_INVALID_SYMBOL_NAME = 0x1013, + /** + * The variable is already defined. + */ + HSA_STATUS_ERROR_VARIABLE_ALREADY_DEFINED = 0x1014, + /** + * The variable is undefined. + */ + HSA_STATUS_ERROR_VARIABLE_UNDEFINED = 0x1015, + /** + * An HSAIL operation resulted in a hardware exception. + */ + HSA_STATUS_ERROR_EXCEPTION = 0x1016, + /** + * The code object symbol is invalid. + */ + HSA_STATUS_ERROR_INVALID_CODE_SYMBOL = 0x1018, + /** + * The executable symbol is invalid. + */ + HSA_STATUS_ERROR_INVALID_EXECUTABLE_SYMBOL = 0x1019, + /** + * The file descriptor is invalid. + */ + HSA_STATUS_ERROR_INVALID_FILE = 0x1020, + /** + * The code object reader is invalid. + */ + HSA_STATUS_ERROR_INVALID_CODE_OBJECT_READER = 0x1021, + /** + * The cache is invalid. + */ + HSA_STATUS_ERROR_INVALID_CACHE = 0x1022, + /** + * The wavefront is invalid. + */ + HSA_STATUS_ERROR_INVALID_WAVEFRONT = 0x1023, + /** + * The signal group is invalid. + */ + HSA_STATUS_ERROR_INVALID_SIGNAL_GROUP = 0x1024, + /** + * The HSA runtime is not in the configuration state. + */ + HSA_STATUS_ERROR_INVALID_RUNTIME_STATE = 0x1025, + /** + * The queue received an error that may require process termination. + */ + HSA_STATUS_ERROR_FATAL = 0x1026 +} hsa_status_t; + +/** + * @brief Query additional information about a status code. + * + * @param[in] status Status code. + * + * @param[out] status_string A NUL-terminated string that describes the error + * status. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p status is an invalid + * status code, or @p status_string is NULL. + */ +hsa_status_t HSA_API hsa_status_string( + hsa_status_t status, + const char ** status_string); + +/** @} */ + +/** \defgroup common Common Definitions + * @{ + */ + +/** + * @brief Three-dimensional coordinate. + */ +typedef struct hsa_dim3_s { + /** + * X dimension. + */ + uint32_t x; + + /** + * Y dimension. + */ + uint32_t y; + + /** + * Z dimension. + */ + uint32_t z; +} hsa_dim3_t; + +/** + * @brief Access permissions. + */ +typedef enum { + /** + * Used to remove existing access + */ + HSA_ACCESS_PERMISSION_NONE = 0, + /** + * Read-only access. + */ + HSA_ACCESS_PERMISSION_RO = 1, + /** + * Write-only access. + */ + HSA_ACCESS_PERMISSION_WO = 2, + /** + * Read and write access. + */ + HSA_ACCESS_PERMISSION_RW = 3 +} hsa_access_permission_t; + +/** + * @brief POSIX file descriptor. + */ +typedef int hsa_file_t; + +/** @} **/ + + +/** \defgroup initshutdown Initialization and Shut Down + * @{ + */ + +/** + * @brief Initialize the HSA runtime. + * + * @details Initializes the HSA runtime if it is not already initialized, and + * increases the reference counter associated with the HSA runtime for the + * current process. Invocation of any HSA function other than ::hsa_init results + * in undefined behavior if the current HSA runtime reference counter is less + * than one. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to allocate + * the required resources. + * + * @retval ::HSA_STATUS_ERROR_REFCOUNT_OVERFLOW The HSA runtime reference + * count reaches INT32_MAX. + */ +hsa_status_t HSA_API hsa_init(); + +/** + * @brief Shut down the HSA runtime. + * + * @details Decreases the reference count of the HSA runtime instance. When the + * reference count reaches 0, the HSA runtime is no longer considered valid + * but the application might call ::hsa_init to initialize the HSA runtime + * again. + * + * Once the reference count of the HSA runtime reaches 0, all the resources + * associated with it (queues, signals, agent information, etc.) are + * considered invalid and any attempt to reference them in subsequent API calls + * results in undefined behavior. When the reference count reaches 0, the HSA + * runtime may release resources associated with it. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + */ +hsa_status_t HSA_API hsa_shut_down(); + +/** @} **/ + +/** \defgroup agentinfo System and Agent Information + * @{ + */ + +/** + * @brief Endianness. A convention used to interpret the bytes making up a data + * word. + */ +typedef enum { + /** + * The least significant byte is stored in the smallest address. + */ + HSA_ENDIANNESS_LITTLE = 0, + /** + * The most significant byte is stored in the smallest address. + */ + HSA_ENDIANNESS_BIG = 1 +} hsa_endianness_t; + +/** + * @brief Machine model. A machine model determines the size of certain data + * types in HSA runtime and an agent. + */ +typedef enum { + /** + * Small machine model. Addresses use 32 bits. + */ + HSA_MACHINE_MODEL_SMALL = 0, + /** + * Large machine model. Addresses use 64 bits. + */ + HSA_MACHINE_MODEL_LARGE = 1 +} hsa_machine_model_t; + +/** + * @brief Profile. A profile indicates a particular level of feature + * support. For example, in the base profile the application must use the HSA + * runtime allocator to reserve shared virtual memory, while in the full profile + * any host pointer can be shared across all the agents. + */ +typedef enum { + /** + * Base profile. + */ + HSA_PROFILE_BASE = 0, + /** + * Full profile. + */ + HSA_PROFILE_FULL = 1 +} hsa_profile_t; + +/** + * @brief System attributes. + */ +typedef enum { + /** + * Major version of the HSA runtime specification supported by the + * implementation. The type of this attribute is uint16_t. + */ + HSA_SYSTEM_INFO_VERSION_MAJOR = 0, + /** + * Minor version of the HSA runtime specification supported by the + * implementation. The type of this attribute is uint16_t. + */ + HSA_SYSTEM_INFO_VERSION_MINOR = 1, + /** + * Current timestamp. The value of this attribute monotonically increases at a + * constant rate. The type of this attribute is uint64_t. + */ + HSA_SYSTEM_INFO_TIMESTAMP = 2, + /** + * Timestamp value increase rate, in Hz. The timestamp (clock) frequency is + * in the range 1-400MHz. The type of this attribute is uint64_t. + */ + HSA_SYSTEM_INFO_TIMESTAMP_FREQUENCY = 3, + /** + * Maximum duration of a signal wait operation. Expressed as a count based on + * the timestamp frequency. The type of this attribute is uint64_t. + */ + HSA_SYSTEM_INFO_SIGNAL_MAX_WAIT = 4, + /** + * Endianness of the system. The type of this attribute is ::hsa_endianness_t. + */ + HSA_SYSTEM_INFO_ENDIANNESS = 5, + /** + * Machine model supported by the HSA runtime. The type of this attribute is + * ::hsa_machine_model_t. + */ + HSA_SYSTEM_INFO_MACHINE_MODEL = 6, + /** + * Bit-mask indicating which extensions are supported by the + * implementation. An extension with an ID of @p i is supported if the bit at + * position @p i is set. The type of this attribute is uint8_t[128]. + */ + HSA_SYSTEM_INFO_EXTENSIONS = 7, + /** + * String containing the ROCr build identifier. + */ + HSA_AMD_SYSTEM_INFO_BUILD_VERSION = 0x200, + /** + * Returns true if hsa_amd_svm_* APIs are supported by the driver. The type of + * this attribute is bool. + */ + HSA_AMD_SYSTEM_INFO_SVM_SUPPORTED = 0x201, + // TODO: Should this be per Agent? + /** + * Returns true if all Agents have access to system allocated memory (such as + * that allocated by mmap, malloc, or new) by default. + * If false then system allocated memory may only be made SVM accessible to + * an Agent by declaration of accessibility with hsa_amd_svm_set_attributes. + * The type of this attribute is bool. + */ + HSA_AMD_SYSTEM_INFO_SVM_ACCESSIBLE_BY_DEFAULT = 0x202, + /** + * Returns true if mwaitx is enabled on this system + * The type of this attribute is bool. + */ + HSA_AMD_SYSTEM_INFO_MWAITX_ENABLED = 0x203, + /** + * Returns true if DMABUF APIs are supported by the driver. The type of + * this attribute is bool. + */ + HSA_AMD_SYSTEM_INFO_DMABUF_SUPPORTED = 0x204, + /** + * Returns true if Virtual Memory APIs are supported by the driver. The type of + * this attribute is bool. + */ + HSA_AMD_SYSTEM_INFO_VIRTUAL_MEM_API_SUPPORTED = 0x205, + /** + * Returns true if XNACK is enabled on this system. The type of + * this attribute is bool. + */ + HSA_AMD_SYSTEM_INFO_XNACK_ENABLED = 0x206, + /** + * Major version of the HSA runtime extension specification supported by the + * implementation. The type of this attribute is uint16_t. + */ + HSA_AMD_SYSTEM_INFO_EXT_VERSION_MAJOR = 0x207, + /** + * Minor version of the HSA runtime extension specification supported by the + * implementation. The type of this attribute is uint16_t. + */ + HSA_AMD_SYSTEM_INFO_EXT_VERSION_MINOR = 0x208, +} hsa_system_info_t; + +/** + * @brief Get the current value of a system attribute. + * + * @param[in] attribute Attribute to query. + * + * @param[out] value Pointer to an application-allocated buffer where to store + * the value of the attribute. If the buffer passed by the application is not + * large enough to hold the value of @p attribute, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p attribute is an invalid + * system attribute, or @p value is NULL. + */ +hsa_status_t HSA_API hsa_system_get_info( + hsa_system_info_t attribute, + void* value); + +/** + * @brief HSA extensions. + */ +typedef enum { + /** + * Finalizer extension. + */ + HSA_EXTENSION_FINALIZER = 0, + /** + * Images extension. + */ + HSA_EXTENSION_IMAGES = 1, + + /** + * Performance counter extension. + */ + HSA_EXTENSION_PERFORMANCE_COUNTERS = 2, + + /** + * Profiling events extension. + */ + HSA_EXTENSION_PROFILING_EVENTS = 3, + /** + * Extension count. + */ + HSA_EXTENSION_STD_LAST = 3, + /** + * First AMD extension number. + */ + HSA_AMD_FIRST_EXTENSION = 0x200, + /** + * Profiler extension. + */ + HSA_EXTENSION_AMD_PROFILER = 0x200, + /** + * Loader extension. + */ + HSA_EXTENSION_AMD_LOADER = 0x201, + /** + * AqlProfile extension. + */ + HSA_EXTENSION_AMD_AQLPROFILE = 0x202, + /** + * PC Sampling extension. + */ + HSA_EXTENSION_AMD_PC_SAMPLING = 0x203, + /** + * Last AMD extension. + */ + HSA_AMD_LAST_EXTENSION = 0x203 +} hsa_extension_t; + +/** + * @brief Query the name of a given extension. + * + * @param[in] extension Extension identifier. If the extension is not supported + * by the implementation (see ::HSA_SYSTEM_INFO_EXTENSIONS), the behavior + * is undefined. + * + * @param[out] name Pointer to a memory location where the HSA runtime stores + * the extension name. The extension name is a NUL-terminated string. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p extension is not a valid + * extension, or @p name is NULL. + */ +hsa_status_t HSA_API hsa_extension_get_name( + uint16_t extension, + const char **name); + +/** + * @deprecated + * + * @brief Query if a given version of an extension is supported by the HSA + * implementation. + * + * @param[in] extension Extension identifier. + * + * @param[in] version_major Major version number. + * + * @param[in] version_minor Minor version number. + * + * @param[out] result Pointer to a memory location where the HSA runtime stores + * the result of the check. The result is true if the specified version of the + * extension is supported, and false otherwise. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p extension is not a valid + * extension, or @p result is NULL. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_system_extension_supported( + uint16_t extension, + uint16_t version_major, + uint16_t version_minor, + bool* result); + +/** + * @brief Query if a given version of an extension is supported by the HSA + * implementation. All minor versions from 0 up to the returned @p version_minor + * must be supported by the implementation. + * + * @param[in] extension Extension identifier. + * + * @param[in] version_major Major version number. + * + * @param[out] version_minor Minor version number. + * + * @param[out] result Pointer to a memory location where the HSA runtime stores + * the result of the check. The result is true if the specified version of the + * extension is supported, and false otherwise. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p extension is not a valid + * extension, or @p version_minor is NULL, or @p result is NULL. + */ +hsa_status_t HSA_API hsa_system_major_extension_supported( + uint16_t extension, + uint16_t version_major, + uint16_t *version_minor, + bool* result); + + +/** + * @deprecated + * + * @brief Retrieve the function pointers corresponding to a given version of an + * extension. Portable applications are expected to invoke the extension API + * using the returned function pointers + * + * @details The application is responsible for verifying that the given version + * of the extension is supported by the HSA implementation (see + * ::hsa_system_extension_supported). If the given combination of extension, + * major version, and minor version is not supported by the implementation, the + * behavior is undefined. + * + * @param[in] extension Extension identifier. + * + * @param[in] version_major Major version number for which to retrieve the + * function pointer table. + * + * @param[in] version_minor Minor version number for which to retrieve the + * function pointer table. + * + * @param[out] table Pointer to an application-allocated function pointer table + * that is populated by the HSA runtime. Must not be NULL. The memory associated + * with table can be reused or freed after the function returns. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p extension is not a valid + * extension, or @p table is NULL. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_system_get_extension_table( + uint16_t extension, + uint16_t version_major, + uint16_t version_minor, + void *table); + +/** + * @brief Retrieve the function pointers corresponding to a given major version + * of an extension. Portable applications are expected to invoke the extension + * API using the returned function pointers. + * + * @details The application is responsible for verifying that the given major + * version of the extension is supported by the HSA implementation (see + * ::hsa_system_major_extension_supported). If the given combination of extension + * and major version is not supported by the implementation, the behavior is + * undefined. Additionally if the length doesn't allow space for a full minor + * version, it is implementation defined if only some of the function pointers for + * that minor version get written. + * + * @param[in] extension Extension identifier. + * + * @param[in] version_major Major version number for which to retrieve the + * function pointer table. + * + * @param[in] table_length Size in bytes of the function pointer table to be + * populated. The implementation will not write more than this many bytes to the + * table. + * + * @param[out] table Pointer to an application-allocated function pointer table + * that is populated by the HSA runtime. Must not be NULL. The memory associated + * with table can be reused or freed after the function returns. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p extension is not a valid + * extension, or @p table is NULL. + */ +hsa_status_t HSA_API hsa_system_get_major_extension_table( + uint16_t extension, + uint16_t version_major, + size_t table_length, + void *table); + +/** + * @brief Struct containing an opaque handle to an agent, a device that participates in + * the HSA memory model. An agent can submit AQL packets for execution, and + * may also accept AQL packets for execution (agent dispatch packets or kernel + * dispatch packets launching HSAIL-derived binaries). + */ +typedef struct hsa_agent_s { + /** + * Opaque handle. Two handles reference the same object of the enclosing type + * if and only if they are equal. + */ + uint64_t handle; +} hsa_agent_t; + +/** + * @brief Agent features. + */ +typedef enum { + /** + * The agent supports AQL packets of kernel dispatch type. If this + * feature is enabled, the agent is also a kernel agent. + */ + HSA_AGENT_FEATURE_KERNEL_DISPATCH = 1, + /** + * The agent supports AQL packets of agent dispatch type. + */ + HSA_AGENT_FEATURE_AGENT_DISPATCH = 2 +} hsa_agent_feature_t; + +/** + * @brief Hardware device type. + */ +typedef enum { + /** + * CPU device. + */ + HSA_DEVICE_TYPE_CPU = 0, + /** + * GPU device. + */ + HSA_DEVICE_TYPE_GPU = 1, + /** + * DSP device. + */ + HSA_DEVICE_TYPE_DSP = 2 +} hsa_device_type_t; + +/** + * @brief Default floating-point rounding mode. + */ +typedef enum { + /** + * Use a default floating-point rounding mode specified elsewhere. + */ + HSA_DEFAULT_FLOAT_ROUNDING_MODE_DEFAULT = 0, + /** + * Operations that specify the default floating-point mode are rounded to zero + * by default. + */ + HSA_DEFAULT_FLOAT_ROUNDING_MODE_ZERO = 1, + /** + * Operations that specify the default floating-point mode are rounded to the + * nearest representable number and that ties should be broken by selecting + * the value with an even least significant bit. + */ + HSA_DEFAULT_FLOAT_ROUNDING_MODE_NEAR = 2 +} hsa_default_float_rounding_mode_t; + +/** + * @brief Agent attributes. + */ +typedef enum { + /** + * Agent name. The type of this attribute is a NUL-terminated char[64]. The + * name must be at most 63 characters long (not including the NUL terminator) + * and all array elements not used for the name must be NUL. + */ + HSA_AGENT_INFO_NAME = 0, + /** + * Name of vendor. The type of this attribute is a NUL-terminated char[64]. + * The name must be at most 63 characters long (not including the NUL + * terminator) and all array elements not used for the name must be NUL. + */ + HSA_AGENT_INFO_VENDOR_NAME = 1, + /** + * Agent capability. The type of this attribute is ::hsa_agent_feature_t. + */ + HSA_AGENT_INFO_FEATURE = 2, + /** + * @deprecated Query ::HSA_ISA_INFO_MACHINE_MODELS for a given intruction set + * architecture supported by the agent instead. If more than one ISA is + * supported by the agent, the returned value corresponds to the first ISA + * enumerated by ::hsa_agent_iterate_isas. + * + * Machine model supported by the agent. The type of this attribute is + * ::hsa_machine_model_t. + */ + HSA_AGENT_INFO_MACHINE_MODEL = 3, + /** + * @deprecated Query ::HSA_ISA_INFO_PROFILES for a given intruction set + * architecture supported by the agent instead. If more than one ISA is + * supported by the agent, the returned value corresponds to the first ISA + * enumerated by ::hsa_agent_iterate_isas. + * + * Profile supported by the agent. The type of this attribute is + * ::hsa_profile_t. + */ + HSA_AGENT_INFO_PROFILE = 4, + /** + * @deprecated Query ::HSA_ISA_INFO_DEFAULT_FLOAT_ROUNDING_MODES for a given + * intruction set architecture supported by the agent instead. If more than + * one ISA is supported by the agent, the returned value corresponds to the + * first ISA enumerated by ::hsa_agent_iterate_isas. + * + * Default floating-point rounding mode. The type of this attribute is + * ::hsa_default_float_rounding_mode_t, but the value + * ::HSA_DEFAULT_FLOAT_ROUNDING_MODE_DEFAULT is not allowed. + */ + HSA_AGENT_INFO_DEFAULT_FLOAT_ROUNDING_MODE = 5, + /** + * @deprecated Query ::HSA_ISA_INFO_BASE_PROFILE_DEFAULT_FLOAT_ROUNDING_MODES + * for a given intruction set architecture supported by the agent instead. If + * more than one ISA is supported by the agent, the returned value corresponds + * to the first ISA enumerated by ::hsa_agent_iterate_isas. + * + * A bit-mask of ::hsa_default_float_rounding_mode_t values, representing the + * default floating-point rounding modes supported by the agent in the Base + * profile. The type of this attribute is uint32_t. The default floating-point + * rounding mode (::HSA_AGENT_INFO_DEFAULT_FLOAT_ROUNDING_MODE) bit must not + * be set. + */ + HSA_AGENT_INFO_BASE_PROFILE_DEFAULT_FLOAT_ROUNDING_MODES = 23, + /** + * @deprecated Query ::HSA_ISA_INFO_FAST_F16_OPERATION for a given intruction + * set architecture supported by the agent instead. If more than one ISA is + * supported by the agent, the returned value corresponds to the first ISA + * enumerated by ::hsa_agent_iterate_isas. + * + * Flag indicating that the f16 HSAIL operation is at least as fast as the + * f32 operation in the current agent. The value of this attribute is + * undefined if the agent is not a kernel agent. The type of this + * attribute is bool. + */ + HSA_AGENT_INFO_FAST_F16_OPERATION = 24, + /** + * @deprecated Query ::HSA_WAVEFRONT_INFO_SIZE for a given wavefront and + * intruction set architecture supported by the agent instead. If more than + * one ISA is supported by the agent, the returned value corresponds to the + * first ISA enumerated by ::hsa_agent_iterate_isas and the first wavefront + * enumerated by ::hsa_isa_iterate_wavefronts for that ISA. + * + * Number of work-items in a wavefront. Must be a power of 2 in the range + * [1,256]. The value of this attribute is undefined if the agent is not + * a kernel agent. The type of this attribute is uint32_t. + */ + HSA_AGENT_INFO_WAVEFRONT_SIZE = 6, + /** + * @deprecated Query ::HSA_ISA_INFO_WORKGROUP_MAX_DIM for a given intruction + * set architecture supported by the agent instead. If more than one ISA is + * supported by the agent, the returned value corresponds to the first ISA + * enumerated by ::hsa_agent_iterate_isas. + * + * Maximum number of work-items of each dimension of a work-group. Each + * maximum must be greater than 0. No maximum can exceed the value of + * ::HSA_AGENT_INFO_WORKGROUP_MAX_SIZE. The value of this attribute is + * undefined if the agent is not a kernel agent. The type of this + * attribute is uint16_t[3]. + */ + HSA_AGENT_INFO_WORKGROUP_MAX_DIM = 7, + /** + * @deprecated Query ::HSA_ISA_INFO_WORKGROUP_MAX_SIZE for a given intruction + * set architecture supported by the agent instead. If more than one ISA is + * supported by the agent, the returned value corresponds to the first ISA + * enumerated by ::hsa_agent_iterate_isas. + * + * Maximum total number of work-items in a work-group. The value of this + * attribute is undefined if the agent is not a kernel agent. The type + * of this attribute is uint32_t. + */ + HSA_AGENT_INFO_WORKGROUP_MAX_SIZE = 8, + /** + * @deprecated Query ::HSA_ISA_INFO_GRID_MAX_DIM for a given intruction set + * architecture supported by the agent instead. + * + * Maximum number of work-items of each dimension of a grid. Each maximum must + * be greater than 0, and must not be smaller than the corresponding value in + * ::HSA_AGENT_INFO_WORKGROUP_MAX_DIM. No maximum can exceed the value of + * ::HSA_AGENT_INFO_GRID_MAX_SIZE. The value of this attribute is undefined + * if the agent is not a kernel agent. The type of this attribute is + * ::hsa_dim3_t. + */ + HSA_AGENT_INFO_GRID_MAX_DIM = 9, + /** + * @deprecated Query ::HSA_ISA_INFO_GRID_MAX_SIZE for a given intruction set + * architecture supported by the agent instead. If more than one ISA is + * supported by the agent, the returned value corresponds to the first ISA + * enumerated by ::hsa_agent_iterate_isas. + * + * Maximum total number of work-items in a grid. The value of this attribute + * is undefined if the agent is not a kernel agent. The type of this + * attribute is uint32_t. + */ + HSA_AGENT_INFO_GRID_MAX_SIZE = 10, + /** + * @deprecated Query ::HSA_ISA_INFO_FBARRIER_MAX_SIZE for a given intruction + * set architecture supported by the agent instead. If more than one ISA is + * supported by the agent, the returned value corresponds to the first ISA + * enumerated by ::hsa_agent_iterate_isas. + * + * Maximum number of fbarriers per work-group. Must be at least 32. The value + * of this attribute is undefined if the agent is not a kernel agent. The + * type of this attribute is uint32_t. + */ + HSA_AGENT_INFO_FBARRIER_MAX_SIZE = 11, + /** + * @deprecated The maximum number of queues is not statically determined. + * + * Maximum number of queues that can be active (created but not destroyed) at + * one time in the agent. The type of this attribute is uint32_t. + */ + HSA_AGENT_INFO_QUEUES_MAX = 12, + /** + * Minimum number of packets that a queue created in the agent + * can hold. Must be a power of 2 greater than 0. Must not exceed + * the value of ::HSA_AGENT_INFO_QUEUE_MAX_SIZE. The type of this + * attribute is uint32_t. + */ + HSA_AGENT_INFO_QUEUE_MIN_SIZE = 13, + /** + * Maximum number of packets that a queue created in the agent can + * hold. Must be a power of 2 greater than 0. The type of this attribute + * is uint32_t. + */ + HSA_AGENT_INFO_QUEUE_MAX_SIZE = 14, + /** + * Type of a queue created in the agent. The type of this attribute is + * ::hsa_queue_type32_t. + */ + HSA_AGENT_INFO_QUEUE_TYPE = 15, + /** + * @deprecated NUMA information is not exposed anywhere else in the API. + * + * Identifier of the NUMA node associated with the agent. The type of this + * attribute is uint32_t. + */ + HSA_AGENT_INFO_NODE = 16, + /** + * Type of hardware device associated with the agent. The type of this + * attribute is ::hsa_device_type_t. + */ + HSA_AGENT_INFO_DEVICE = 17, + /** + * @deprecated Query ::hsa_agent_iterate_caches to retrieve information about + * the caches present in a given agent. + * + * Array of data cache sizes (L1..L4). Each size is expressed in bytes. A size + * of 0 for a particular level indicates that there is no cache information + * for that level. The type of this attribute is uint32_t[4]. + */ + HSA_AGENT_INFO_CACHE_SIZE = 18, + /** + * @deprecated An agent may support multiple instruction set + * architectures. See ::hsa_agent_iterate_isas. If more than one ISA is + * supported by the agent, the returned value corresponds to the first ISA + * enumerated by ::hsa_agent_iterate_isas. + * + * Instruction set architecture of the agent. The type of this attribute + * is ::hsa_isa_t. + */ + HSA_AGENT_INFO_ISA = 19, + /** + * Bit-mask indicating which extensions are supported by the agent. An + * extension with an ID of @p i is supported if the bit at position @p i is + * set. The type of this attribute is uint8_t[128]. + */ + HSA_AGENT_INFO_EXTENSIONS = 20, + /** + * Major version of the HSA runtime specification supported by the + * agent. The type of this attribute is uint16_t. + */ + HSA_AGENT_INFO_VERSION_MAJOR = 21, + /** + * Minor version of the HSA runtime specification supported by the + * agent. The type of this attribute is uint16_t. + */ + HSA_AGENT_INFO_VERSION_MINOR = 22, + /** + * This enum does not have a fixed underlying type, thus in C++ post D2338: + * If the enumeration type does not have a fixed underlying type, the value is + * unchanged if the original value is within the range of the enumeration + * values (9.7.1 [dcl.enum]), and otherwise, the behavior is + * undefined. + * Thus increase the range of this enum to encompass vendor extensions. + */ + HSA_AGENT_INFO_LAST = INT32_MAX +} hsa_agent_info_t; + +/** + * @brief Get the current value of an attribute for a given agent. + * + * @param[in] agent A valid agent. + * + * @param[in] attribute Attribute to query. + * + * @param[out] value Pointer to an application-allocated buffer where to store + * the value of the attribute. If the buffer passed by the application is not + * large enough to hold the value of @p attribute, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p attribute is an invalid + * agent attribute, or @p value is NULL. + */ +hsa_status_t HSA_API hsa_agent_get_info( + hsa_agent_t agent, + hsa_agent_info_t attribute, + void* value); + +/** + * @brief Iterate over the available agents, and invoke an + * application-defined callback on every iteration. + * + * @param[in] callback Callback to be invoked once per agent. The HSA + * runtime passes two arguments to the callback: the agent and the + * application data. If @p callback returns a status other than + * ::HSA_STATUS_SUCCESS for a particular iteration, the traversal stops and + * ::hsa_iterate_agents returns that status value. + * + * @param[in] data Application data that is passed to @p callback on every + * iteration. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p callback is NULL. +*/ +hsa_status_t HSA_API hsa_iterate_agents( + hsa_status_t (*callback)(hsa_agent_t agent, void* data), + void* data); + +/* + +// If we do not know the size of an attribute, we need to query it first +// Note: this API will not be in the spec unless needed +hsa_status_t HSA_API hsa_agent_get_info_size( + hsa_agent_t agent, + hsa_agent_info_t attribute, + size_t* size); + +// Set the value of an agents attribute +// Note: this API will not be in the spec unless needed +hsa_status_t HSA_API hsa_agent_set_info( + hsa_agent_t agent, + hsa_agent_info_t attribute, + void* value); + +*/ + +/** + * @brief Exception policies applied in the presence of hardware exceptions. + */ +typedef enum { + /** + * If a hardware exception is detected, a work-item signals an exception. + */ + HSA_EXCEPTION_POLICY_BREAK = 1, + /** + * If a hardware exception is detected, a hardware status bit is set. + */ + HSA_EXCEPTION_POLICY_DETECT = 2 +} hsa_exception_policy_t; + +/** + * @deprecated Use ::hsa_isa_get_exception_policies for a given intruction set + * architecture supported by the agent instead. If more than one ISA is + * supported by the agent, this function uses the first value returned by + * ::hsa_agent_iterate_isas. + * + * @brief Retrieve the exception policy support for a given combination of + * agent and profile + * + * @param[in] agent Agent. + * + * @param[in] profile Profile. + * + * @param[out] mask Pointer to a memory location where the HSA runtime stores a + * mask of ::hsa_exception_policy_t values. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p profile is not a valid + * profile, or @p mask is NULL. + * + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_agent_get_exception_policies( + hsa_agent_t agent, + hsa_profile_t profile, + uint16_t *mask); + +/** + * @brief Cache handle. + */ +typedef struct hsa_cache_s { + /** + * Opaque handle. Two handles reference the same object of the enclosing type + * if and only if they are equal. + */ + uint64_t handle; +} hsa_cache_t; + +/** + * @brief Cache attributes. + */ +typedef enum { + /** + * The length of the cache name in bytes, not including the NUL terminator. + * The type of this attribute is uint32_t. + */ + HSA_CACHE_INFO_NAME_LENGTH = 0, + /** + * Human-readable description. The type of this attribute is a NUL-terminated + * character array with the length equal to the value of + * ::HSA_CACHE_INFO_NAME_LENGTH attribute. + */ + HSA_CACHE_INFO_NAME = 1, + /** + * Cache level. A L1 cache must return a value of 1, a L2 must return a value + * of 2, and so on. The type of this attribute is uint8_t. + */ + HSA_CACHE_INFO_LEVEL = 2, + /** + * Cache size, in bytes. A value of 0 indicates that there is no size + * information available. The type of this attribute is uint32_t. + */ + HSA_CACHE_INFO_SIZE = 3 +} hsa_cache_info_t; + +/** + * @brief Get the current value of an attribute for a given cache object. + * + * @param[in] cache Cache. + * + * @param[in] attribute Attribute to query. + * + * @param[out] value Pointer to an application-allocated buffer where to store + * the value of the attribute. If the buffer passed by the application is not + * large enough to hold the value of @p attribute, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_CACHE The cache is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p attribute is an invalid + * instruction set architecture attribute, or @p value is + * NULL. + */ +hsa_status_t HSA_API hsa_cache_get_info( + hsa_cache_t cache, + hsa_cache_info_t attribute, + void* value); + +/** + * @brief Iterate over the memory caches of a given agent, and + * invoke an application-defined callback on every iteration. + * + * @details Caches are visited in ascending order according to the value of the + * ::HSA_CACHE_INFO_LEVEL attribute. + * + * @param[in] agent A valid agent. + * + * @param[in] callback Callback to be invoked once per cache that is present in + * the agent. The HSA runtime passes two arguments to the callback: the cache + * and the application data. If @p callback returns a status other than + * ::HSA_STATUS_SUCCESS for a particular iteration, the traversal stops and + * that value is returned. + * + * @param[in] data Application data that is passed to @p callback on every + * iteration. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p callback is NULL. + */ +hsa_status_t HSA_API hsa_agent_iterate_caches( + hsa_agent_t agent, + hsa_status_t (*callback)(hsa_cache_t cache, void* data), + void* data); + +/** + * @deprecated + * + * @brief Query if a given version of an extension is supported by an agent + * + * @param[in] extension Extension identifier. + * + * @param[in] agent Agent. + * + * @param[in] version_major Major version number. + * + * @param[in] version_minor Minor version number. + * + * @param[out] result Pointer to a memory location where the HSA runtime stores + * the result of the check. The result is true if the specified version of the + * extension is supported, and false otherwise. The result must be false if + * ::hsa_system_extension_supported returns false for the same extension + * version. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p extension is not a valid + * extension, or @p result is NULL. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_agent_extension_supported( + uint16_t extension, + hsa_agent_t agent, + uint16_t version_major, + uint16_t version_minor, + bool* result); + +/** + * @brief Query if a given version of an extension is supported by an agent. All + * minor versions from 0 up to the returned @p version_minor must be supported. + * + * @param[in] extension Extension identifier. + * + * @param[in] agent Agent. + * + * @param[in] version_major Major version number. + * + * @param[out] version_minor Minor version number. + * + * @param[out] result Pointer to a memory location where the HSA runtime stores + * the result of the check. The result is true if the specified version of the + * extension is supported, and false otherwise. The result must be false if + * ::hsa_system_extension_supported returns false for the same extension + * version. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p extension is not a valid + * extension, or @p version_minor is NULL, or @p result is NULL. + */ +hsa_status_t HSA_API hsa_agent_major_extension_supported( + uint16_t extension, + hsa_agent_t agent, + uint16_t version_major, + uint16_t *version_minor, + bool* result); + + +/** @} */ + + +/** \defgroup signals Signals + * @{ + */ + +/** + * @brief Signal handle. + */ +typedef struct hsa_signal_s { + /** + * Opaque handle. Two handles reference the same object of the enclosing type + * if and only if they are equal. The value 0 is reserved. + */ + uint64_t handle; +} hsa_signal_t; + +/** + * @brief Signal value. The value occupies 32 bits in small machine mode, and 64 + * bits in large machine mode. + */ +#ifdef HSA_LARGE_MODEL + typedef int64_t hsa_signal_value_t; +#else + typedef int32_t hsa_signal_value_t; +#endif + +/** + * @brief Create a signal. + * + * @param[in] initial_value Initial value of the signal. + * + * @param[in] num_consumers Size of @p consumers. A value of 0 indicates that + * any agent might wait on the signal. + * + * @param[in] consumers List of agents that might consume (wait on) the + * signal. If @p num_consumers is 0, this argument is ignored; otherwise, the + * HSA runtime might use the list to optimize the handling of the signal + * object. If an agent not listed in @p consumers waits on the returned + * signal, the behavior is undefined. The memory associated with @p consumers + * can be reused or freed after the function returns. + * + * @param[out] signal Pointer to a memory location where the HSA runtime will + * store the newly created signal handle. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to allocate + * the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p signal is NULL, @p + * num_consumers is greater than 0 but @p consumers is NULL, or @p consumers + * contains duplicates. + */ +hsa_status_t HSA_API hsa_signal_create( + hsa_signal_value_t initial_value, + uint32_t num_consumers, + const hsa_agent_t *consumers, + hsa_signal_t *signal); + +/** + * @brief Destroy a signal previous created by ::hsa_signal_create. + * + * @param[in] signal Signal. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_SIGNAL @p signal is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT The handle in @p signal is 0. + */ +hsa_status_t HSA_API hsa_signal_destroy( + hsa_signal_t signal); + +/** + * @brief Atomically read the current value of a signal. + * + * @param[in] signal Signal. + * + * @return Value of the signal. +*/ +hsa_signal_value_t HSA_API hsa_signal_load_scacquire( + hsa_signal_t signal); + +/** + * @copydoc hsa_signal_load_scacquire + */ +hsa_signal_value_t HSA_API hsa_signal_load_relaxed( + hsa_signal_t signal); + +/** + * @deprecated Renamed as ::hsa_signal_load_scacquire. + * + * @copydoc hsa_signal_load_scacquire +*/ +hsa_signal_value_t HSA_API HSA_DEPRECATED hsa_signal_load_acquire( + hsa_signal_t signal); + +/** + * @brief Atomically set the value of a signal. + * + * @details If the value of the signal is changed, all the agents waiting + * on @p signal for which @p value satisfies their wait condition are awakened. + * + * @param[in] signal Signal. + * + * @param[in] value New signal value. + */ +void HSA_API hsa_signal_store_relaxed( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_store_relaxed + */ +void HSA_API hsa_signal_store_screlease( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @deprecated Renamed as ::hsa_signal_store_screlease. + * + * @copydoc hsa_signal_store_screlease + */ +void HSA_API HSA_DEPRECATED hsa_signal_store_release( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @brief Atomically set the value of a signal without necessarily notifying the + * the agents waiting on it. + * + * @details The agents waiting on @p signal may not wake up even when the new + * value satisfies their wait condition. If the application wants to update the + * signal and there is no need to notify any agent, invoking this function can + * be more efficient than calling the non-silent counterpart. + * + * @param[in] signal Signal. + * + * @param[in] value New signal value. + */ +void HSA_API hsa_signal_silent_store_relaxed( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_silent_store_relaxed + */ +void HSA_API hsa_signal_silent_store_screlease( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @brief Atomically set the value of a signal and return its previous value. + * + * @details If the value of the signal is changed, all the agents waiting + * on @p signal for which @p value satisfies their wait condition are awakened. + * + * @param[in] signal Signal. If @p signal is a queue doorbell signal, the + * behavior is undefined. + * + * @param[in] value New value. + * + * @return Value of the signal prior to the exchange. + * + */ +hsa_signal_value_t HSA_API hsa_signal_exchange_scacq_screl( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @deprecated Renamed as ::hsa_signal_exchange_scacq_screl. + * + * @copydoc hsa_signal_exchange_scacq_screl + */ +hsa_signal_value_t HSA_API HSA_DEPRECATED hsa_signal_exchange_acq_rel( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_exchange_scacq_screl + */ +hsa_signal_value_t HSA_API hsa_signal_exchange_scacquire( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @deprecated Renamed as ::hsa_signal_exchange_scacquire. + * + * @copydoc hsa_signal_exchange_scacquire + */ +hsa_signal_value_t HSA_API HSA_DEPRECATED hsa_signal_exchange_acquire( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_exchange_scacq_screl + */ +hsa_signal_value_t HSA_API hsa_signal_exchange_relaxed( + hsa_signal_t signal, + hsa_signal_value_t value); +/** + * @copydoc hsa_signal_exchange_scacq_screl + */ +hsa_signal_value_t HSA_API hsa_signal_exchange_screlease( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @deprecated Renamed as ::hsa_signal_exchange_screlease. + * + * @copydoc hsa_signal_exchange_screlease + */ +hsa_signal_value_t HSA_API HSA_DEPRECATED hsa_signal_exchange_release( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @brief Atomically set the value of a signal if the observed value is equal to + * the expected value. The observed value is returned regardless of whether the + * replacement was done. + * + * @details If the value of the signal is changed, all the agents waiting + * on @p signal for which @p value satisfies their wait condition are awakened. + * + * @param[in] signal Signal. If @p signal is a queue + * doorbell signal, the behavior is undefined. + * + * @param[in] expected Value to compare with. + * + * @param[in] value New value. + * + * @return Observed value of the signal. + * + */ +hsa_signal_value_t HSA_API hsa_signal_cas_scacq_screl( + hsa_signal_t signal, + hsa_signal_value_t expected, + hsa_signal_value_t value); + + +/** + * @deprecated Renamed as ::hsa_signal_cas_scacq_screl. + * + * @copydoc hsa_signal_cas_scacq_screl + */ +hsa_signal_value_t HSA_API HSA_DEPRECATED hsa_signal_cas_acq_rel( + hsa_signal_t signal, + hsa_signal_value_t expected, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_cas_scacq_screl + */ +hsa_signal_value_t HSA_API hsa_signal_cas_scacquire( + hsa_signal_t signal, + hsa_signal_value_t expected, + hsa_signal_value_t value); + +/** + * @deprecated Renamed as ::hsa_signal_cas_scacquire. + * + * @copydoc hsa_signal_cas_scacquire + */ +hsa_signal_value_t HSA_API HSA_DEPRECATED hsa_signal_cas_acquire( + hsa_signal_t signal, + hsa_signal_value_t expected, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_cas_scacq_screl + */ +hsa_signal_value_t HSA_API hsa_signal_cas_relaxed( + hsa_signal_t signal, + hsa_signal_value_t expected, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_cas_scacq_screl + */ +hsa_signal_value_t HSA_API hsa_signal_cas_screlease( + hsa_signal_t signal, + hsa_signal_value_t expected, + hsa_signal_value_t value); + +/** + * @deprecated Renamed as ::hsa_signal_cas_screlease. + * + * @copydoc hsa_signal_cas_screlease + */ +hsa_signal_value_t HSA_API HSA_DEPRECATED hsa_signal_cas_release( + hsa_signal_t signal, + hsa_signal_value_t expected, + hsa_signal_value_t value); + +/** + * @brief Atomically increment the value of a signal by a given amount. + * + * @details If the value of the signal is changed, all the agents waiting on + * @p signal for which @p value satisfies their wait condition are awakened. + * + * @param[in] signal Signal. If @p signal is a queue doorbell signal, the + * behavior is undefined. + * + * @param[in] value Value to add to the value of the signal. + * + */ +void HSA_API hsa_signal_add_scacq_screl( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @deprecated Renamed as ::hsa_signal_add_scacq_screl. + * + * @copydoc hsa_signal_add_scacq_screl + */ +void HSA_API HSA_DEPRECATED hsa_signal_add_acq_rel( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_add_scacq_screl + */ +void HSA_API hsa_signal_add_scacquire( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @deprecated Renamed as ::hsa_signal_add_scacquire. + * + * @copydoc hsa_signal_add_scacquire + */ +void HSA_API HSA_DEPRECATED hsa_signal_add_acquire( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_add_scacq_screl + */ +void HSA_API hsa_signal_add_relaxed( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_add_scacq_screl + */ +void HSA_API hsa_signal_add_screlease( + hsa_signal_t signal, + hsa_signal_value_t value); + + +/** + * @deprecated Renamed as ::hsa_signal_add_screlease. + * + * @copydoc hsa_signal_add_screlease + */ +void HSA_API HSA_DEPRECATED hsa_signal_add_release( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @brief Atomically decrement the value of a signal by a given amount. + * + * @details If the value of the signal is changed, all the agents waiting on + * @p signal for which @p value satisfies their wait condition are awakened. + * + * @param[in] signal Signal. If @p signal is a queue doorbell signal, the + * behavior is undefined. + * + * @param[in] value Value to subtract from the value of the signal. + * + */ +void HSA_API hsa_signal_subtract_scacq_screl( + hsa_signal_t signal, + hsa_signal_value_t value); + + +/** + * @deprecated Renamed as ::hsa_signal_subtract_scacq_screl. + * + * @copydoc hsa_signal_subtract_scacq_screl + */ +void HSA_API HSA_DEPRECATED hsa_signal_subtract_acq_rel( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_subtract_scacq_screl + */ +void HSA_API hsa_signal_subtract_scacquire( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @deprecated Renamed as ::hsa_signal_subtract_scacquire. + * + * @copydoc hsa_signal_subtract_scacquire + */ +void HSA_API HSA_DEPRECATED hsa_signal_subtract_acquire( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_subtract_scacq_screl + */ +void HSA_API hsa_signal_subtract_relaxed( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_subtract_scacq_screl + */ +void HSA_API hsa_signal_subtract_screlease( + hsa_signal_t signal, + hsa_signal_value_t value); + + +/** + * @deprecated Renamed as ::hsa_signal_subtract_screlease. + * + * @copydoc hsa_signal_subtract_screlease + */ +void HSA_API HSA_DEPRECATED hsa_signal_subtract_release( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @brief Atomically perform a bitwise AND operation between the value of a + * signal and a given value. + * + * @details If the value of the signal is changed, all the agents waiting on + * @p signal for which @p value satisfies their wait condition are awakened. + * + * @param[in] signal Signal. If @p signal is a queue doorbell signal, the + * behavior is undefined. + * + * @param[in] value Value to AND with the value of the signal. + * + */ +void HSA_API hsa_signal_and_scacq_screl( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @deprecated Renamed as ::hsa_signal_and_scacq_screl. + * + * @copydoc hsa_signal_and_scacq_screl + */ +void HSA_API HSA_DEPRECATED hsa_signal_and_acq_rel( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_and_scacq_screl + */ +void HSA_API hsa_signal_and_scacquire( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @deprecated Renamed as ::hsa_signal_and_scacquire. + * + * @copydoc hsa_signal_and_scacquire + */ +void HSA_API HSA_DEPRECATED hsa_signal_and_acquire( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_and_scacq_screl + */ +void HSA_API hsa_signal_and_relaxed( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_and_scacq_screl + */ +void HSA_API hsa_signal_and_screlease( + hsa_signal_t signal, + hsa_signal_value_t value); + + +/** + * @deprecated Renamed as ::hsa_signal_and_screlease. + * + * @copydoc hsa_signal_and_screlease + */ +void HSA_API HSA_DEPRECATED hsa_signal_and_release( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @brief Atomically perform a bitwise OR operation between the value of a + * signal and a given value. + * + * @details If the value of the signal is changed, all the agents waiting on + * @p signal for which @p value satisfies their wait condition are awakened. + * + * @param[in] signal Signal. If @p signal is a queue doorbell signal, the + * behavior is undefined. + * + * @param[in] value Value to OR with the value of the signal. + */ +void HSA_API hsa_signal_or_scacq_screl( + hsa_signal_t signal, + hsa_signal_value_t value); + + +/** + * @deprecated Renamed as ::hsa_signal_or_scacq_screl. + * + * @copydoc hsa_signal_or_scacq_screl + */ +void HSA_API HSA_DEPRECATED hsa_signal_or_acq_rel( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_or_scacq_screl + */ +void HSA_API hsa_signal_or_scacquire( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @deprecated Renamed as ::hsa_signal_or_scacquire. + * + * @copydoc hsa_signal_or_scacquire + */ +void HSA_API HSA_DEPRECATED hsa_signal_or_acquire( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_or_scacq_screl + */ +void HSA_API hsa_signal_or_relaxed( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_or_scacq_screl + */ +void HSA_API hsa_signal_or_screlease( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @deprecated Renamed as ::hsa_signal_or_screlease. + * + * @copydoc hsa_signal_or_screlease + */ +void HSA_API HSA_DEPRECATED hsa_signal_or_release( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @brief Atomically perform a bitwise XOR operation between the value of a + * signal and a given value. + * + * @details If the value of the signal is changed, all the agents waiting on + * @p signal for which @p value satisfies their wait condition are awakened. + * + * @param[in] signal Signal. If @p signal is a queue doorbell signal, the + * behavior is undefined. + * + * @param[in] value Value to XOR with the value of the signal. + * + */ +void HSA_API hsa_signal_xor_scacq_screl( + hsa_signal_t signal, + hsa_signal_value_t value); + + +/** + * @deprecated Renamed as ::hsa_signal_xor_scacq_screl. + * + * @copydoc hsa_signal_xor_scacq_screl + */ +void HSA_API HSA_DEPRECATED hsa_signal_xor_acq_rel( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_xor_scacq_screl + */ +void HSA_API hsa_signal_xor_scacquire( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @deprecated Renamed as ::hsa_signal_xor_scacquire. + * + * @copydoc hsa_signal_xor_scacquire + */ +void HSA_API HSA_DEPRECATED hsa_signal_xor_acquire( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_xor_scacq_screl + */ +void HSA_API hsa_signal_xor_relaxed( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @copydoc hsa_signal_xor_scacq_screl + */ +void HSA_API hsa_signal_xor_screlease( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @deprecated Renamed as ::hsa_signal_xor_screlease. + * + * @copydoc hsa_signal_xor_screlease + */ +void HSA_API HSA_DEPRECATED hsa_signal_xor_release( + hsa_signal_t signal, + hsa_signal_value_t value); + +/** + * @brief Wait condition operator. + */ +typedef enum { + /** + * The two operands are equal. + */ + HSA_SIGNAL_CONDITION_EQ = 0, + /** + * The two operands are not equal. + */ + HSA_SIGNAL_CONDITION_NE = 1, + /** + * The first operand is less than the second operand. + */ + HSA_SIGNAL_CONDITION_LT = 2, + /** + * The first operand is greater than or equal to the second operand. + */ + HSA_SIGNAL_CONDITION_GTE = 3 +} hsa_signal_condition_t; + +/** + * @brief State of the application thread during a signal wait. + */ +typedef enum { + /** + * The application thread may be rescheduled while waiting on the signal. + */ + HSA_WAIT_STATE_BLOCKED = 0, + /** + * The application thread stays active while waiting on a signal. + */ + HSA_WAIT_STATE_ACTIVE = 1 +} hsa_wait_state_t; + + +/** + * @brief Wait until a signal value satisfies a specified condition, or a + * certain amount of time has elapsed. + * + * @details A wait operation can spuriously resume at any time sooner than the + * timeout (for example, due to system or other external factors) even when the + * condition has not been met. + * + * The function is guaranteed to return if the signal value satisfies the + * condition at some point in time during the wait, but the value returned to + * the application might not satisfy the condition. The application must ensure + * that signals are used in such way that wait wakeup conditions are not + * invalidated before dependent threads have woken up. + * + * When the wait operation internally loads the value of the passed signal, it + * uses the memory order indicated in the function name. + * + * @param[in] signal Signal. + * + * @param[in] condition Condition used to compare the signal value with @p + * compare_value. + * + * @param[in] compare_value Value to compare with. + * + * @param[in] timeout_hint Maximum duration of the wait. Specified in the same + * unit as the system timestamp. The operation might block for a shorter or + * longer time even if the condition is not met. A value of UINT64_MAX indicates + * no maximum. + * + * @param[in] wait_state_hint Hint used by the application to indicate the + * preferred waiting state. The actual waiting state is ultimately decided by + * HSA runtime and may not match the provided hint. A value of + * ::HSA_WAIT_STATE_ACTIVE may improve the latency of response to a signal + * update by avoiding rescheduling overhead. + * + * @return Observed value of the signal, which might not satisfy the specified + * condition. + * +*/ +hsa_signal_value_t HSA_API hsa_signal_wait_scacquire( + hsa_signal_t signal, + hsa_signal_condition_t condition, + hsa_signal_value_t compare_value, + uint64_t timeout_hint, + hsa_wait_state_t wait_state_hint); + +/** + * @copydoc hsa_signal_wait_scacquire + */ +hsa_signal_value_t HSA_API hsa_signal_wait_relaxed( + hsa_signal_t signal, + hsa_signal_condition_t condition, + hsa_signal_value_t compare_value, + uint64_t timeout_hint, + hsa_wait_state_t wait_state_hint); + +/** + * @deprecated Renamed as ::hsa_signal_wait_scacquire. + * + * @copydoc hsa_signal_wait_scacquire + */ +hsa_signal_value_t HSA_API HSA_DEPRECATED hsa_signal_wait_acquire( + hsa_signal_t signal, + hsa_signal_condition_t condition, + hsa_signal_value_t compare_value, + uint64_t timeout_hint, + hsa_wait_state_t wait_state_hint); + +/** + * @brief Group of signals. + */ +typedef struct hsa_signal_group_s { + /** + * Opaque handle. Two handles reference the same object of the enclosing type + * if and only if they are equal. + */ + uint64_t handle; +} hsa_signal_group_t; + +/** + * @brief Create a signal group. + * + * @param[in] num_signals Number of elements in @p signals. Must not be 0. + * + * @param[in] signals List of signals in the group. The list must not contain + * any repeated elements. Must not be NULL. + * + * @param[in] num_consumers Number of elements in @p consumers. Must not be 0. + * + * @param[in] consumers List of agents that might consume (wait on) the signal + * group. The list must not contain repeated elements, and must be a subset of + * the set of agents that are allowed to wait on all the signals in the + * group. If an agent not listed in @p consumers waits on the returned group, + * the behavior is undefined. The memory associated with @p consumers can be + * reused or freed after the function returns. Must not be NULL. + * + * @param[out] signal_group Pointer to newly created signal group. Must not be + * NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to allocate + * the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p num_signals is 0, @p signals + * is NULL, @p num_consumers is 0, @p consumers is NULL, or @p signal_group is + * NULL. + */ +hsa_status_t HSA_API hsa_signal_group_create( + uint32_t num_signals, + const hsa_signal_t *signals, + uint32_t num_consumers, + const hsa_agent_t *consumers, + hsa_signal_group_t *signal_group); + +/** + * @brief Destroy a signal group previous created by ::hsa_signal_group_create. + * + * @param[in] signal_group Signal group. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_SIGNAL_GROUP @p signal_group is invalid. + */ +hsa_status_t HSA_API hsa_signal_group_destroy( + hsa_signal_group_t signal_group); + +/** + * @brief Wait until the value of at least one of the signals in a signal group + * satisfies its associated condition. + * + * @details The function is guaranteed to return if the value of at least one of + * the signals in the group satisfies its associated condition at some point in + * time during the wait, but the signal value returned to the application may no + * longer satisfy the condition. The application must ensure that signals in the + * group are used in such way that wait wakeup conditions are not invalidated + * before dependent threads have woken up. + * + * When this operation internally loads the value of the passed signal, it uses + * the memory order indicated in the function name. + * + * @param[in] signal_group Signal group. + * + * @param[in] conditions List of conditions. Each condition, and the value at + * the same index in @p compare_values, is used to compare the value of the + * signal at that index in @p signal_group (the signal passed by the application + * to ::hsa_signal_group_create at that particular index). The size of @p + * conditions must not be smaller than the number of signals in @p signal_group; + * any extra elements are ignored. Must not be NULL. + * + * @param[in] compare_values List of comparison values. The size of @p + * compare_values must not be smaller than the number of signals in @p + * signal_group; any extra elements are ignored. Must not be NULL. + * + * @param[in] wait_state_hint Hint used by the application to indicate the + * preferred waiting state. The actual waiting state is decided by the HSA runtime + * and may not match the provided hint. A value of ::HSA_WAIT_STATE_ACTIVE may + * improve the latency of response to a signal update by avoiding rescheduling + * overhead. + * + * @param[out] signal Signal in the group that satisfied the associated + * condition. If several signals satisfied their condition, the function can + * return any of those signals. Must not be NULL. + * + * @param[out] value Observed value for @p signal, which might no longer satisfy + * the specified condition. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_INVALID_SIGNAL_GROUP @p signal_group is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p conditions is NULL, @p + * compare_values is NULL, @p signal is NULL, or @p value is NULL. + */ +hsa_status_t HSA_API hsa_signal_group_wait_any_scacquire( + hsa_signal_group_t signal_group, + const hsa_signal_condition_t *conditions, + const hsa_signal_value_t *compare_values, + hsa_wait_state_t wait_state_hint, + hsa_signal_t *signal, + hsa_signal_value_t *value); + +/** + * @copydoc hsa_signal_group_wait_any_scacquire + */ +hsa_status_t HSA_API hsa_signal_group_wait_any_relaxed( + hsa_signal_group_t signal_group, + const hsa_signal_condition_t *conditions, + const hsa_signal_value_t *compare_values, + hsa_wait_state_t wait_state_hint, + hsa_signal_t *signal, + hsa_signal_value_t *value); + +/** @} */ + +/** \defgroup memory Memory + * @{ + */ + +/** + * @brief A memory region represents a block of virtual memory with certain + * properties. For example, the HSA runtime represents fine-grained memory in + * the global segment using a region. A region might be associated with more + * than one agent. + */ +typedef struct hsa_region_s { + /** + * Opaque handle. Two handles reference the same object of the enclosing type + * if and only if they are equal. + */ + uint64_t handle; +} hsa_region_t; + +/** @} */ + + +/** \defgroup queue Queues + * @{ + */ + +/** + * @brief Queue type. Intended to be used for dynamic queue protocol + * determination. + */ +typedef enum { + /** + * Queue supports multiple producers. Use of multiproducer queue mechanics is + * required. + */ + HSA_QUEUE_TYPE_MULTI = 0, + /** + * Queue only supports a single producer. In some scenarios, the application + * may want to limit the submission of AQL packets to a single agent. Queues + * that support a single producer may be more efficient than queues supporting + * multiple producers. Use of multiproducer queue mechanics is not supported. + */ + HSA_QUEUE_TYPE_SINGLE = 1, + /** + * Queue supports multiple producers and cooperative dispatches. Cooperative + * dispatches are able to use GWS synchronization. Queues of this type may be + * limited in number. The runtime may return the same queue to serve multiple + * ::hsa_queue_create calls when this type is given. Callers must inspect the + * returned queue to discover queue size. Queues of this type are reference + * counted and require a matching number of ::hsa_queue_destroy calls to + * release. Use of multiproducer queue mechanics is required. See + * ::HSA_AMD_AGENT_INFO_COOPERATIVE_QUEUES to query agent support for this + * type. + */ + HSA_QUEUE_TYPE_COOPERATIVE = 2 +} hsa_queue_type_t; + +/** + * @brief A fixed-size type used to represent ::hsa_queue_type_t constants. + */ +typedef uint32_t hsa_queue_type32_t; + +/** + * @brief Queue features. + */ +typedef enum { + /** + * Queue supports kernel dispatch packets. + */ + HSA_QUEUE_FEATURE_KERNEL_DISPATCH = 1, + + /** + * Queue supports agent dispatch packets. + */ + HSA_QUEUE_FEATURE_AGENT_DISPATCH = 2 +} hsa_queue_feature_t; + +/** + * @brief User mode queue. + * + * @details The queue structure is read-only and allocated by the HSA runtime, + * but agents can directly modify the contents of the buffer pointed by @a + * base_address, or use HSA runtime APIs to access the doorbell signal. + * + */ +typedef struct hsa_queue_s { + /** + * Queue type. + */ + hsa_queue_type32_t type; + + /** + * Queue features mask. This is a bit-field of ::hsa_queue_feature_t + * values. Applications should ignore any unknown set bits. + */ + uint32_t features; + +#ifdef HSA_LARGE_MODEL + void* base_address; +#elif defined HSA_LITTLE_ENDIAN + /** + * Starting address of the HSA runtime-allocated buffer used to store the AQL + * packets. Must be aligned to the size of an AQL packet. + */ + void* base_address; + /** + * Reserved. Must be 0. + */ + uint32_t reserved0; +#else + uint32_t reserved0; + void* base_address; +#endif + + /** + * Signal object used by the application to indicate the ID of a packet that + * is ready to be processed. The HSA runtime manages the doorbell signal. If + * the application tries to replace or destroy this signal, the behavior is + * undefined. + * + * If @a type is ::HSA_QUEUE_TYPE_SINGLE, the doorbell signal value must be + * updated in a monotonically increasing fashion. If @a type is + * ::HSA_QUEUE_TYPE_MULTI, the doorbell signal value can be updated with any + * value. + */ + hsa_signal_t doorbell_signal; + + /** + * Maximum number of packets the queue can hold. Must be a power of 2. + */ + uint32_t size; + /** + * Reserved. Must be 0. + */ + uint32_t reserved1; + /** + * Queue identifier, which is unique over the lifetime of the application. + */ + uint64_t id; + +} hsa_queue_t; + +/** + * @brief Create a user mode queue. + * + * @details The HSA runtime creates the queue structure, the underlying packet + * buffer, the completion signal, and the write and read indexes. The initial + * value of the write and read indexes is 0. The type of every packet in the + * buffer is initialized to ::HSA_PACKET_TYPE_INVALID. + * + * The application should only rely on the error code returned to determine if + * the queue is valid. + * + * @param[in] agent Agent where to create the queue. + * + * @param[in] size Number of packets the queue is expected to + * hold. Must be a power of 2 between 1 and the value of + * ::HSA_AGENT_INFO_QUEUE_MAX_SIZE in @p agent. The size of the newly + * created queue is the maximum of @p size and the value of + * ::HSA_AGENT_INFO_QUEUE_MIN_SIZE in @p agent. + * + * @param[in] type Type of the queue, a bitwise OR of hsa_queue_type_t values. + * If the value of ::HSA_AGENT_INFO_QUEUE_TYPE in @p agent is ::HSA_QUEUE_TYPE_SINGLE, + * then @p type must also be ::HSA_QUEUE_TYPE_SINGLE. + * + * @param[in] callback Callback invoked by the HSA runtime for every + * asynchronous event related to the newly created queue. May be NULL. The HSA + * runtime passes three arguments to the callback: a code identifying the event + * that triggered the invocation, a pointer to the queue where the event + * originated, and the application data. + * + * @param[in] data Application data that is passed to @p callback on every + * iteration. May be NULL. + * + * @param[in] private_segment_size Hint indicating the maximum + * expected private segment usage per work-item, in bytes. There may + * be performance degradation if the application places a kernel + * dispatch packet in the queue and the corresponding private segment + * usage exceeds @p private_segment_size. If the application does not + * want to specify any particular value for this argument, @p + * private_segment_size must be UINT32_MAX. If the queue does not + * support kernel dispatch packets, this argument is ignored. + * + * @param[in] group_segment_size Hint indicating the maximum expected + * group segment usage per work-group, in bytes. There may be + * performance degradation if the application places a kernel dispatch + * packet in the queue and the corresponding group segment usage + * exceeds @p group_segment_size. If the application does not want to + * specify any particular value for this argument, @p + * group_segment_size must be UINT32_MAX. If the queue does not + * support kernel dispatch packets, this argument is ignored. + * + * @param[out] queue Memory location where the HSA runtime stores a pointer to + * the newly created queue. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to allocate + * the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_QUEUE_CREATION @p agent does not + * support queues of the given type. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p size is not a power of two, + * @p size is 0, @p type is an invalid queue type, or @p queue is NULL. + * + */ +hsa_status_t HSA_API hsa_queue_create( + hsa_agent_t agent, + uint32_t size, + hsa_queue_type32_t type, + void (*callback)(hsa_status_t status, hsa_queue_t *source, void *data), + void *data, + uint32_t private_segment_size, + uint32_t group_segment_size, + hsa_queue_t **queue); + +/** + * @brief Create a queue for which the application or a kernel is responsible + * for processing the AQL packets. + * + * @details The application can use this function to create queues where AQL + * packets are not parsed by the packet processor associated with an agent, + * but rather by a unit of execution running on that agent (for example, a + * thread in the host application). + * + * The application is responsible for ensuring that all the producers and + * consumers of the resulting queue can access the provided doorbell signal + * and memory region. The application is also responsible for ensuring that the + * unit of execution processing the queue packets supports the indicated + * features (AQL packet types). + * + * When the queue is created, the HSA runtime allocates the packet buffer using + * @p region, and the write and read indexes. The initial value of the write and + * read indexes is 0, and the type of every packet in the buffer is initialized + * to ::HSA_PACKET_TYPE_INVALID. The value of the @e size, @e type, @e features, + * and @e doorbell_signal fields in the returned queue match the values passed + * by the application. + * + * @param[in] region Memory region that the HSA runtime should use to allocate + * the AQL packet buffer and any other queue metadata. + * + * @param[in] size Number of packets the queue is expected to hold. Must be a + * power of 2 greater than 0. + * + * @param[in] type Queue type. + * + * @param[in] features Supported queue features. This is a bit-field of + * ::hsa_queue_feature_t values. + * + * @param[in] doorbell_signal Doorbell signal that the HSA runtime must + * associate with the returned queue. The signal handle must not be 0. + * + * @param[out] queue Memory location where the HSA runtime stores a pointer to + * the newly created queue. The application should not rely on the value + * returned for this argument but only in the status code to determine if the + * queue is valid. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to allocate + * the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p size is not a power of two, @p + * size is 0, @p type is an invalid queue type, the doorbell signal handle is + * 0, or @p queue is NULL. + * + */ +hsa_status_t HSA_API hsa_soft_queue_create( + hsa_region_t region, + uint32_t size, + hsa_queue_type32_t type, + uint32_t features, + hsa_signal_t doorbell_signal, + hsa_queue_t **queue); + +/** + * @brief Destroy a user mode queue. + * + * @details When a queue is destroyed, the state of the AQL packets that have + * not been yet fully processed (their completion phase has not finished) + * becomes undefined. It is the responsibility of the application to ensure that + * all pending queue operations are finished if their results are required. + * + * The resources allocated by the HSA runtime during queue creation (queue + * structure, ring buffer, doorbell signal) are released. The queue should not + * be accessed after being destroyed. + * + * @param[in] queue Pointer to a queue created using ::hsa_queue_create. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_QUEUE The queue is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p queue is NULL. + */ +hsa_status_t HSA_API hsa_queue_destroy( + hsa_queue_t *queue); + +/** + * @brief Inactivate a queue. + * + * @details Inactivating the queue aborts any pending executions and prevent any + * new packets from being processed. Any more packets written to the queue once + * it is inactivated will be ignored by the packet processor. + * + * @param[in] queue Pointer to a queue. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_QUEUE The queue is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p queue is NULL. + */ +hsa_status_t HSA_API hsa_queue_inactivate( + hsa_queue_t *queue); + +/** + * @deprecated Renamed as ::hsa_queue_load_read_index_scacquire. + * + * @copydoc hsa_queue_load_read_index_scacquire + */ +uint64_t HSA_API HSA_DEPRECATED hsa_queue_load_read_index_acquire( + const hsa_queue_t *queue); + +/** + * @brief Atomically load the read index of a queue. + * + * @param[in] queue Pointer to a queue. + * + * @return Read index of the queue pointed by @p queue. + */ +uint64_t HSA_API hsa_queue_load_read_index_scacquire( + const hsa_queue_t *queue); + +/** + * @copydoc hsa_queue_load_read_index_scacquire + */ +uint64_t HSA_API hsa_queue_load_read_index_relaxed( + const hsa_queue_t *queue); + +/** + * @deprecated Renamed as ::hsa_queue_load_write_index_scacquire. + * + * @copydoc hsa_queue_load_write_index_scacquire + */ +uint64_t HSA_API HSA_DEPRECATED hsa_queue_load_write_index_acquire( + const hsa_queue_t *queue); + +/** + * @brief Atomically load the write index of a queue. + * + * @param[in] queue Pointer to a queue. + * + * @return Write index of the queue pointed by @p queue. + */ +uint64_t HSA_API hsa_queue_load_write_index_scacquire( + const hsa_queue_t *queue); + +/** + * @copydoc hsa_queue_load_write_index_scacquire + */ +uint64_t HSA_API hsa_queue_load_write_index_relaxed( + const hsa_queue_t *queue); + +/** + * @brief Atomically set the write index of a queue. + * + * @details It is recommended that the application uses this function to update + * the write index when there is a single agent submitting work to the queue + * (the queue type is ::HSA_QUEUE_TYPE_SINGLE). + * + * @param[in] queue Pointer to a queue. + * + * @param[in] value Value to assign to the write index. + * + */ +void HSA_API hsa_queue_store_write_index_relaxed( + const hsa_queue_t *queue, + uint64_t value); + +/** + * @deprecated Renamed as ::hsa_queue_store_write_index_screlease. + * + * @copydoc hsa_queue_store_write_index_screlease + */ +void HSA_API HSA_DEPRECATED hsa_queue_store_write_index_release( + const hsa_queue_t *queue, + uint64_t value); + +/** + * @copydoc hsa_queue_store_write_index_relaxed + */ +void HSA_API hsa_queue_store_write_index_screlease( + const hsa_queue_t *queue, + uint64_t value); + +/** + * @deprecated Renamed as ::hsa_queue_cas_write_index_scacq_screl. + * + * @copydoc hsa_queue_cas_write_index_scacq_screl + */ +uint64_t HSA_API HSA_DEPRECATED hsa_queue_cas_write_index_acq_rel( + const hsa_queue_t *queue, + uint64_t expected, + uint64_t value); + +/** + * @brief Atomically set the write index of a queue if the observed value is + * equal to the expected value. The application can inspect the returned value + * to determine if the replacement was done. + * + * @param[in] queue Pointer to a queue. + * + * @param[in] expected Expected value. + * + * @param[in] value Value to assign to the write index if @p expected matches + * the observed write index. Must be greater than @p expected. + * + * @return Previous value of the write index. + */ +uint64_t HSA_API hsa_queue_cas_write_index_scacq_screl( + const hsa_queue_t *queue, + uint64_t expected, + uint64_t value); + +/** + * @deprecated Renamed as ::hsa_queue_cas_write_index_scacquire. + * + * @copydoc hsa_queue_cas_write_index_scacquire + */ +uint64_t HSA_API HSA_DEPRECATED hsa_queue_cas_write_index_acquire( + const hsa_queue_t *queue, + uint64_t expected, + uint64_t value); + +/** + * @copydoc hsa_queue_cas_write_index_scacq_screl + */ +uint64_t HSA_API hsa_queue_cas_write_index_scacquire( + const hsa_queue_t *queue, + uint64_t expected, + uint64_t value); + +/** + * @copydoc hsa_queue_cas_write_index_scacq_screl + */ +uint64_t HSA_API hsa_queue_cas_write_index_relaxed( + const hsa_queue_t *queue, + uint64_t expected, + uint64_t value); + +/** + * @deprecated Renamed as ::hsa_queue_cas_write_index_screlease. + * + * @copydoc hsa_queue_cas_write_index_screlease + */ +uint64_t HSA_API HSA_DEPRECATED hsa_queue_cas_write_index_release( + const hsa_queue_t *queue, + uint64_t expected, + uint64_t value); + +/** + * @copydoc hsa_queue_cas_write_index_scacq_screl + */ +uint64_t HSA_API hsa_queue_cas_write_index_screlease( + const hsa_queue_t *queue, + uint64_t expected, + uint64_t value); + +/** + * @deprecated Renamed as ::hsa_queue_add_write_index_scacq_screl. + * + * @copydoc hsa_queue_add_write_index_scacq_screl + */ +uint64_t HSA_API HSA_DEPRECATED hsa_queue_add_write_index_acq_rel( + const hsa_queue_t *queue, + uint64_t value); + +/** + * @brief Atomically increment the write index of a queue by an offset. + * + * @param[in] queue Pointer to a queue. + * + * @param[in] value Value to add to the write index. + * + * @return Previous value of the write index. + */ +uint64_t HSA_API hsa_queue_add_write_index_scacq_screl( + const hsa_queue_t *queue, + uint64_t value); + +/** + * @deprecated Renamed as ::hsa_queue_add_write_index_scacquire. + * + * @copydoc hsa_queue_add_write_index_scacquire + */ +uint64_t HSA_API HSA_DEPRECATED hsa_queue_add_write_index_acquire( + const hsa_queue_t *queue, + uint64_t value); + +/** + * @copydoc hsa_queue_add_write_index_scacq_screl + */ +uint64_t HSA_API hsa_queue_add_write_index_scacquire( + const hsa_queue_t *queue, + uint64_t value); + +/** + * @copydoc hsa_queue_add_write_index_scacq_screl + */ +uint64_t HSA_API hsa_queue_add_write_index_relaxed( + const hsa_queue_t *queue, + uint64_t value); + +/** + * @deprecated Renamed as ::hsa_queue_add_write_index_screlease. + * + * @copydoc hsa_queue_add_write_index_screlease + */ +uint64_t HSA_API HSA_DEPRECATED hsa_queue_add_write_index_release( + const hsa_queue_t *queue, + uint64_t value); + +/** + * @copydoc hsa_queue_add_write_index_scacq_screl + */ +uint64_t HSA_API hsa_queue_add_write_index_screlease( + const hsa_queue_t *queue, + uint64_t value); + +/** + * @brief Atomically set the read index of a queue. + * + * @details Modifications of the read index are not allowed and result in + * undefined behavior if the queue is associated with an agent for which + * only the corresponding packet processor is permitted to update the read + * index. + * + * @param[in] queue Pointer to a queue. + * + * @param[in] value Value to assign to the read index. + * + */ +void HSA_API hsa_queue_store_read_index_relaxed( + const hsa_queue_t *queue, + uint64_t value); + +/** + * @deprecated Renamed as ::hsa_queue_store_read_index_screlease. + * + * @copydoc hsa_queue_store_read_index_screlease + */ +void HSA_API HSA_DEPRECATED hsa_queue_store_read_index_release( + const hsa_queue_t *queue, + uint64_t value); + +/** + * @copydoc hsa_queue_store_read_index_relaxed + */ +void HSA_API hsa_queue_store_read_index_screlease( + const hsa_queue_t *queue, + uint64_t value); +/** @} */ + + +/** \defgroup aql Architected Queuing Language + * @{ + */ + +/** + * @brief Packet type. + */ +typedef enum { + /** + * Vendor-specific packet. + */ + HSA_PACKET_TYPE_VENDOR_SPECIFIC = 0, + /** + * The packet has been processed in the past, but has not been reassigned to + * the packet processor. A packet processor must not process a packet of this + * type. All queues support this packet type. + */ + HSA_PACKET_TYPE_INVALID = 1, + /** + * Packet used by agents for dispatching jobs to kernel agents. Not all + * queues support packets of this type (see ::hsa_queue_feature_t). + */ + HSA_PACKET_TYPE_KERNEL_DISPATCH = 2, + /** + * Packet used by agents to delay processing of subsequent packets, and to + * express complex dependencies between multiple packets. All queues support + * this packet type. + */ + HSA_PACKET_TYPE_BARRIER_AND = 3, + /** + * Packet used by agents for dispatching jobs to agents. Not all + * queues support packets of this type (see ::hsa_queue_feature_t). + */ + HSA_PACKET_TYPE_AGENT_DISPATCH = 4, + /** + * Packet used by agents to delay processing of subsequent packets, and to + * express complex dependencies between multiple packets. All queues support + * this packet type. + */ + HSA_PACKET_TYPE_BARRIER_OR = 5 +} hsa_packet_type_t; + +/** + * @brief Scope of the memory fence operation associated with a packet. + */ +typedef enum { + /** + * No scope (no fence is applied). The packet relies on external fences to + * ensure visibility of memory updates. + */ + HSA_FENCE_SCOPE_NONE = 0, + /** + * The fence is applied with agent scope for the global segment. + */ + HSA_FENCE_SCOPE_AGENT = 1, + /** + * The fence is applied across both agent and system scope for the global + * segment. + */ + HSA_FENCE_SCOPE_SYSTEM = 2 +} hsa_fence_scope_t; + +/** + * @brief Sub-fields of the @a header field that is present in any AQL + * packet. The offset (with respect to the address of @a header) of a sub-field + * is identical to its enumeration constant. The width of each sub-field is + * determined by the corresponding value in ::hsa_packet_header_width_t. The + * offset and the width are expressed in bits. + */ + typedef enum { + /** + * Packet type. The value of this sub-field must be one of + * ::hsa_packet_type_t. If the type is ::HSA_PACKET_TYPE_VENDOR_SPECIFIC, the + * packet layout is vendor-specific. + */ + HSA_PACKET_HEADER_TYPE = 0, + /** + * Barrier bit. If the barrier bit is set, the processing of the current + * packet only launches when all preceding packets (within the same queue) are + * complete. + */ + HSA_PACKET_HEADER_BARRIER = 8, + /** + * Acquire fence scope. The value of this sub-field determines the scope and + * type of the memory fence operation applied before the packet enters the + * active phase. An acquire fence ensures that any subsequent global segment + * or image loads by any unit of execution that belongs to a dispatch that has + * not yet entered the active phase on any queue of the same kernel agent, + * sees any data previously released at the scopes specified by the acquire + * fence. The value of this sub-field must be one of ::hsa_fence_scope_t. + */ + HSA_PACKET_HEADER_SCACQUIRE_FENCE_SCOPE = 9, + /** + * @deprecated Renamed as ::HSA_PACKET_HEADER_SCACQUIRE_FENCE_SCOPE. + */ + HSA_PACKET_HEADER_ACQUIRE_FENCE_SCOPE = 9, + /** + * Release fence scope, The value of this sub-field determines the scope and + * type of the memory fence operation applied after kernel completion but + * before the packet is completed. A release fence makes any global segment or + * image data that was stored by any unit of execution that belonged to a + * dispatch that has completed the active phase on any queue of the same + * kernel agent visible in all the scopes specified by the release fence. The + * value of this sub-field must be one of ::hsa_fence_scope_t. + */ + HSA_PACKET_HEADER_SCRELEASE_FENCE_SCOPE = 11, + /** + * @deprecated Renamed as ::HSA_PACKET_HEADER_SCRELEASE_FENCE_SCOPE. + */ + HSA_PACKET_HEADER_RELEASE_FENCE_SCOPE = 11 + } hsa_packet_header_t; + +/** + * @brief Width (in bits) of the sub-fields in ::hsa_packet_header_t. + */ + typedef enum { + HSA_PACKET_HEADER_WIDTH_TYPE = 8, + HSA_PACKET_HEADER_WIDTH_BARRIER = 1, + HSA_PACKET_HEADER_WIDTH_SCACQUIRE_FENCE_SCOPE = 2, + /** + * @deprecated Use HSA_PACKET_HEADER_WIDTH_SCACQUIRE_FENCE_SCOPE. + */ + HSA_PACKET_HEADER_WIDTH_ACQUIRE_FENCE_SCOPE = 2, + HSA_PACKET_HEADER_WIDTH_SCRELEASE_FENCE_SCOPE = 2, + /** + * @deprecated Use HSA_PACKET_HEADER_WIDTH_SCRELEASE_FENCE_SCOPE. + */ + HSA_PACKET_HEADER_WIDTH_RELEASE_FENCE_SCOPE = 2 + } hsa_packet_header_width_t; + +/** + * @brief Sub-fields of the kernel dispatch packet @a setup field. The offset + * (with respect to the address of @a setup) of a sub-field is identical to its + * enumeration constant. The width of each sub-field is determined by the + * corresponding value in ::hsa_kernel_dispatch_packet_setup_width_t. The + * offset and the width are expressed in bits. + */ + typedef enum { + /** + * Number of dimensions of the grid. Valid values are 1, 2, or 3. + * + */ + HSA_KERNEL_DISPATCH_PACKET_SETUP_DIMENSIONS = 0 + } hsa_kernel_dispatch_packet_setup_t; + +/** + * @brief Width (in bits) of the sub-fields in + * ::hsa_kernel_dispatch_packet_setup_t. + */ + typedef enum { + HSA_KERNEL_DISPATCH_PACKET_SETUP_WIDTH_DIMENSIONS = 2 + } hsa_kernel_dispatch_packet_setup_width_t; + +/** + * @brief AQL kernel dispatch packet + */ +typedef struct hsa_kernel_dispatch_packet_s { + /** + * Packet header. Used to configure multiple packet parameters such as the + * packet type. The parameters are described by ::hsa_packet_header_t. + */ + uint16_t header; + + /** + * Dispatch setup parameters. Used to configure kernel dispatch parameters + * such as the number of dimensions in the grid. The parameters are described + * by ::hsa_kernel_dispatch_packet_setup_t. + */ + uint16_t setup; + + /** + * X dimension of work-group, in work-items. Must be greater than 0. + */ + uint16_t workgroup_size_x; + + /** + * Y dimension of work-group, in work-items. Must be greater than + * 0. If the grid has 1 dimension, the only valid value is 1. + */ + uint16_t workgroup_size_y; + + /** + * Z dimension of work-group, in work-items. Must be greater than + * 0. If the grid has 1 or 2 dimensions, the only valid value is 1. + */ + uint16_t workgroup_size_z; + + /** + * Reserved. Must be 0. + */ + uint16_t reserved0; + + /** + * X dimension of grid, in work-items. Must be greater than 0. Must + * not be smaller than @a workgroup_size_x. + */ + uint32_t grid_size_x; + + /** + * Y dimension of grid, in work-items. Must be greater than 0. If the grid has + * 1 dimension, the only valid value is 1. Must not be smaller than @a + * workgroup_size_y. + */ + uint32_t grid_size_y; + + /** + * Z dimension of grid, in work-items. Must be greater than 0. If the grid has + * 1 or 2 dimensions, the only valid value is 1. Must not be smaller than @a + * workgroup_size_z. + */ + uint32_t grid_size_z; + + /** + * Size in bytes of private memory allocation request (per work-item). + */ + uint32_t private_segment_size; + + /** + * Size in bytes of group memory allocation request (per work-group). Must not + * be less than the sum of the group memory used by the kernel (and the + * functions it calls directly or indirectly) and the dynamically allocated + * group segment variables. + */ + uint32_t group_segment_size; + + /** + * Opaque handle to a code object that includes an implementation-defined + * executable code for the kernel. + */ + uint64_t kernel_object; + +#ifdef HSA_LARGE_MODEL + void* kernarg_address; +#elif defined HSA_LITTLE_ENDIAN + /** + * Pointer to a buffer containing the kernel arguments. May be NULL. + * + * The buffer must be allocated using ::hsa_memory_allocate, and must not be + * modified once the kernel dispatch packet is enqueued until the dispatch has + * completed execution. + */ + void* kernarg_address; + /** + * Reserved. Must be 0. + */ + uint32_t reserved1; +#else + uint32_t reserved1; + void* kernarg_address; +#endif + + /** + * Reserved. Must be 0. + */ + uint64_t reserved2; + + /** + * Signal used to indicate completion of the job. The application can use the + * special signal handle 0 to indicate that no signal is used. + */ + hsa_signal_t completion_signal; + +} hsa_kernel_dispatch_packet_t; + +/** + * @brief Agent dispatch packet. + */ +typedef struct hsa_agent_dispatch_packet_s { + /** + * Packet header. Used to configure multiple packet parameters such as the + * packet type. The parameters are described by ::hsa_packet_header_t. + */ + uint16_t header; + + /** + * Application-defined function to be performed by the destination agent. + */ + uint16_t type; + + /** + * Reserved. Must be 0. + */ + uint32_t reserved0; + +#ifdef HSA_LARGE_MODEL + void* return_address; +#elif defined HSA_LITTLE_ENDIAN + /** + * Address where to store the function return values, if any. + */ + void* return_address; + /** + * Reserved. Must be 0. + */ + uint32_t reserved1; +#else + uint32_t reserved1; + void* return_address; +#endif + + /** + * Function arguments. + */ + uint64_t arg[4]; + + /** + * Reserved. Must be 0. + */ + uint64_t reserved2; + + /** + * Signal used to indicate completion of the job. The application can use the + * special signal handle 0 to indicate that no signal is used. + */ + hsa_signal_t completion_signal; + +} hsa_agent_dispatch_packet_t; + +/** + * @brief Barrier-AND packet. + */ +typedef struct hsa_barrier_and_packet_s { + /** + * Packet header. Used to configure multiple packet parameters such as the + * packet type. The parameters are described by ::hsa_packet_header_t. + */ + uint16_t header; + + /** + * Reserved. Must be 0. + */ + uint16_t reserved0; + + /** + * Reserved. Must be 0. + */ + uint32_t reserved1; + + /** + * Array of dependent signal objects. Signals with a handle value of 0 are + * allowed and are interpreted by the packet processor as satisfied + * dependencies. + */ + hsa_signal_t dep_signal[5]; + + /** + * Reserved. Must be 0. + */ + uint64_t reserved2; + + /** + * Signal used to indicate completion of the job. The application can use the + * special signal handle 0 to indicate that no signal is used. + */ + hsa_signal_t completion_signal; + +} hsa_barrier_and_packet_t; + +/** + * @brief Barrier-OR packet. + */ +typedef struct hsa_barrier_or_packet_s { + /** + * Packet header. Used to configure multiple packet parameters such as the + * packet type. The parameters are described by ::hsa_packet_header_t. + */ + uint16_t header; + + /** + * Reserved. Must be 0. + */ + uint16_t reserved0; + + /** + * Reserved. Must be 0. + */ + uint32_t reserved1; + + /** + * Array of dependent signal objects. Signals with a handle value of 0 are + * allowed and are interpreted by the packet processor as dependencies not + * satisfied. + */ + hsa_signal_t dep_signal[5]; + + /** + * Reserved. Must be 0. + */ + uint64_t reserved2; + + /** + * Signal used to indicate completion of the job. The application can use the + * special signal handle 0 to indicate that no signal is used. + */ + hsa_signal_t completion_signal; + +} hsa_barrier_or_packet_t; + +/** @} */ + +/** \addtogroup memory Memory + * @{ + */ + +/** + * @brief Memory segments associated with a region. + */ +typedef enum { + /** + * Global segment. Used to hold data that is shared by all agents. + */ + HSA_REGION_SEGMENT_GLOBAL = 0, + /** + * Read-only segment. Used to hold data that remains constant during the + * execution of a kernel. + */ + HSA_REGION_SEGMENT_READONLY = 1, + /** + * Private segment. Used to hold data that is local to a single work-item. + */ + HSA_REGION_SEGMENT_PRIVATE = 2, + /** + * Group segment. Used to hold data that is shared by the work-items of a + * work-group. + */ + HSA_REGION_SEGMENT_GROUP = 3, + /** + * Kernarg segment. Used to store kernel arguments. + */ + HSA_REGION_SEGMENT_KERNARG = 4 +} hsa_region_segment_t; + +/** + * @brief Global region flags. + */ +typedef enum { + /** + * The application can use memory in the region to store kernel arguments, and + * provide the values for the kernarg segment of a kernel dispatch. If this + * flag is set, then ::HSA_REGION_GLOBAL_FLAG_FINE_GRAINED must be set. + */ + HSA_REGION_GLOBAL_FLAG_KERNARG = 1, + /** + * Updates to memory in this region are immediately visible to all the + * agents under the terms of the HSA memory model. If this + * flag is set, then ::HSA_REGION_GLOBAL_FLAG_COARSE_GRAINED must not be set. + */ + HSA_REGION_GLOBAL_FLAG_FINE_GRAINED = 2, + /** + * Updates to memory in this region can be performed by a single agent at + * a time. If a different agent in the system is allowed to access the + * region, the application must explicitely invoke ::hsa_memory_assign_agent + * in order to transfer ownership to that agent for a particular buffer. + */ + HSA_REGION_GLOBAL_FLAG_COARSE_GRAINED = 4, + + /** + * Updates to memory in this region have extended scope, where the device-scope atomics + * to this memory type act as system-scope with respect to all variables located in + * memory regions of this type. + * Note: On non-compliant systems, the application may still be responsible for performing + * device-specific actions necessary to achieve system-scope coherence. + */ + HSA_REGION_GLOBAL_FLAG_EXTENDED_SCOPE_FINE_GRAINED = 8 +} hsa_region_global_flag_t; + +/** + * @brief Attributes of a memory region. + */ +typedef enum { + /** + * Segment where memory in the region can be used. The type of this + * attribute is ::hsa_region_segment_t. + */ + HSA_REGION_INFO_SEGMENT = 0, + /** + * Flag mask. The value of this attribute is undefined if the value of + * ::HSA_REGION_INFO_SEGMENT is not ::HSA_REGION_SEGMENT_GLOBAL. The type of + * this attribute is uint32_t, a bit-field of ::hsa_region_global_flag_t + * values. + */ + HSA_REGION_INFO_GLOBAL_FLAGS = 1, + /** + * Size of this region, in bytes. The type of this attribute is size_t. + */ + HSA_REGION_INFO_SIZE = 2, + /** + * Maximum allocation size in this region, in bytes. Must not exceed the value + * of ::HSA_REGION_INFO_SIZE. The type of this attribute is size_t. + * + * If the region is in the global or readonly segments, this is the maximum + * size that the application can pass to ::hsa_memory_allocate. + * + * If the region is in the group segment, this is the maximum size (per + * work-group) that can be requested for a given kernel dispatch. If the + * region is in the private segment, this is the maximum size (per work-item) + * that can be requested for a specific kernel dispatch, and must be at least + * 256 bytes. + */ + HSA_REGION_INFO_ALLOC_MAX_SIZE = 4, + /** + * Maximum size (per work-group) of private memory that can be requested for a + * specific kernel dispatch. Must be at least 65536 bytes. The type of this + * attribute is uint32_t. The value of this attribute is undefined if the + * region is not in the private segment. + */ + HSA_REGION_INFO_ALLOC_MAX_PRIVATE_WORKGROUP_SIZE = 8, + /** + * Indicates whether memory in this region can be allocated using + * ::hsa_memory_allocate. The type of this attribute is bool. + * + * The value of this flag is always false for regions in the group and private + * segments. + */ + HSA_REGION_INFO_RUNTIME_ALLOC_ALLOWED = 5, + /** + * Allocation granularity of buffers allocated by ::hsa_memory_allocate in + * this region. The size of a buffer allocated in this region is a multiple of + * the value of this attribute. The value of this attribute is only defined if + * ::HSA_REGION_INFO_RUNTIME_ALLOC_ALLOWED is true for this region. The type + * of this attribute is size_t. + */ + HSA_REGION_INFO_RUNTIME_ALLOC_GRANULE = 6, + /** + * Alignment of buffers allocated by ::hsa_memory_allocate in this region. The + * value of this attribute is only defined if + * ::HSA_REGION_INFO_RUNTIME_ALLOC_ALLOWED is true for this region, and must be + * a power of 2. The type of this attribute is size_t. + */ + HSA_REGION_INFO_RUNTIME_ALLOC_ALIGNMENT = 7 +} hsa_region_info_t; + +/** + * @brief Get the current value of an attribute of a region. + * + * @param[in] region A valid region. + * + * @param[in] attribute Attribute to query. + * + * @param[out] value Pointer to a application-allocated buffer where to store + * the value of the attribute. If the buffer passed by the application is not + * large enough to hold the value of @p attribute, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_REGION The region is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p attribute is an invalid + * region attribute, or @p value is NULL. + */ +hsa_status_t HSA_API hsa_region_get_info( + hsa_region_t region, + hsa_region_info_t attribute, + void* value); + +/** + * @brief Iterate over the memory regions associated with a given agent, and + * invoke an application-defined callback on every iteration. + * + * @param[in] agent A valid agent. + * + * @param[in] callback Callback to be invoked once per region that is + * accessible from the agent. The HSA runtime passes two arguments to the + * callback, the region and the application data. If @p callback returns a + * status other than ::HSA_STATUS_SUCCESS for a particular iteration, the + * traversal stops and ::hsa_agent_iterate_regions returns that status value. + * + * @param[in] data Application data that is passed to @p callback on every + * iteration. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p callback is NULL. + */ +hsa_status_t HSA_API hsa_agent_iterate_regions( + hsa_agent_t agent, + hsa_status_t (*callback)(hsa_region_t region, void* data), + void* data); + +/** + * @brief Allocate a block of memory in a given region. + * + * @param[in] region Region where to allocate memory from. The region must have + * the ::HSA_REGION_INFO_RUNTIME_ALLOC_ALLOWED flag set. + * + * @param[in] size Allocation size, in bytes. Must not be zero. This value is + * rounded up to the nearest multiple of ::HSA_REGION_INFO_RUNTIME_ALLOC_GRANULE + * in @p region. + * + * @param[out] ptr Pointer to the location where to store the base address of + * the allocated block. The returned base address is aligned to the value of + * ::HSA_REGION_INFO_RUNTIME_ALLOC_ALIGNMENT in @p region. If the allocation + * fails, the returned value is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to allocate + * the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_REGION The region is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ALLOCATION The host is not allowed to + * allocate memory in @p region, or @p size is greater than the value of + * HSA_REGION_INFO_ALLOC_MAX_SIZE in @p region. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p ptr is NULL, or @p size is 0. + */ +hsa_status_t HSA_API hsa_memory_allocate(hsa_region_t region, + size_t size, + void** ptr); + +/** + * @brief Deallocate a block of memory previously allocated using + * ::hsa_memory_allocate. + * + * @param[in] ptr Pointer to a memory block. If @p ptr does not match a value + * previously returned by ::hsa_memory_allocate, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + */ +hsa_status_t HSA_API hsa_memory_free(void* ptr); + +/** + * @brief Copy a block of memory from the location pointed to by @p src to the + * memory block pointed to by @p dst. + * + * @param[out] dst Buffer where the content is to be copied. If @p dst is in + * coarse-grained memory, the copied data is only visible to the agent currently + * assigned (::hsa_memory_assign_agent) to @p dst. + * + * @param[in] src A valid pointer to the source of data to be copied. The source + * buffer must not overlap with the destination buffer. If the source buffer is + * in coarse-grained memory then it must be assigned to an agent, from which the + * data will be retrieved. + * + * @param[in] size Number of bytes to copy. If @p size is 0, no copy is + * performed and the function returns success. Copying a number of bytes larger + * than the size of the buffers pointed by @p dst or @p src results in undefined + * behavior. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT The source or destination + * pointers are NULL. + */ +hsa_status_t HSA_API hsa_memory_copy( + void *dst, + const void *src, + size_t size); + +/** + * @brief Change the ownership of a global, coarse-grained buffer. + * + * @details The contents of a coarse-grained buffer are visible to an agent + * only after ownership has been explicitely transferred to that agent. Once the + * operation completes, the previous owner cannot longer access the data in the + * buffer. + * + * An implementation of the HSA runtime is allowed, but not required, to change + * the physical location of the buffer when ownership is transferred to a + * different agent. In general the application must not assume this + * behavior. The virtual location (address) of the passed buffer is never + * modified. + * + * @param[in] ptr Base address of a global buffer. The pointer must match an + * address previously returned by ::hsa_memory_allocate. The size of the buffer + * affected by the ownership change is identical to the size of that previous + * allocation. If @p ptr points to a fine-grained global buffer, no operation is + * performed and the function returns success. If @p ptr does not point to + * global memory, the behavior is undefined. + * + * @param[in] agent Agent that becomes the owner of the buffer. The + * application is responsible for ensuring that @p agent has access to the + * region that contains the buffer. It is allowed to change ownership to an + * agent that is already the owner of the buffer, with the same or different + * access permissions. + * + * @param[in] access Access permissions requested for the new owner. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to allocate + * the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p ptr is NULL, or @p access is + * not a valid access value. + */ +hsa_status_t HSA_API hsa_memory_assign_agent( + void *ptr, + hsa_agent_t agent, + hsa_access_permission_t access); + +/** + * + * @brief Register a global, fine-grained buffer. + * + * @details Registering a buffer serves as an indication to the HSA runtime that + * the memory might be accessed from a kernel agent other than the + * host. Registration is a performance hint that allows the HSA runtime + * implementation to know which buffers will be accessed by some of the kernel + * agents ahead of time. + * + * Registration is only recommended for buffers in the global segment that have + * not been allocated using the HSA allocator (::hsa_memory_allocate), but an OS + * allocator instead. Registering an OS-allocated buffer in the base profile is + * equivalent to a no-op. + * + * Registrations should not overlap. + * + * @param[in] ptr A buffer in global, fine-grained memory. If a NULL pointer is + * passed, no operation is performed. If the buffer has been allocated using + * ::hsa_memory_allocate, or has already been registered, no operation is + * performed. + * + * @param[in] size Requested registration size in bytes. A size of 0 is + * only allowed if @p ptr is NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to allocate + * the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p size is 0 but @p ptr + * is not NULL. + */ +hsa_status_t HSA_API hsa_memory_register( + void *ptr, + size_t size); + +/** + * + * @brief Deregister memory previously registered using ::hsa_memory_register. + * + * @details If the memory interval being deregistered does not match a previous + * registration (start and end addresses), the behavior is undefined. + * + * @param[in] ptr A pointer to the base of the buffer to be deregistered. If + * a NULL pointer is passed, no operation is performed. + * + * @param[in] size Size of the buffer to be deregistered. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + */ +hsa_status_t HSA_API hsa_memory_deregister( + void *ptr, + size_t size); + +/** @} */ + + +/** \defgroup instruction-set-architecture Instruction Set Architecture. + * @{ + */ + +/** + * @brief Instruction set architecture. + */ +typedef struct hsa_isa_s { + /** + * Opaque handle. Two handles reference the same object of the enclosing type + * if and only if they are equal. + */ + uint64_t handle; +} hsa_isa_t; + +/** + * @brief Retrieve a reference to an instruction set architecture handle out of + * a symbolic name. + * + * @param[in] name Vendor-specific name associated with a particular + * instruction set architecture. @p name must start with the vendor name and a + * colon (for example, "AMD:"). The rest of the name is vendor-specific. Must be + * a NUL-terminated string. + * + * @param[out] isa Memory location where the HSA runtime stores the ISA handle + * corresponding to the given name. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ISA_NAME The given name does not + * correspond to any instruction set architecture. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to + * allocate the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p name is NULL, or @p isa is + * NULL. + */ +hsa_status_t HSA_API hsa_isa_from_name( + const char *name, + hsa_isa_t *isa); + +/** + * @brief Iterate over the instruction sets supported by the given agent, and + * invoke an application-defined callback on every iteration. The iterator is + * deterministic: if an agent supports several instruction set architectures, + * they are traversed in the same order in every invocation of this function. + * + * @param[in] agent A valid agent. + * + * @param[in] callback Callback to be invoked once per instruction set + * architecture. The HSA runtime passes two arguments to the callback: the + * ISA and the application data. If @p callback returns a status other than + * ::HSA_STATUS_SUCCESS for a particular iteration, the traversal stops and + * that status value is returned. + * + * @param[in] data Application data that is passed to @p callback on every + * iteration. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p callback is NULL. + */ +hsa_status_t HSA_API hsa_agent_iterate_isas( + hsa_agent_t agent, + hsa_status_t (*callback)(hsa_isa_t isa, void *data), + void *data); + +/** + * @brief Instruction set architecture attributes. + */ +typedef enum { + /** + * The length of the ISA name in bytes, not including the NUL terminator. The + * type of this attribute is uint32_t. + */ + HSA_ISA_INFO_NAME_LENGTH = 0, + /** + * Human-readable description. The type of this attribute is character array + * with the length equal to the value of ::HSA_ISA_INFO_NAME_LENGTH attribute. + */ + HSA_ISA_INFO_NAME = 1, + /** + * @deprecated + * + * Number of call conventions supported by the instruction set architecture. + * Must be greater than zero. The type of this attribute is uint32_t. + */ + HSA_ISA_INFO_CALL_CONVENTION_COUNT = 2, + /** + * @deprecated + * + * Number of work-items in a wavefront for a given call convention. Must be a + * power of 2 in the range [1,256]. The type of this attribute is uint32_t. + */ + HSA_ISA_INFO_CALL_CONVENTION_INFO_WAVEFRONT_SIZE = 3, + /** + * @deprecated + * + * Number of wavefronts per compute unit for a given call convention. In + * practice, other factors (for example, the amount of group memory used by a + * work-group) may further limit the number of wavefronts per compute + * unit. The type of this attribute is uint32_t. + */ + HSA_ISA_INFO_CALL_CONVENTION_INFO_WAVEFRONTS_PER_COMPUTE_UNIT = 4, + /** + * Machine models supported by the instruction set architecture. The type of + * this attribute is a bool[2]. If the ISA supports the small machine model, + * the element at index ::HSA_MACHINE_MODEL_SMALL is true. If the ISA supports + * the large model, the element at index ::HSA_MACHINE_MODEL_LARGE is true. + */ + HSA_ISA_INFO_MACHINE_MODELS = 5, + /** + * Profiles supported by the instruction set architecture. The type of this + * attribute is a bool[2]. If the ISA supports the base profile, the element + * at index ::HSA_PROFILE_BASE is true. If the ISA supports the full profile, + * the element at index ::HSA_PROFILE_FULL is true. + */ + HSA_ISA_INFO_PROFILES = 6, + /** + * Default floating-point rounding modes supported by the instruction set + * architecture. The type of this attribute is a bool[3]. The value at a given + * index is true if the corresponding rounding mode in + * ::hsa_default_float_rounding_mode_t is supported. At least one default mode + * has to be supported. + * + * If the default mode is supported, then + * ::HSA_ISA_INFO_BASE_PROFILE_DEFAULT_FLOAT_ROUNDING_MODES must report that + * both the zero and the near roundings modes are supported. + */ + HSA_ISA_INFO_DEFAULT_FLOAT_ROUNDING_MODES = 7, + /** + * Default floating-point rounding modes supported by the instruction set + * architecture in the Base profile. The type of this attribute is a + * bool[3]. The value at a given index is true if the corresponding rounding + * mode in ::hsa_default_float_rounding_mode_t is supported. The value at + * index HSA_DEFAULT_FLOAT_ROUNDING_MODE_DEFAULT must be false. At least one + * of the values at indexes ::HSA_DEFAULT_FLOAT_ROUNDING_MODE_ZERO or + * HSA_DEFAULT_FLOAT_ROUNDING_MODE_NEAR must be true. + */ + HSA_ISA_INFO_BASE_PROFILE_DEFAULT_FLOAT_ROUNDING_MODES = 8, + /** + * Flag indicating that the f16 HSAIL operation is at least as fast as the + * f32 operation in the instruction set architecture. The type of this + * attribute is bool. + */ + HSA_ISA_INFO_FAST_F16_OPERATION = 9, + /** + * Maximum number of work-items of each dimension of a work-group. Each + * maximum must be greater than 0. No maximum can exceed the value of + * ::HSA_ISA_INFO_WORKGROUP_MAX_SIZE. The type of this attribute is + * uint16_t[3]. + */ + HSA_ISA_INFO_WORKGROUP_MAX_DIM = 12, + /** + * Maximum total number of work-items in a work-group. The type + * of this attribute is uint32_t. + */ + HSA_ISA_INFO_WORKGROUP_MAX_SIZE = 13, + /** + * Maximum number of work-items of each dimension of a grid. Each maximum must + * be greater than 0, and must not be smaller than the corresponding value in + * ::HSA_ISA_INFO_WORKGROUP_MAX_DIM. No maximum can exceed the value of + * ::HSA_ISA_INFO_GRID_MAX_SIZE. The type of this attribute is + * ::hsa_dim3_t. + */ + HSA_ISA_INFO_GRID_MAX_DIM = 14, + /** + * Maximum total number of work-items in a grid. The type of this + * attribute is uint64_t. + */ + HSA_ISA_INFO_GRID_MAX_SIZE = 16, + /** + * Maximum number of fbarriers per work-group. Must be at least 32. The + * type of this attribute is uint32_t. + */ + HSA_ISA_INFO_FBARRIER_MAX_SIZE = 17 +} hsa_isa_info_t; + +/** + * @deprecated The concept of call convention has been deprecated. If the + * application wants to query the value of an attribute for a given instruction + * set architecture, use ::hsa_isa_get_info_alt instead. If the application + * wants to query an attribute that is specific to a given combination of ISA + * and wavefront, use ::hsa_wavefront_get_info. + * + * @brief Get the current value of an attribute for a given instruction set + * architecture (ISA). + * + * @param[in] isa A valid instruction set architecture. + * + * @param[in] attribute Attribute to query. + * + * @param[in] index Call convention index. Used only for call convention + * attributes, otherwise ignored. Must have a value between 0 (inclusive) and + * the value of the attribute ::HSA_ISA_INFO_CALL_CONVENTION_COUNT (not + * inclusive) in @p isa. + * + * @param[out] value Pointer to an application-allocated buffer where to store + * the value of the attribute. If the buffer passed by the application is not + * large enough to hold the value of @p attribute, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ISA The instruction set architecture is + * invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_INDEX The index is out of range. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p attribute is an invalid + * instruction set architecture attribute, or @p value is + * NULL. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_isa_get_info( + hsa_isa_t isa, + hsa_isa_info_t attribute, + uint32_t index, + void *value); + +/** + * @brief Get the current value of an attribute for a given instruction set + * architecture (ISA). + * + * @param[in] isa A valid instruction set architecture. + * + * @param[in] attribute Attribute to query. + * + * @param[out] value Pointer to an application-allocated buffer where to store + * the value of the attribute. If the buffer passed by the application is not + * large enough to hold the value of @p attribute, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ISA The instruction set architecture is + * invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p attribute is an invalid + * instruction set architecture attribute, or @p value is + * NULL. + */ +hsa_status_t HSA_API hsa_isa_get_info_alt( + hsa_isa_t isa, + hsa_isa_info_t attribute, + void *value); + +/** + * @brief Retrieve the exception policy support for a given combination of + * instruction set architecture and profile. + * + * @param[in] isa A valid instruction set architecture. + * + * @param[in] profile Profile. + * + * @param[out] mask Pointer to a memory location where the HSA runtime stores a + * mask of ::hsa_exception_policy_t values. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ISA The instruction set architecture is + * invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p profile is not a valid + * profile, or @p mask is NULL. + */ +hsa_status_t HSA_API hsa_isa_get_exception_policies( + hsa_isa_t isa, + hsa_profile_t profile, + uint16_t *mask); + +/** + * @brief Floating-point types. + */ +typedef enum { + /** + * 16-bit floating-point type. + */ + HSA_FP_TYPE_16 = 1, + /** + * 32-bit floating-point type. + */ + HSA_FP_TYPE_32 = 2, + /** + * 64-bit floating-point type. + */ + HSA_FP_TYPE_64 = 4 +} hsa_fp_type_t; + +/** + * @brief Flush to zero modes. + */ +typedef enum { + /** + * Flush to zero. + */ + HSA_FLUSH_MODE_FTZ = 1, + /** + * Do not flush to zero. + */ + HSA_FLUSH_MODE_NON_FTZ = 2 +} hsa_flush_mode_t; + +/** + * @brief Round methods. + */ +typedef enum { + /** + * Single round method. + */ + HSA_ROUND_METHOD_SINGLE = 1, + /** + * Double round method. + */ + HSA_ROUND_METHOD_DOUBLE = 2 +} hsa_round_method_t; + +/** + * @brief Retrieve the round method (single or double) used to implement the + * floating-point multiply add instruction (mad) for a given combination of + * instruction set architecture, floating-point type, and flush to zero + * modifier. + * + * @param[in] isa Instruction set architecture. + * + * @param[in] fp_type Floating-point type. + * + * @param[in] flush_mode Flush to zero modifier. + * + * @param[out] round_method Pointer to a memory location where the HSA + * runtime stores the round method used by the implementation. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ISA The instruction set architecture is + * invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p fp_type is not a valid + * floating-point type, or @p flush_mode is not a valid flush to zero modifier, + * or @p round_method is NULL. + */ +hsa_status_t HSA_API hsa_isa_get_round_method( + hsa_isa_t isa, + hsa_fp_type_t fp_type, + hsa_flush_mode_t flush_mode, + hsa_round_method_t *round_method); + +/** + * @brief Wavefront handle + */ +typedef struct hsa_wavefront_s { + /** + * Opaque handle. Two handles reference the same object of the enclosing type + * if and only if they are equal. + */ + uint64_t handle; +} hsa_wavefront_t; + +/** + * @brief Wavefront attributes. + */ +typedef enum { + /** + * Number of work-items in the wavefront. Must be a power of 2 in the range + * [1,256]. The type of this attribute is uint32_t. + */ + HSA_WAVEFRONT_INFO_SIZE = 0 +} hsa_wavefront_info_t; + +/** + * @brief Get the current value of a wavefront attribute. + * + * @param[in] wavefront A wavefront. + * + * @param[in] attribute Attribute to query. + * + * @param[out] value Pointer to an application-allocated buffer where to store + * the value of the attribute. If the buffer passed by the application is not + * large enough to hold the value of @p attribute, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_WAVEFRONT The wavefront is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p attribute is an invalid + * wavefront attribute, or @p value is NULL. + */ +hsa_status_t HSA_API hsa_wavefront_get_info( + hsa_wavefront_t wavefront, + hsa_wavefront_info_t attribute, + void *value); + +/** + * @brief Iterate over the different wavefronts supported by an instruction set + * architecture, and invoke an application-defined callback on every iteration. + * + * @param[in] isa Instruction set architecture. + * + * @param[in] callback Callback to be invoked once per wavefront that is + * supported by the agent. The HSA runtime passes two arguments to the callback: + * the wavefront handle and the application data. If @p callback returns a + * status other than ::HSA_STATUS_SUCCESS for a particular iteration, the + * traversal stops and that value is returned. + * + * @param[in] data Application data that is passed to @p callback on every + * iteration. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ISA The instruction set architecture is + * invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p callback is NULL. + */ +hsa_status_t HSA_API hsa_isa_iterate_wavefronts( + hsa_isa_t isa, + hsa_status_t (*callback)(hsa_wavefront_t wavefront, void *data), + void *data); + +/** + * @deprecated Use ::hsa_agent_iterate_isas to query which instructions set + * architectures are supported by a given agent. + * + * @brief Check if the instruction set architecture of a code object can be + * executed on an agent associated with another architecture. + * + * @param[in] code_object_isa Instruction set architecture associated with a + * code object. + * + * @param[in] agent_isa Instruction set architecture associated with an agent. + * + * @param[out] result Pointer to a memory location where the HSA runtime stores + * the result of the check. If the two architectures are compatible, the result + * is true; if they are incompatible, the result is false. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ISA @p code_object_isa or @p agent_isa are + * invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p result is NULL. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_isa_compatible( + hsa_isa_t code_object_isa, + hsa_isa_t agent_isa, + bool *result); + +/** @} */ + + +/** \defgroup executable Executable + * @{ + */ + +/** + * @brief Code object reader handle. A code object reader is used to + * load a code object from file (when created using + * ::hsa_code_object_reader_create_from_file), or from memory (if created using + * ::hsa_code_object_reader_create_from_memory). + */ +typedef struct hsa_code_object_reader_s { + /** + * Opaque handle. Two handles reference the same object of the enclosing type + * if and only if they are equal. + */ + uint64_t handle; +} hsa_code_object_reader_t; + +/** + * @brief Create a code object reader to operate on a file. + * + * @param[in] file File descriptor. The file must have been opened by + * application with at least read permissions prior calling this function. The + * file must contain a vendor-specific code object. + * + * The file is owned and managed by the application; the lifetime of the file + * descriptor must exceed that of any associated code object reader. + * + * @param[out] code_object_reader Memory location to store the newly created + * code object reader handle. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_FILE @p file is invalid. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to + * allocate the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p code_object_reader is NULL. + */ +hsa_status_t HSA_API hsa_code_object_reader_create_from_file( + hsa_file_t file, + hsa_code_object_reader_t *code_object_reader); + +/** + * @brief Create a code object reader to operate on memory. + * + * @param[in] code_object Memory buffer that contains a vendor-specific code + * object. The buffer is owned and managed by the application; the lifetime of + * the buffer must exceed that of any associated code object reader. + * + * @param[in] size Size of the buffer pointed to by @p code_object. Must not be + * 0. + * + * @param[out] code_object_reader Memory location to store newly created code + * object reader handle. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to + * allocate the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p code_object is NULL, @p size + * is zero, or @p code_object_reader is NULL. + */ +hsa_status_t HSA_API hsa_code_object_reader_create_from_memory( + const void *code_object, + size_t size, + hsa_code_object_reader_t *code_object_reader); + +/** + * @brief Destroy a code object reader. + * + * @details The code object reader handle becomes invalid after completion of + * this function. Any file or memory used to create the code object read is not + * closed, removed, or deallocated by this function. + * + * @param[in] code_object_reader Code object reader to destroy. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_CODE_OBJECT_READER @p code_object_reader + * is invalid. + */ +hsa_status_t HSA_API hsa_code_object_reader_destroy( + hsa_code_object_reader_t code_object_reader); + +/** + * @brief Struct containing an opaque handle to an executable, which contains + * ISA for finalized kernels and indirect functions together with the allocated + * global or readonly segment variables they reference. + */ +typedef struct hsa_executable_s { + /** + * Opaque handle. Two handles reference the same object of the enclosing type + * if and only if they are equal. + */ + uint64_t handle; +} hsa_executable_t; + +/** + * @brief Executable state. + */ +typedef enum { + /** + * Executable state, which allows the user to load code objects and define + * external variables. Variable addresses, kernel code handles, and + * indirect function code handles are not available in query operations until + * the executable is frozen (zero always returned). + */ + HSA_EXECUTABLE_STATE_UNFROZEN = 0, + /** + * Executable state, which allows the user to query variable addresses, + * kernel code handles, and indirect function code handles using query + * operations. Loading new code objects, as well as defining external + * variables, is not allowed in this state. + */ + HSA_EXECUTABLE_STATE_FROZEN = 1 +} hsa_executable_state_t; + +/** + * @deprecated Use ::hsa_executable_create_alt instead, which allows the + * application to specify the default floating-point rounding mode of the + * executable and assumes an unfrozen initial state. + * + * @brief Create an empty executable. + * + * @param[in] profile Profile used in the executable. + * + * @param[in] executable_state Executable state. If the state is + * ::HSA_EXECUTABLE_STATE_FROZEN, the resulting executable is useless because no + * code objects can be loaded, and no variables can be defined. + * + * @param[in] options Standard and vendor-specific options. Unknown options are + * ignored. A standard option begins with the "-hsa_" prefix. Options beginning + * with the "-hsa_ext__" prefix are reserved for extensions. A + * vendor-specific option begins with the "-_" prefix. Must be a + * NUL-terminated string. May be NULL. + * + * @param[out] executable Memory location where the HSA runtime stores the newly + * created executable handle. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to + * allocate the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p profile is invalid, or + * @p executable is NULL. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_executable_create( + hsa_profile_t profile, + hsa_executable_state_t executable_state, + const char *options, + hsa_executable_t *executable); + +/** + * @brief Create an empty executable. + * + * @param[in] profile Profile used in the executable. + * + * @param[in] default_float_rounding_mode Default floating-point rounding mode + * used in the executable. Allowed rounding modes are near and zero (default is + * not allowed). + * + * @param[in] options Standard and vendor-specific options. Unknown options are + * ignored. A standard option begins with the "-hsa_" prefix. Options beginning + * with the "-hsa_ext__" prefix are reserved for extensions. A + * vendor-specific option begins with the "-_" prefix. Must be a + * NUL-terminated string. May be NULL. + * + * @param[out] executable Memory location where the HSA runtime stores newly + * created executable handle. The initial state of the executable is + * ::HSA_EXECUTABLE_STATE_UNFROZEN. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to + * allocate the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p profile is invalid, or + * @p executable is NULL. + */ +hsa_status_t HSA_API hsa_executable_create_alt( + hsa_profile_t profile, + hsa_default_float_rounding_mode_t default_float_rounding_mode, + const char *options, + hsa_executable_t *executable); + +/** + * @brief Destroy an executable. + * + * @details An executable handle becomes invalid after the executable has been + * destroyed. Code object handles that were loaded into this executable are + * still valid after the executable has been destroyed, and can be used as + * intended. Resources allocated outside and associated with this executable + * (such as external global or readonly variables) can be released after the + * executable has been destroyed. + * + * Executable should not be destroyed while kernels are in flight. + * + * @param[in] executable Executable. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE The executable is invalid. + */ +hsa_status_t HSA_API hsa_executable_destroy( + hsa_executable_t executable); + +/** + * @brief Loaded code object handle. + */ +typedef struct hsa_loaded_code_object_s { + /** + * Opaque handle. Two handles reference the same object of the enclosing type + * if and only if they are equal. + */ + uint64_t handle; +} hsa_loaded_code_object_t; + +/** + * @brief Load a program code object into an executable. + * + * @details A program code object contains information about resources that are + * accessible by all kernel agents that run the executable, and can be loaded + * at most once into an executable. + * + * If the program code object uses extensions, the implementation must support + * them for this operation to return successfully. + * + * @param[in] executable Executable. + * + * @param[in] code_object_reader A code object reader that holds the program + * code object to load. If a code object reader is destroyed before all the + * associated executables are destroyed, the behavior is undefined. + * + * @param[in] options Standard and vendor-specific options. Unknown options are + * ignored. A standard option begins with the "-hsa_" prefix. Options beginning + * with the "-hsa_ext__" prefix are reserved for extensions. A + * vendor-specific option begins with the "-_" prefix. Must be a + * NUL-terminated string. May be NULL. + * + * @param[out] loaded_code_object Pointer to a memory location where the HSA + * runtime stores the loaded code object handle. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to + * allocate the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE The executable is invalid. + * + * @retval ::HSA_STATUS_ERROR_FROZEN_EXECUTABLE The executable is frozen. + * + * @retval ::HSA_STATUS_ERROR_INVALID_CODE_OBJECT_READER @p code_object_reader + * is invalid. + * + * @retval ::HSA_STATUS_ERROR_INCOMPATIBLE_ARGUMENTS The program code object is + * not compatible with the executable or the implementation (for example, the + * code object uses an extension that is not supported by the implementation). + */ +hsa_status_t HSA_API hsa_executable_load_program_code_object( + hsa_executable_t executable, + hsa_code_object_reader_t code_object_reader, + const char *options, + hsa_loaded_code_object_t *loaded_code_object); + +/** + * @brief Load an agent code object into an executable. + * + * @details The agent code object contains all defined agent + * allocation variables, functions, indirect functions, and kernels in a given + * program for a given instruction set architecture. + * + * Any module linkage declaration must have been defined either by a define + * variable or by loading a code object that has a symbol with module linkage + * definition. + * + * The default floating-point rounding mode of the code object associated with + * @p code_object_reader must match that of the executable + * (::HSA_EXECUTABLE_INFO_DEFAULT_FLOAT_ROUNDING_MODE), or be default (in which + * case the value of ::HSA_EXECUTABLE_INFO_DEFAULT_FLOAT_ROUNDING_MODE is used). + * If the agent code object uses extensions, the implementation and the agent + * must support them for this operation to return successfully. + * + * @param[in] executable Executable. + * + * @param[in] agent Agent to load code object for. A code object can be loaded + * into an executable at most once for a given agent. The instruction set + * architecture of the code object must be supported by the agent. + * + * @param[in] code_object_reader A code object reader that holds the code object + * to load. If a code object reader is destroyed before all the associated + * executables are destroyed, the behavior is undefined. + * + * @param[in] options Standard and vendor-specific options. Unknown options are + * ignored. A standard option begins with the "-hsa_" prefix. Options beginning + * with the "-hsa_ext__" prefix are reserved for extensions. A + * vendor-specific option begins with the "-_" prefix. Must be a + * NUL-terminated string. May be NULL. + * + * @param[out] loaded_code_object Pointer to a memory location where the HSA + * runtime stores the loaded code object handle. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to + * allocate the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE The executable is invalid. + * + * @retval ::HSA_STATUS_ERROR_FROZEN_EXECUTABLE The executable is frozen. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_CODE_OBJECT_READER @p code_object_reader + * is invalid. + * + * @retval ::HSA_STATUS_ERROR_INCOMPATIBLE_ARGUMENTS The code object read by @p + * code_object_reader is not compatible with the agent (for example, the agent + * does not support the instruction set architecture of the code object), the + * executable (for example, there is a default floating-point mode mismatch + * between the two), or the implementation. + */ +hsa_status_t HSA_API hsa_executable_load_agent_code_object( + hsa_executable_t executable, + hsa_agent_t agent, + hsa_code_object_reader_t code_object_reader, + const char *options, + hsa_loaded_code_object_t *loaded_code_object); + +/** + * @brief Freeze the executable. + * + * @details No modifications to executable can be made after freezing: no code + * objects can be loaded to the executable, and no external variables can be + * defined. Freezing the executable does not prevent querying the executable's + * attributes. The application must define all the external variables in an + * executable before freezing it. + * + * @param[in] executable Executable. + * + * @param[in] options Standard and vendor-specific options. Unknown options are + * ignored. A standard option begins with the "-hsa_" prefix. Options beginning + * with the "-hsa_ext__" prefix are reserved for extensions. A + * vendor-specific option begins with the "-_" prefix. Must be a + * NUL-terminated string. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE The executable is invalid. + * + * @retval ::HSA_STATUS_ERROR_VARIABLE_UNDEFINED One or more variables are + * undefined in the executable. + * + * @retval ::HSA_STATUS_ERROR_FROZEN_EXECUTABLE @p executable is already frozen. + */ +hsa_status_t HSA_API hsa_executable_freeze( + hsa_executable_t executable, + const char *options); + +/** + * @brief Executable attributes. + */ +typedef enum { + /** + * Profile this executable is created for. The type of this attribute is + * ::hsa_profile_t. + */ + HSA_EXECUTABLE_INFO_PROFILE = 1, + /** + * Executable state. The type of this attribute is ::hsa_executable_state_t. + */ + HSA_EXECUTABLE_INFO_STATE = 2, + /** + * Default floating-point rounding mode specified when executable was created. + * The type of this attribute is ::hsa_default_float_rounding_mode_t. + */ + HSA_EXECUTABLE_INFO_DEFAULT_FLOAT_ROUNDING_MODE = 3 +} hsa_executable_info_t; + +/** + * @brief Get the current value of an attribute for a given executable. + * + * @param[in] executable Executable. + * + * @param[in] attribute Attribute to query. + * + * @param[out] value Pointer to an application-allocated buffer where to store + * the value of the attribute. If the buffer passed by the application is not + * large enough to hold the value of @p attribute, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE The executable is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p attribute is an invalid + * executable attribute, or @p value is NULL. + */ +hsa_status_t HSA_API hsa_executable_get_info( + hsa_executable_t executable, + hsa_executable_info_t attribute, + void *value); + +/** + * @brief Define an external global variable with program allocation. + * + * @details This function allows the application to provide the definition + * of a variable in the global segment memory with program allocation. The + * variable must be defined before loading a code object into an executable. + * In addition, code objects loaded must not define the variable. + * + * @param[in] executable Executable. Must not be in frozen state. + * + * @param[in] variable_name Name of the variable. The Programmer's Reference + * Manual describes the standard name mangling scheme. + * + * @param[in] address Address where the variable is defined. This address must + * be in global memory and can be read and written by any agent in the + * system. The application cannot deallocate the buffer pointed by @p address + * before @p executable is destroyed. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to + * allocate the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE The executable is invalid. + * + * @retval ::HSA_STATUS_ERROR_VARIABLE_ALREADY_DEFINED The variable is + * already defined. + * + * @retval ::HSA_STATUS_ERROR_INVALID_SYMBOL_NAME There is no variable with the + * @p variable_name. + * + * @retval ::HSA_STATUS_ERROR_FROZEN_EXECUTABLE @p executable is frozen. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p variable_name is NULL. + */ +hsa_status_t HSA_API hsa_executable_global_variable_define( + hsa_executable_t executable, + const char *variable_name, + void *address); + +/** + * @brief Define an external global variable with agent allocation. + * + * @details This function allows the application to provide the definition + * of a variable in the global segment memory with agent allocation. The + * variable must be defined before loading a code object into an executable. + * In addition, code objects loaded must not define the variable. + * + * @param[in] executable Executable. Must not be in frozen state. + * + * @param[in] agent Agent for which the variable is being defined. + * + * @param[in] variable_name Name of the variable. The Programmer's Reference + * Manual describes the standard name mangling scheme. + * + * @param[in] address Address where the variable is defined. This address must + * have been previously allocated using ::hsa_memory_allocate in a global region + * that is only visible to @p agent. The application cannot deallocate the + * buffer pointed by @p address before @p executable is destroyed. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to + * allocate the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE The executable is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT @p agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_VARIABLE_ALREADY_DEFINED The variable is + * already defined. + * + * @retval ::HSA_STATUS_ERROR_INVALID_SYMBOL_NAME There is no variable with the + * @p variable_name. + * + * @retval ::HSA_STATUS_ERROR_FROZEN_EXECUTABLE @p executable is frozen. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p variable_name is NULL. + */ +hsa_status_t HSA_API hsa_executable_agent_global_variable_define( + hsa_executable_t executable, + hsa_agent_t agent, + const char *variable_name, + void *address); + +/** + * @brief Define an external readonly variable. + * + * @details This function allows the application to provide the definition + * of a variable in the readonly segment memory. The variable must be defined + * before loading a code object into an executable. In addition, code objects + * loaded must not define the variable. + * + * @param[in] executable Executable. Must not be in frozen state. + * + * @param[in] agent Agent for which the variable is being defined. + * + * @param[in] variable_name Name of the variable. The Programmer's Reference + * Manual describes the standard name mangling scheme. + * + * @param[in] address Address where the variable is defined. This address must + * have been previously allocated using ::hsa_memory_allocate in a readonly + * region associated with @p agent. The application cannot deallocate the buffer + * pointed by @p address before @p executable is destroyed. + * + * @param[in] address Address where the variable is defined. The buffer pointed + * by @p address is owned by the application, and cannot be deallocated before + * @p executable is destroyed. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to + * allocate the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE Executable is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT @p agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_VARIABLE_ALREADY_DEFINED The variable is + * already defined. + * + * @retval ::HSA_STATUS_ERROR_INVALID_SYMBOL_NAME There is no variable with the + * @p variable_name. + * + * @retval ::HSA_STATUS_ERROR_FROZEN_EXECUTABLE @p executable is frozen. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p variable_name is NULL. + */ +hsa_status_t HSA_API hsa_executable_readonly_variable_define( + hsa_executable_t executable, + hsa_agent_t agent, + const char *variable_name, + void *address); + +/** + * @brief Validate an executable. Checks that all code objects have matching + * machine model, profile, and default floating-point rounding mode. Checks that + * all declarations have definitions. Checks declaration-definition + * compatibility (see the HSA Programming Reference Manual for compatibility + * rules). Invoking this function is equivalent to invoking + * ::hsa_executable_validate_alt with no options. + * + * @param[in] executable Executable. Must be in frozen state. + * + * @param[out] result Memory location where the HSA runtime stores the + * validation result. If the executable passes validation, the result is 0. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE @p executable is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p result is NULL. + */ +hsa_status_t HSA_API hsa_executable_validate( + hsa_executable_t executable, + uint32_t *result); + +/** + * @brief Validate an executable. Checks that all code objects have matching + * machine model, profile, and default floating-point rounding mode. Checks that + * all declarations have definitions. Checks declaration-definition + * compatibility (see the HSA Programming Reference Manual for compatibility + * rules). + * + * @param[in] executable Executable. Must be in frozen state. + * + * @param[in] options Standard and vendor-specific options. Unknown options are + * ignored. A standard option begins with the "-hsa_" prefix. Options beginning + * with the "-hsa_ext__" prefix are reserved for extensions. A + * vendor-specific option begins with the "-_" prefix. Must be a + * NUL-terminated string. May be NULL. + * + * @param[out] result Memory location where the HSA runtime stores the + * validation result. If the executable passes validation, the result is 0. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE @p executable is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p result is NULL. + */ +hsa_status_t HSA_API hsa_executable_validate_alt( + hsa_executable_t executable, + const char *options, + uint32_t *result); + +/** + * @brief Executable symbol handle. + * + * The lifetime of an executable object symbol matches that of the executable + * associated with it. An operation on a symbol whose associated executable has + * been destroyed results in undefined behavior. + */ +typedef struct hsa_executable_symbol_s { + /** + * Opaque handle. Two handles reference the same object of the enclosing type + * if and only if they are equal. + */ + uint64_t handle; +} hsa_executable_symbol_t; + +/** + * @deprecated Use ::hsa_executable_get_symbol_by_name instead. + * + * @brief Get the symbol handle for a given a symbol name. + * + * @param[in] executable Executable. + * + * @param[in] module_name Module name. Must be NULL if the symbol has + * program linkage. + * + * @param[in] symbol_name Symbol name. + * + * @param[in] agent Agent associated with the symbol. If the symbol is + * independent of any agent (for example, a variable with program + * allocation), this argument is ignored. + * + * @param[in] call_convention Call convention associated with the symbol. If the + * symbol does not correspond to an indirect function, this argument is ignored. + * + * @param[out] symbol Memory location where the HSA runtime stores the symbol + * handle. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE The executable is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_SYMBOL_NAME There is no symbol with a name + * that matches @p symbol_name. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p symbol_name is NULL, or + * @p symbol is NULL. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_executable_get_symbol( + hsa_executable_t executable, + const char *module_name, + const char *symbol_name, + hsa_agent_t agent, + int32_t call_convention, + hsa_executable_symbol_t *symbol); + +/** + * @brief Retrieve the symbol handle corresponding to a given a symbol name. + * + * @param[in] executable Executable. + * + * @param[in] symbol_name Symbol name. Must be a NUL-terminated character + * array. The Programmer's Reference Manual describes the standard name mangling + * scheme. + * + * @param[in] agent Pointer to the agent for which the symbol with the given + * name is defined. If the symbol corresponding to the given name has program + * allocation, @p agent must be NULL. + * + * @param[out] symbol Memory location where the HSA runtime stores the symbol + * handle. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE The executable is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_SYMBOL_NAME There is no symbol with a name + * that matches @p symbol_name. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p symbol_name is NULL, or @p + * symbol is NULL. + */ +hsa_status_t HSA_API hsa_executable_get_symbol_by_name( + hsa_executable_t executable, + const char *symbol_name, + const hsa_agent_t *agent, + hsa_executable_symbol_t *symbol); + +/** + * @brief Symbol type. + */ +typedef enum { + /** + * Variable. + */ + HSA_SYMBOL_KIND_VARIABLE = 0, + /** + * Kernel. + */ + HSA_SYMBOL_KIND_KERNEL = 1, + /** + * Indirect function. + */ + HSA_SYMBOL_KIND_INDIRECT_FUNCTION = 2 +} hsa_symbol_kind_t; + +/** + * @brief Linkage type of a symbol. + */ +typedef enum { + /** + * Module linkage. + */ + HSA_SYMBOL_LINKAGE_MODULE = 0, + /** + * Program linkage. + */ + HSA_SYMBOL_LINKAGE_PROGRAM = 1 +} hsa_symbol_linkage_t; + +/** + * @brief Allocation type of a variable. + */ +typedef enum { + /** + * Agent allocation. + */ + HSA_VARIABLE_ALLOCATION_AGENT = 0, + /** + * Program allocation. + */ + HSA_VARIABLE_ALLOCATION_PROGRAM = 1 +} hsa_variable_allocation_t; + +/** + * @brief Memory segment associated with a variable. + */ +typedef enum { + /** + * Global memory segment. + */ + HSA_VARIABLE_SEGMENT_GLOBAL = 0, + /** + * Readonly memory segment. + */ + HSA_VARIABLE_SEGMENT_READONLY = 1 +} hsa_variable_segment_t; + +/** + * @brief Executable symbol attributes. + */ +typedef enum { + /** + * The kind of the symbol. The type of this attribute is ::hsa_symbol_kind_t. + */ + HSA_EXECUTABLE_SYMBOL_INFO_TYPE = 0, + /** + * The length of the symbol name in bytes, not including the NUL terminator. + * The type of this attribute is uint32_t. + */ + HSA_EXECUTABLE_SYMBOL_INFO_NAME_LENGTH = 1, + /** + * The name of the symbol. The type of this attribute is character array with + * the length equal to the value of ::HSA_EXECUTABLE_SYMBOL_INFO_NAME_LENGTH + * attribute. + */ + HSA_EXECUTABLE_SYMBOL_INFO_NAME = 2, + /** + * @deprecated + * + * The length of the module name in bytes (not including the NUL terminator) + * to which this symbol belongs if this symbol has module linkage, otherwise 0 + * is returned. The type of this attribute is uint32_t. + */ + HSA_EXECUTABLE_SYMBOL_INFO_MODULE_NAME_LENGTH = 3, + /** + * @deprecated + * + * The module name to which this symbol belongs if this symbol has module + * linkage, otherwise an empty string is returned. The type of this attribute + * is character array with the length equal to the value of + * ::HSA_EXECUTABLE_SYMBOL_INFO_MODULE_NAME_LENGTH attribute. + */ + HSA_EXECUTABLE_SYMBOL_INFO_MODULE_NAME = 4, + /** + * @deprecated + * + * Agent associated with this symbol. If the symbol is a variable, the + * value of this attribute is only defined if + * ::HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ALLOCATION is + * ::HSA_VARIABLE_ALLOCATION_AGENT. The type of this attribute is hsa_agent_t. + */ + HSA_EXECUTABLE_SYMBOL_INFO_AGENT = 20, + /** + * The address of the variable. The value of this attribute is undefined if + * the symbol is not a variable. The type of this attribute is uint64_t. + * + * If executable's state is ::HSA_EXECUTABLE_STATE_UNFROZEN, then 0 is + * returned. + */ + HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ADDRESS = 21, + /** + * The linkage kind of the symbol. The type of this attribute is + * ::hsa_symbol_linkage_t. + */ + HSA_EXECUTABLE_SYMBOL_INFO_LINKAGE = 5, + /** + * Indicates whether the symbol corresponds to a definition. The type of this + * attribute is bool. + */ + HSA_EXECUTABLE_SYMBOL_INFO_IS_DEFINITION = 17, + /** + * @deprecated + * + * The allocation kind of the variable. The value of this attribute is + * undefined if the symbol is not a variable. The type of this attribute is + * ::hsa_variable_allocation_t. + */ + HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ALLOCATION = 6, + /** + * @deprecated + * + * The segment kind of the variable. The value of this attribute is undefined + * if the symbol is not a variable. The type of this attribute is + * ::hsa_variable_segment_t. + */ + HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_SEGMENT = 7, + /** + * @deprecated + * + * Alignment of the symbol in memory. The value of this attribute is undefined + * if the symbol is not a variable. The type of this attribute is uint32_t. + * + * The current alignment of the variable in memory may be greater than the + * value specified in the source program variable declaration. + */ + HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ALIGNMENT = 8, + /** + * @deprecated + * + * Size of the variable. The value of this attribute is undefined if + * the symbol is not a variable. The type of this attribute is uint32_t. + * + * A value of 0 is returned if the variable is an external variable and has an + * unknown dimension. + */ + HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_SIZE = 9, + /** + * @deprecated + * + * Indicates whether the variable is constant. The value of this attribute is + * undefined if the symbol is not a variable. The type of this attribute is + * bool. + */ + HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_IS_CONST = 10, + /** + * Kernel object handle, used in the kernel dispatch packet. The value of this + * attribute is undefined if the symbol is not a kernel. The type of this + * attribute is uint64_t. + * + * If the state of the executable is ::HSA_EXECUTABLE_STATE_UNFROZEN, then 0 + * is returned. + */ + HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_OBJECT = 22, + /** + * Size of kernarg segment memory that is required to hold the values of the + * kernel arguments, in bytes. Must be a multiple of 16. The value of this + * attribute is undefined if the symbol is not a kernel. The type of this + * attribute is uint32_t. + */ + HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_KERNARG_SEGMENT_SIZE = 11, + /** + * Alignment (in bytes) of the buffer used to pass arguments to the kernel, + * which is the maximum of 16 and the maximum alignment of any of the kernel + * arguments. The value of this attribute is undefined if the symbol is not a + * kernel. The type of this attribute is uint32_t. + */ + HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_KERNARG_SEGMENT_ALIGNMENT = 12, + /** + * Size of static group segment memory required by the kernel (per + * work-group), in bytes. The value of this attribute is undefined + * if the symbol is not a kernel. The type of this attribute is uint32_t. + * + * The reported amount does not include any dynamically allocated group + * segment memory that may be requested by the application when a kernel is + * dispatched. + */ + HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_GROUP_SEGMENT_SIZE = 13, + /** + * Size of static private, spill, and arg segment memory required by + * this kernel (per work-item), in bytes. The value of this attribute is + * undefined if the symbol is not a kernel. The type of this attribute is + * uint32_t. + * + * If the value of ::HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_DYNAMIC_CALLSTACK is + * true, the kernel may use more private memory than the reported value, and + * the application must add the dynamic call stack usage to @a + * private_segment_size when populating a kernel dispatch packet. + */ + HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_PRIVATE_SEGMENT_SIZE = 14, + /** + * Dynamic callstack flag. The value of this attribute is undefined if the + * symbol is not a kernel. The type of this attribute is bool. + * + * If this flag is set (the value is true), the kernel uses a dynamically + * sized call stack. This can happen if recursive calls, calls to indirect + * functions, or the HSAIL alloca instruction are present in the kernel. + */ + HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_DYNAMIC_CALLSTACK = 15, + /** + * @deprecated + * + * Call convention of the kernel. The value of this attribute is undefined if + * the symbol is not a kernel. The type of this attribute is uint32_t. + */ + HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_CALL_CONVENTION = 18, + /** + * Indirect function object handle. The value of this attribute is undefined + * if the symbol is not an indirect function, or the associated agent does + * not support the Full Profile. The type of this attribute depends on the + * machine model: the type is uint32_t for small machine model, and uint64_t + * for large model. + * + * If the state of the executable is ::HSA_EXECUTABLE_STATE_UNFROZEN, then 0 + * is returned. + */ + HSA_EXECUTABLE_SYMBOL_INFO_INDIRECT_FUNCTION_OBJECT = 23, + /** + * @deprecated + * + * Call convention of the indirect function. The value of this attribute is + * undefined if the symbol is not an indirect function, or the associated + * agent does not support the Full Profile. The type of this attribute is + * uint32_t. + */ + HSA_EXECUTABLE_SYMBOL_INFO_INDIRECT_FUNCTION_CALL_CONVENTION = 16 +} hsa_executable_symbol_info_t; + +/** + * @brief Get the current value of an attribute for a given executable symbol. + * + * @param[in] executable_symbol Executable symbol. + * + * @param[in] attribute Attribute to query. + * + * @param[out] value Pointer to an application-allocated buffer where to store + * the value of the attribute. If the buffer passed by the application is not + * large enough to hold the value of @p attribute, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE_SYMBOL The executable symbol is + * invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p attribute is an invalid + * executable symbol attribute, or @p value is NULL. + */ +hsa_status_t HSA_API hsa_executable_symbol_get_info( + hsa_executable_symbol_t executable_symbol, + hsa_executable_symbol_info_t attribute, + void *value); + +/** + * @deprecated + * + * @brief Iterate over the symbols in a executable, and invoke an + * application-defined callback on every iteration. + * + * @param[in] executable Executable. + * + * @param[in] callback Callback to be invoked once per executable symbol. The + * HSA runtime passes three arguments to the callback: the executable, a symbol, + * and the application data. If @p callback returns a status other than + * ::HSA_STATUS_SUCCESS for a particular iteration, the traversal stops and + * ::hsa_executable_iterate_symbols returns that status value. + * + * @param[in] data Application data that is passed to @p callback on every + * iteration. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE The executable is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p callback is NULL. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_executable_iterate_symbols( + hsa_executable_t executable, + hsa_status_t (*callback)(hsa_executable_t exec, + hsa_executable_symbol_t symbol, + void *data), + void *data); + +/** + * @brief Iterate over the kernels, indirect functions, and agent allocation + * variables in an executable for a given agent, and invoke an application- + * defined callback on every iteration. + * + * @param[in] executable Executable. + * + * @param[in] agent Agent. + * + * @param[in] callback Callback to be invoked once per executable symbol. The + * HSA runtime passes three arguments to the callback: the executable, a symbol, + * and the application data. If @p callback returns a status other than + * ::HSA_STATUS_SUCCESS for a particular iteration, the traversal stops and + * ::hsa_executable_iterate_symbols returns that status value. + * + * @param[in] data Application data that is passed to @p callback on every + * iteration. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE The executable is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p callback is NULL. + */ +hsa_status_t HSA_API hsa_executable_iterate_agent_symbols( + hsa_executable_t executable, + hsa_agent_t agent, + hsa_status_t (*callback)(hsa_executable_t exec, + hsa_agent_t agent, + hsa_executable_symbol_t symbol, + void *data), + void *data); + +/** + * @brief Iterate over the program allocation variables in an executable, and + * invoke an application-defined callback on every iteration. + * + * @param[in] executable Executable. + * + * @param[in] callback Callback to be invoked once per executable symbol. The + * HSA runtime passes three arguments to the callback: the executable, a symbol, + * and the application data. If @p callback returns a status other than + * ::HSA_STATUS_SUCCESS for a particular iteration, the traversal stops and + * ::hsa_executable_iterate_symbols returns that status value. + * + * @param[in] data Application data that is passed to @p callback on every + * iteration. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE The executable is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p callback is NULL. + */ +hsa_status_t HSA_API hsa_executable_iterate_program_symbols( + hsa_executable_t executable, + hsa_status_t (*callback)(hsa_executable_t exec, + hsa_executable_symbol_t symbol, + void *data), + void *data); + +/** @} */ + + +/** \defgroup code-object Code Objects (deprecated). + * @{ + */ + +/** + * @deprecated + * + * @brief Struct containing an opaque handle to a code object, which contains + * ISA for finalized kernels and indirect functions together with information + * about the global or readonly segment variables they reference. + */ +typedef struct hsa_code_object_s { + /** + * Opaque handle. Two handles reference the same object of the enclosing type + * if and only if they are equal. + */ + uint64_t handle; +} hsa_code_object_t; + +/** + * @deprecated + * + * @brief Application data handle that is passed to the serialization + * and deserialization functions. + */ +typedef struct hsa_callback_data_s { + /** + * Opaque handle. + */ + uint64_t handle; +} hsa_callback_data_t; + +/** + * @deprecated + * + * @brief Serialize a code object. Can be used for offline finalization, + * install-time finalization, disk code caching, etc. + * + * @param[in] code_object Code object. + * + * @param[in] alloc_callback Callback function for memory allocation. Must not + * be NULL. The HSA runtime passes three arguments to the callback: the + * allocation size, the application data, and a pointer to a memory location + * where the application stores the allocation result. The HSA runtime invokes + * @p alloc_callback once to allocate a buffer that contains the serialized + * version of @p code_object. If the callback returns a status code other than + * ::HSA_STATUS_SUCCESS, this function returns the same code. + * + * @param[in] callback_data Application data that is passed to @p + * alloc_callback. May be NULL. + * + * @param[in] options Standard and vendor-specific options. Unknown options are + * ignored. A standard option begins with the "-hsa_" prefix. Options beginning + * with the "-hsa_ext__" prefix are reserved for extensions. A + * vendor-specific option begins with the "-_" prefix. Must be a + * NUL-terminated string. May be NULL. + * + * @param[out] serialized_code_object Memory location where the HSA runtime + * stores a pointer to the serialized code object. Must not be NULL. + * + * @param[out] serialized_code_object_size Memory location where the HSA runtime + * stores the size (in bytes) of @p serialized_code_object. The returned value + * matches the allocation size passed by the HSA runtime to @p + * alloc_callback. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to + * allocate the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_CODE_OBJECT @p code_object is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p alloc_callback, @p + * serialized_code_object, or @p serialized_code_object_size are NULL. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_code_object_serialize( + hsa_code_object_t code_object, + hsa_status_t (*alloc_callback)(size_t size, + hsa_callback_data_t data, + void **address), + hsa_callback_data_t callback_data, + const char *options, + void **serialized_code_object, + size_t *serialized_code_object_size); + +/** + * @deprecated + * + * @brief Deserialize a code object. + * + * @param[in] serialized_code_object A serialized code object. Must not be NULL. + * + * @param[in] serialized_code_object_size The size (in bytes) of @p + * serialized_code_object. Must not be 0. + * + * @param[in] options Standard and vendor-specific options. Unknown options are + * ignored. A standard option begins with the "-hsa_" prefix. Options beginning + * with the "-hsa_ext__" prefix are reserved for extensions. A + * vendor-specific option begins with the "-_" prefix. Must be a + * NUL-terminated string. May be NULL. + * + * @param[out] code_object Memory location where the HSA runtime stores the + * deserialized code object. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to + * allocate the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p serialized_code_object, or @p + * code_object are NULL, or @p serialized_code_object_size is 0. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_code_object_deserialize( + void *serialized_code_object, + size_t serialized_code_object_size, + const char *options, + hsa_code_object_t *code_object); + +/** + * @deprecated + * + * @brief Destroy a code object. + * + * @details The lifetime of a code object must exceed that of any executable + * where it has been loaded. If an executable that loaded @p code_object has not + * been destroyed, the behavior is undefined. + * + * @param[in] code_object Code object. The handle becomes invalid after it has + * been destroyed. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_CODE_OBJECT @p code_object is invalid. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_code_object_destroy( + hsa_code_object_t code_object); + +/** + * @deprecated + * + * @brief Code object type. + */ +typedef enum { + /** + * Produces code object that contains ISA for all kernels and indirect + * functions in HSA source. + */ + HSA_CODE_OBJECT_TYPE_PROGRAM = 0 +} hsa_code_object_type_t; + +/** + * @deprecated + * + * @brief Code object attributes. + */ +typedef enum { + /** + * The version of the code object. The type of this attribute is a + * NUL-terminated char[64]. The name must be at most 63 characters long (not + * including the NUL terminator) and all array elements not used for the name + * must be NUL. + */ + HSA_CODE_OBJECT_INFO_VERSION = 0, + /** + * Type of code object. The type of this attribute is + * ::hsa_code_object_type_t. + */ + HSA_CODE_OBJECT_INFO_TYPE = 1, + /** + * Instruction set architecture this code object is produced for. The type of + * this attribute is ::hsa_isa_t. + */ + HSA_CODE_OBJECT_INFO_ISA = 2, + /** + * Machine model this code object is produced for. The type of this attribute + * is ::hsa_machine_model_t. + */ + HSA_CODE_OBJECT_INFO_MACHINE_MODEL = 3, + /** + * Profile this code object is produced for. The type of this attribute is + * ::hsa_profile_t. + */ + HSA_CODE_OBJECT_INFO_PROFILE = 4, + /** + * Default floating-point rounding mode used when the code object is + * produced. The type of this attribute is + * ::hsa_default_float_rounding_mode_t. + */ + HSA_CODE_OBJECT_INFO_DEFAULT_FLOAT_ROUNDING_MODE = 5 +} hsa_code_object_info_t; + +/** + * @deprecated + * + * @brief Get the current value of an attribute for a given code object. + * + * @param[in] code_object Code object. + * + * @param[in] attribute Attribute to query. + * + * @param[out] value Pointer to an application-allocated buffer where to store + * the value of the attribute. If the buffer passed by the application is not + * large enough to hold the value of @p attribute, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_CODE_OBJECT @p code_object is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p attribute is an invalid + * code object attribute, or @p value is NULL. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_code_object_get_info( + hsa_code_object_t code_object, + hsa_code_object_info_t attribute, + void *value); + +/** + * @deprecated + * + * @brief Load code object into the executable. + * + * @details Every global or readonly variable that is external must be defined + * before loading the code object. An internal global or readonly variable is + * allocated once the code object, that is being loaded, references this + * variable and this variable is not allocated. + * + * Any module linkage declaration must have been defined either by a define + * variable or by loading a code object that has a symbol with module linkage + * definition. + * + * @param[in] executable Executable. + * + * @param[in] agent Agent to load code object for. The agent must support the + * default floating-point rounding mode used by @p code_object. + * + * @param[in] code_object Code object to load. The lifetime of the code object + * must exceed that of the executable: if @p code_object is destroyed before @p + * executable, the behavior is undefined. + * + * @param[in] options Standard and vendor-specific options. Unknown options are + * ignored. A standard option begins with the "-hsa_" prefix. Options beginning + * with the "-hsa_ext__" prefix are reserved for extensions. A + * vendor-specific option begins with the "-_" prefix. Must be a + * NUL-terminated string. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to + * allocate the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_EXECUTABLE The executable is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_CODE_OBJECT @p code_object is invalid. + * + * @retval ::HSA_STATUS_ERROR_INCOMPATIBLE_ARGUMENTS @p agent is not compatible + * with @p code_object (for example, @p agent does not support the default + * floating-point rounding mode specified by @p code_object), or @p code_object + * is not compatible with @p executable (for example, @p code_object and @p + * executable have different machine models or profiles). + * + * @retval ::HSA_STATUS_ERROR_FROZEN_EXECUTABLE @p executable is frozen. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_executable_load_code_object( + hsa_executable_t executable, + hsa_agent_t agent, + hsa_code_object_t code_object, + const char *options); + +/** + * @deprecated + * + * @brief Code object symbol handle. + * + * The lifetime of a code object symbol matches that of the code object + * associated with it. An operation on a symbol whose associated code object has + * been destroyed results in undefined behavior. + */ +typedef struct hsa_code_symbol_s { + /** + * Opaque handle. Two handles reference the same object of the enclosing type + * if and only if they are equal. + */ + uint64_t handle; +} hsa_code_symbol_t; + +/** + * @deprecated + * + * @brief Get the symbol handle within a code object for a given a symbol name. + * + * @param[in] code_object Code object. + * + * @param[in] symbol_name Symbol name. + * + * @param[out] symbol Memory location where the HSA runtime stores the symbol + * handle. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_CODE_OBJECT @p code_object is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_SYMBOL_NAME There is no symbol with a name + * that matches @p symbol_name. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p symbol_name is NULL, or + * @p symbol is NULL. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_code_object_get_symbol( + hsa_code_object_t code_object, + const char *symbol_name, + hsa_code_symbol_t *symbol); + +/** + * @deprecated + * + * @brief Get the symbol handle within a code object for a given a symbol name. + * + * @param[in] code_object Code object. + * + * @param[in] module_name Module name. Must be NULL if the symbol has + * program linkage. + * + * @param[in] symbol_name Symbol name. + * + * @param[out] symbol Memory location where the HSA runtime stores the symbol + * handle. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_CODE_OBJECT @p code_object is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_SYMBOL_NAME There is no symbol with a name + * that matches @p symbol_name. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p symbol_name is NULL, or + * @p symbol is NULL. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_code_object_get_symbol_from_name( + hsa_code_object_t code_object, + const char *module_name, + const char *symbol_name, + hsa_code_symbol_t *symbol); + +/** + * @deprecated + * + * @brief Code object symbol attributes. + */ +typedef enum { + /** + * The type of the symbol. The type of this attribute is ::hsa_symbol_kind_t. + */ + HSA_CODE_SYMBOL_INFO_TYPE = 0, + /** + * The length of the symbol name in bytes, not including the NUL terminator. + * The type of this attribute is uint32_t. + */ + HSA_CODE_SYMBOL_INFO_NAME_LENGTH = 1, + /** + * The name of the symbol. The type of this attribute is character array with + * the length equal to the value of ::HSA_CODE_SYMBOL_INFO_NAME_LENGTH + * attribute. + */ + HSA_CODE_SYMBOL_INFO_NAME = 2, + /** + * The length of the module name in bytes (not including the NUL terminator) + * to which this symbol belongs if this symbol has module linkage, otherwise 0 + * is returned. The type of this attribute is uint32_t. + */ + HSA_CODE_SYMBOL_INFO_MODULE_NAME_LENGTH = 3, + /** + * The module name to which this symbol belongs if this symbol has module + * linkage, otherwise an empty string is returned. The type of this attribute + * is character array with the length equal to the value of + * ::HSA_CODE_SYMBOL_INFO_MODULE_NAME_LENGTH attribute. + */ + HSA_CODE_SYMBOL_INFO_MODULE_NAME = 4, + /** + * The linkage kind of the symbol. The type of this attribute is + * ::hsa_symbol_linkage_t. + */ + HSA_CODE_SYMBOL_INFO_LINKAGE = 5, + /** + * Indicates whether the symbol corresponds to a definition. The type of this + * attribute is bool. + */ + HSA_CODE_SYMBOL_INFO_IS_DEFINITION = 17, + /** + * The allocation kind of the variable. The value of this attribute is + * undefined if the symbol is not a variable. The type of this attribute is + * ::hsa_variable_allocation_t. + */ + HSA_CODE_SYMBOL_INFO_VARIABLE_ALLOCATION = 6, + /** + * The segment kind of the variable. The value of this attribute is + * undefined if the symbol is not a variable. The type of this attribute is + * ::hsa_variable_segment_t. + */ + HSA_CODE_SYMBOL_INFO_VARIABLE_SEGMENT = 7, + /** + * Alignment of the symbol in memory. The value of this attribute is undefined + * if the symbol is not a variable. The type of this attribute is uint32_t. + * + * The current alignment of the variable in memory may be greater than the + * value specified in the source program variable declaration. + */ + HSA_CODE_SYMBOL_INFO_VARIABLE_ALIGNMENT = 8, + /** + * Size of the variable. The value of this attribute is undefined if the + * symbol is not a variable. The type of this attribute is uint32_t. + * + * A size of 0 is returned if the variable is an external variable and has an + * unknown dimension. + */ + HSA_CODE_SYMBOL_INFO_VARIABLE_SIZE = 9, + /** + * Indicates whether the variable is constant. The value of this attribute is + * undefined if the symbol is not a variable. The type of this attribute is + * bool. + */ + HSA_CODE_SYMBOL_INFO_VARIABLE_IS_CONST = 10, + /** + * Size of kernarg segment memory that is required to hold the values of the + * kernel arguments, in bytes. Must be a multiple of 16. The value of this + * attribute is undefined if the symbol is not a kernel. The type of this + * attribute is uint32_t. + */ + HSA_CODE_SYMBOL_INFO_KERNEL_KERNARG_SEGMENT_SIZE = 11, + /** + * Alignment (in bytes) of the buffer used to pass arguments to the kernel, + * which is the maximum of 16 and the maximum alignment of any of the kernel + * arguments. The value of this attribute is undefined if the symbol is not a + * kernel. The type of this attribute is uint32_t. + */ + HSA_CODE_SYMBOL_INFO_KERNEL_KERNARG_SEGMENT_ALIGNMENT = 12, + /** + * Size of static group segment memory required by the kernel (per + * work-group), in bytes. The value of this attribute is undefined + * if the symbol is not a kernel. The type of this attribute is uint32_t. + * + * The reported amount does not include any dynamically allocated group + * segment memory that may be requested by the application when a kernel is + * dispatched. + */ + HSA_CODE_SYMBOL_INFO_KERNEL_GROUP_SEGMENT_SIZE = 13, + /** + * Size of static private, spill, and arg segment memory required by + * this kernel (per work-item), in bytes. The value of this attribute is + * undefined if the symbol is not a kernel. The type of this attribute is + * uint32_t. + * + * If the value of ::HSA_CODE_SYMBOL_INFO_KERNEL_DYNAMIC_CALLSTACK is true, + * the kernel may use more private memory than the reported value, and the + * application must add the dynamic call stack usage to @a + * private_segment_size when populating a kernel dispatch packet. + */ + HSA_CODE_SYMBOL_INFO_KERNEL_PRIVATE_SEGMENT_SIZE = 14, + /** + * Dynamic callstack flag. The value of this attribute is undefined if the + * symbol is not a kernel. The type of this attribute is bool. + * + * If this flag is set (the value is true), the kernel uses a dynamically + * sized call stack. This can happen if recursive calls, calls to indirect + * functions, or the HSAIL alloca instruction are present in the kernel. + */ + HSA_CODE_SYMBOL_INFO_KERNEL_DYNAMIC_CALLSTACK = 15, + /** + * Call convention of the kernel. The value of this attribute is undefined if + * the symbol is not a kernel. The type of this attribute is uint32_t. + */ + HSA_CODE_SYMBOL_INFO_KERNEL_CALL_CONVENTION = 18, + /** + * Call convention of the indirect function. The value of this attribute is + * undefined if the symbol is not an indirect function. The type of this + * attribute is uint32_t. + */ + HSA_CODE_SYMBOL_INFO_INDIRECT_FUNCTION_CALL_CONVENTION = 16, + /** + * Wavefront size used by the kernel. The value of this attribute is either + * 32 or 64. The type of this attribute is uint32_t. + */ + HSA_CODE_SYMBOL_INFO_KERNEL_WAVEFRONT_SIZE = 19 +} hsa_code_symbol_info_t; + +/** + * @deprecated + * + * @brief Get the current value of an attribute for a given code symbol. + * + * @param[in] code_symbol Code symbol. + * + * @param[in] attribute Attribute to query. + * + * @param[out] value Pointer to an application-allocated buffer where to store + * the value of the attribute. If the buffer passed by the application is not + * large enough to hold the value of @p attribute, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_CODE_SYMBOL The code symbol is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p attribute is an invalid + * code symbol attribute, or @p value is NULL. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_code_symbol_get_info( + hsa_code_symbol_t code_symbol, + hsa_code_symbol_info_t attribute, + void *value); + +/** + * @deprecated + * + * @brief Iterate over the symbols in a code object, and invoke an + * application-defined callback on every iteration. + * + * @param[in] code_object Code object. + * + * @param[in] callback Callback to be invoked once per code object symbol. The + * HSA runtime passes three arguments to the callback: the code object, a + * symbol, and the application data. If @p callback returns a status other than + * ::HSA_STATUS_SUCCESS for a particular iteration, the traversal stops and + * ::hsa_code_object_iterate_symbols returns that status value. + * + * @param[in] data Application data that is passed to @p callback on every + * iteration. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_CODE_OBJECT @p code_object is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p callback is NULL. + */ +hsa_status_t HSA_API HSA_DEPRECATED hsa_code_object_iterate_symbols( + hsa_code_object_t code_object, + hsa_status_t (*callback)(hsa_code_object_t code_object, + hsa_code_symbol_t symbol, + void *data), + void *data); + +/** @} */ + +#ifdef __cplusplus +} // end extern "C" block +#endif + +#endif // header guard diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_amd_tool.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_amd_tool.h new file mode 100644 index 0000000000000000000000000000000000000000..fa9cac804a49b40be34bccc966be547d56fb94fb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_amd_tool.h @@ -0,0 +1,91 @@ +#ifndef HSA_RUNTIME_AMD_TOOL_EVENTS_H_ +#define HSA_RUNTIME_AMD_TOOL_EVENTS_H_ + +// Insert license header + +#include +#include +#include "hsa.h" + + +typedef enum { + HSA_AMD_EVENT_SCRATCH_ALLOC_FLAG_NONE = 0, + HSA_AMD_EVENT_SCRATCH_ALLOC_FLAG_USE_ONCE = + (1 << 0), // This scratch allocation is only valid for 1 dispatch. + HSA_AMD_EVENT_SCRATCH_ALLOC_FLAG_ALT = + (1 << 1), // Used alternate scratch instead of main scratch +} hsa_amd_event_scratch_alloc_flag_t; + +typedef enum { + HSA_AMD_TOOL_EVENT_MIN = 0, + + // Scratch memory tracking + HSA_AMD_TOOL_EVENT_SCRATCH_ALLOC_START, + HSA_AMD_TOOL_EVENT_SCRATCH_ALLOC_END, + HSA_AMD_TOOL_EVENT_SCRATCH_FREE_START, + HSA_AMD_TOOL_EVENT_SCRATCH_FREE_END, + HSA_AMD_TOOL_EVENT_SCRATCH_ASYNC_RECLAIM_START, + HSA_AMD_TOOL_EVENT_SCRATCH_ASYNC_RECLAIM_END, + + // Add new events above ^ + HSA_AMD_TOOL_EVENT_MAX +} hsa_amd_tool_event_kind_t; + +typedef struct { + hsa_amd_tool_event_kind_t kind; +} hsa_amd_tool_event_none_t; + +typedef struct { + hsa_amd_tool_event_kind_t kind; + const hsa_queue_t* queue; + hsa_amd_event_scratch_alloc_flag_t flags; + uint64_t dispatch_id; // Dispatch ID of the AQL packet that needs more scratch memory +} hsa_amd_event_scratch_alloc_start_t; + +typedef struct { + hsa_amd_tool_event_kind_t kind; + const hsa_queue_t* queue; + hsa_amd_event_scratch_alloc_flag_t flags; + uint64_t dispatch_id; // Dispatch ID of the AQL packet that needs more scratch memory + size_t size; // Amount of scratch allocated - in bytes + size_t num_slots; // limit of number of waves +} hsa_amd_event_scratch_alloc_end_t; + +typedef struct { + hsa_amd_tool_event_kind_t kind; + const hsa_queue_t* queue; + hsa_amd_event_scratch_alloc_flag_t flags; +} hsa_amd_event_scratch_free_start_t; + +typedef struct { + hsa_amd_tool_event_kind_t kind; + const hsa_queue_t* queue; + hsa_amd_event_scratch_alloc_flag_t flags; +} hsa_amd_event_scratch_free_end_t; + +typedef struct { + hsa_amd_tool_event_kind_t kind; + const hsa_queue_t* queue; + hsa_amd_event_scratch_alloc_flag_t flags; +} hsa_amd_event_scratch_async_reclaim_start_t; + +typedef struct { + hsa_amd_tool_event_kind_t kind; + const hsa_queue_t* queue; + hsa_amd_event_scratch_alloc_flag_t flags; +} hsa_amd_event_scratch_async_reclaim_end_t; + +typedef union { + const hsa_amd_tool_event_none_t* none; + const hsa_amd_event_scratch_alloc_start_t* scratch_alloc_start; + const hsa_amd_event_scratch_alloc_end_t* scratch_alloc_end; + const hsa_amd_event_scratch_free_start_t* scratch_free_start; + const hsa_amd_event_scratch_free_end_t* scratch_free_end; + const hsa_amd_event_scratch_async_reclaim_start_t* scratch_async_reclaim_start; + const hsa_amd_event_scratch_async_reclaim_end_t* scratch_async_reclaim_end; +} hsa_amd_tool_event_t; + +typedef hsa_status_t (*hsa_amd_tool_event)(hsa_amd_tool_event_t); + + +#endif \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_api_trace.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_api_trace.h new file mode 100644 index 0000000000000000000000000000000000000000..2a0f59df3b82568cd11c505a149e78d57abb242c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_api_trace.h @@ -0,0 +1,579 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// The University of Illinois/NCSA +// Open Source License (NCSA) +// +// Copyright (c) 2014-2020, Advanced Micro Devices, Inc. All rights reserved. +// +// Developed by: +// +// AMD Research and AMD HSA Software Development +// +// Advanced Micro Devices, Inc. +// +// www.amd.com +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal with 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: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimers in +// the documentation and/or other materials provided with the distribution. +// - Neither the names of Advanced Micro Devices, Inc, +// nor the names of its contributors may be used to endorse or promote +// products derived from this Software without specific prior written +// permission. +// +// 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 CONTRIBUTORS 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 WITH THE SOFTWARE. +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef HSA_RUNTIME_INC_HSA_API_TRACE_H +#define HSA_RUNTIME_INC_HSA_API_TRACE_H + +#include "hsa.h" +#include "hsa_api_trace_version.h" +#ifdef AMD_INTERNAL_BUILD +#include "hsa_ext_image.h" +#include "hsa_ext_amd.h" +#include "hsa_ext_finalize.h" +#include "hsa_amd_tool.h" +#include "hsa_ven_amd_pc_sampling.h" +#else +#include "inc/hsa_ext_image.h" +#include "inc/hsa_ext_amd.h" +#include "inc/hsa_ext_finalize.h" +#include "inc/hsa_amd_tool.h" +#include "inc/hsa_ven_amd_pc_sampling.h" +#endif + +#include +#include +#include + +// Table MAJOR_VERSION and STEP_VERSION defines have moved to hsa_api_trace_version.h + +// Min function used to copy Api Tables +static inline uint32_t Min(const uint32_t a, const uint32_t b) { + return (a > b) ? b : a; +} + +// Declarations of APIs intended for use only by tools. + +// An AQL packet that can be put in an intercept queue to cause a callback to +// be invoked when the packet is about to be submitted to the underlying +// hardware queue. These packets are not copied to the underlying hardware +// queue. These packets should come immediately before the regular AQL packet +// they relate to. This implies that packet rewriters should always keep these +// packets adjacent to the regular AQL packet that follows them. +const uint32_t AMD_AQL_FORMAT_INTERCEPT_MARKER = 0xFE; + +struct amd_aql_intercept_marker_s; + +// When an intercept queue is processing rewritten packets to put them on the +// underlying hardware queue, if it encounters a +// AMD_AQL_FORMAT_INTERCEPT_MARKER vendor AQL packet it will call the following +// handler. packet points to the packet, queue is the underlying hardware +// queue, and packet_id is the packet id of the next packet to be put on the +// underlying hardware queue. The intercept queue does not put these packets +// onto the underlying hardware queue. +typedef void (*amd_intercept_marker_handler)(const struct amd_aql_intercept_marker_s* packet, + hsa_queue_t* queue, uint64_t packet_id); +// An AQL vendor packet used by the intercept queue to mark the following +// packet. The callback will be invoked to allow a tool to know where in the +// underlying hardware queue the following packet will be placed. user_data can +// be used to hold any data useful to the tool. +typedef struct amd_aql_intercept_marker_s { + uint16_t header; // Must have a packet type of HSA_PACKET_TYPE_VENDOR_SPECIFIC. + uint8_t format; // Must be AMD_AQL_FORMAT_INTERCEPT_MARKER. + uint8_t reserved[5]; // Must be 0. +#ifdef HSA_LARGE_MODEL + amd_intercept_marker_handler callback; +#elif defined HSA_LITTLE_ENDIAN + amd_intercept_marker_handler callback; + uint32_t reserved1; // Must be 0. +#else + uint32_t reserved1; // Must be 0. + amd_intercept_marker_handler callback; +#endif + uint64_t user_data[6]; +} amd_aql_intercept_marker_t; + +typedef void (*hsa_amd_queue_intercept_packet_writer)(const void* pkts, uint64_t pkt_count); +typedef void (*hsa_amd_queue_intercept_handler)(const void* pkts, uint64_t pkt_count, + uint64_t user_pkt_index, void* data, + hsa_amd_queue_intercept_packet_writer writer); +hsa_status_t hsa_amd_queue_intercept_register(hsa_queue_t* queue, + hsa_amd_queue_intercept_handler callback, + void* user_data); +hsa_status_t hsa_amd_queue_intercept_create( + hsa_agent_t agent_handle, uint32_t size, hsa_queue_type32_t type, + void (*callback)(hsa_status_t status, hsa_queue_t* source, void* data), void* data, + uint32_t private_segment_size, uint32_t group_segment_size, hsa_queue_t** queue); + +typedef void (*hsa_amd_runtime_queue_notifier)(const hsa_queue_t* queue, hsa_agent_t agent, + void* data); +hsa_status_t hsa_amd_runtime_queue_create_register(hsa_amd_runtime_queue_notifier callback, + void* user_data); + +// Structure of Version used to identify an instance of Api table +// Must be the first member (offsetof == 0) of all API tables. +// This is the root of the table passing ABI. +struct ApiTableVersion { + uint32_t major_id; + uint32_t minor_id; + uint32_t step_id; + uint32_t reserved; +}; + +struct ToolsApiTable { + ApiTableVersion version; + + hsa_amd_tool_event hsa_amd_tool_scratch_event_alloc_start_fn; + hsa_amd_tool_event hsa_amd_tool_scratch_event_alloc_end_fn; + hsa_amd_tool_event hsa_amd_tool_scratch_event_free_start_fn; + hsa_amd_tool_event hsa_amd_tool_scratch_event_free_end_fn; + hsa_amd_tool_event hsa_amd_tool_scratch_event_async_reclaim_start_fn; + hsa_amd_tool_event hsa_amd_tool_scratch_event_async_reclaim_end_fn; +}; + +// Table to export HSA Finalizer Extension Apis +struct FinalizerExtTable { + ApiTableVersion version; + decltype(hsa_ext_program_create)* hsa_ext_program_create_fn; + decltype(hsa_ext_program_destroy)* hsa_ext_program_destroy_fn; + decltype(hsa_ext_program_add_module)* hsa_ext_program_add_module_fn; + decltype(hsa_ext_program_iterate_modules)* hsa_ext_program_iterate_modules_fn; + decltype(hsa_ext_program_get_info)* hsa_ext_program_get_info_fn; + decltype(hsa_ext_program_finalize)* hsa_ext_program_finalize_fn; +}; + +// Table to export HSA Image Extension Apis +struct ImageExtTable { + ApiTableVersion version; + decltype(hsa_ext_image_get_capability)* hsa_ext_image_get_capability_fn; + decltype(hsa_ext_image_data_get_info)* hsa_ext_image_data_get_info_fn; + decltype(hsa_ext_image_create)* hsa_ext_image_create_fn; + decltype(hsa_ext_image_import)* hsa_ext_image_import_fn; + decltype(hsa_ext_image_export)* hsa_ext_image_export_fn; + decltype(hsa_ext_image_copy)* hsa_ext_image_copy_fn; + decltype(hsa_ext_image_clear)* hsa_ext_image_clear_fn; + decltype(hsa_ext_image_destroy)* hsa_ext_image_destroy_fn; + decltype(hsa_ext_sampler_create)* hsa_ext_sampler_create_fn; + decltype(hsa_ext_sampler_destroy)* hsa_ext_sampler_destroy_fn; + decltype(hsa_ext_image_get_capability_with_layout)* hsa_ext_image_get_capability_with_layout_fn; + decltype(hsa_ext_image_data_get_info_with_layout)* hsa_ext_image_data_get_info_with_layout_fn; + decltype(hsa_ext_image_create_with_layout)* hsa_ext_image_create_with_layout_fn; +}; + +// Table to export HSA PC Sampling Extension Apis +struct PcSamplingExtTable { + ApiTableVersion version; + decltype(hsa_ven_amd_pcs_iterate_configuration)* hsa_ven_amd_pcs_iterate_configuration_fn; + decltype(hsa_ven_amd_pcs_create)* hsa_ven_amd_pcs_create_fn; + decltype(hsa_ven_amd_pcs_create_from_id)* hsa_ven_amd_pcs_create_from_id_fn; + decltype(hsa_ven_amd_pcs_destroy)* hsa_ven_amd_pcs_destroy_fn; + decltype(hsa_ven_amd_pcs_start)* hsa_ven_amd_pcs_start_fn; + decltype(hsa_ven_amd_pcs_stop)* hsa_ven_amd_pcs_stop_fn; + decltype(hsa_ven_amd_pcs_flush)* hsa_ven_amd_pcs_flush_fn; +}; + + +// Table to export AMD Extension Apis +struct AmdExtTable { + ApiTableVersion version; + decltype(hsa_amd_coherency_get_type)* hsa_amd_coherency_get_type_fn; + decltype(hsa_amd_coherency_set_type)* hsa_amd_coherency_set_type_fn; + decltype(hsa_amd_profiling_set_profiler_enabled)* hsa_amd_profiling_set_profiler_enabled_fn; + decltype(hsa_amd_profiling_async_copy_enable) *hsa_amd_profiling_async_copy_enable_fn; + decltype(hsa_amd_profiling_get_dispatch_time)* hsa_amd_profiling_get_dispatch_time_fn; + decltype(hsa_amd_profiling_get_async_copy_time) *hsa_amd_profiling_get_async_copy_time_fn; + decltype(hsa_amd_profiling_convert_tick_to_system_domain)* hsa_amd_profiling_convert_tick_to_system_domain_fn; + decltype(hsa_amd_signal_async_handler)* hsa_amd_signal_async_handler_fn; + decltype(hsa_amd_async_function)* hsa_amd_async_function_fn; + decltype(hsa_amd_signal_wait_any)* hsa_amd_signal_wait_any_fn; + decltype(hsa_amd_queue_cu_set_mask)* hsa_amd_queue_cu_set_mask_fn; + decltype(hsa_amd_memory_pool_get_info)* hsa_amd_memory_pool_get_info_fn; + decltype(hsa_amd_agent_iterate_memory_pools)* hsa_amd_agent_iterate_memory_pools_fn; + decltype(hsa_amd_memory_pool_allocate)* hsa_amd_memory_pool_allocate_fn; + decltype(hsa_amd_memory_pool_free)* hsa_amd_memory_pool_free_fn; + decltype(hsa_amd_memory_async_copy)* hsa_amd_memory_async_copy_fn; + decltype(hsa_amd_memory_async_copy_on_engine)* hsa_amd_memory_async_copy_on_engine_fn; + decltype(hsa_amd_memory_copy_engine_status)* hsa_amd_memory_copy_engine_status_fn; + decltype(hsa_amd_agent_memory_pool_get_info)* hsa_amd_agent_memory_pool_get_info_fn; + decltype(hsa_amd_agents_allow_access)* hsa_amd_agents_allow_access_fn; + decltype(hsa_amd_memory_pool_can_migrate)* hsa_amd_memory_pool_can_migrate_fn; + decltype(hsa_amd_memory_migrate)* hsa_amd_memory_migrate_fn; + decltype(hsa_amd_memory_lock)* hsa_amd_memory_lock_fn; + decltype(hsa_amd_memory_unlock)* hsa_amd_memory_unlock_fn; + decltype(hsa_amd_memory_fill)* hsa_amd_memory_fill_fn; + decltype(hsa_amd_interop_map_buffer)* hsa_amd_interop_map_buffer_fn; + decltype(hsa_amd_interop_unmap_buffer)* hsa_amd_interop_unmap_buffer_fn; + decltype(hsa_amd_image_create)* hsa_amd_image_create_fn; + decltype(hsa_amd_pointer_info)* hsa_amd_pointer_info_fn; + decltype(hsa_amd_pointer_info_set_userdata)* hsa_amd_pointer_info_set_userdata_fn; + decltype(hsa_amd_ipc_memory_create)* hsa_amd_ipc_memory_create_fn; + decltype(hsa_amd_ipc_memory_attach)* hsa_amd_ipc_memory_attach_fn; + decltype(hsa_amd_ipc_memory_detach)* hsa_amd_ipc_memory_detach_fn; + decltype(hsa_amd_signal_create)* hsa_amd_signal_create_fn; + decltype(hsa_amd_ipc_signal_create)* hsa_amd_ipc_signal_create_fn; + decltype(hsa_amd_ipc_signal_attach)* hsa_amd_ipc_signal_attach_fn; + decltype(hsa_amd_register_system_event_handler)* hsa_amd_register_system_event_handler_fn; + decltype(hsa_amd_queue_intercept_create)* hsa_amd_queue_intercept_create_fn; + decltype(hsa_amd_queue_intercept_register)* hsa_amd_queue_intercept_register_fn; + decltype(hsa_amd_queue_set_priority)* hsa_amd_queue_set_priority_fn; + decltype(hsa_amd_memory_async_copy_rect)* hsa_amd_memory_async_copy_rect_fn; + decltype(hsa_amd_runtime_queue_create_register)* hsa_amd_runtime_queue_create_register_fn; + decltype(hsa_amd_memory_lock_to_pool)* hsa_amd_memory_lock_to_pool_fn; + decltype(hsa_amd_register_deallocation_callback)* hsa_amd_register_deallocation_callback_fn; + decltype(hsa_amd_deregister_deallocation_callback)* hsa_amd_deregister_deallocation_callback_fn; + decltype(hsa_amd_signal_value_pointer)* hsa_amd_signal_value_pointer_fn; + decltype(hsa_amd_svm_attributes_set)* hsa_amd_svm_attributes_set_fn; + decltype(hsa_amd_svm_attributes_get)* hsa_amd_svm_attributes_get_fn; + decltype(hsa_amd_svm_prefetch_async)* hsa_amd_svm_prefetch_async_fn; + decltype(hsa_amd_spm_acquire)* hsa_amd_spm_acquire_fn; + decltype(hsa_amd_spm_release)* hsa_amd_spm_release_fn; + decltype(hsa_amd_spm_set_dest_buffer)* hsa_amd_spm_set_dest_buffer_fn; + decltype(hsa_amd_queue_cu_get_mask)* hsa_amd_queue_cu_get_mask_fn; + decltype(hsa_amd_portable_export_dmabuf)* hsa_amd_portable_export_dmabuf_fn; + decltype(hsa_amd_portable_close_dmabuf)* hsa_amd_portable_close_dmabuf_fn; + decltype(hsa_amd_vmem_address_reserve)* hsa_amd_vmem_address_reserve_fn; + decltype(hsa_amd_vmem_address_free)* hsa_amd_vmem_address_free_fn; + decltype(hsa_amd_vmem_handle_create)* hsa_amd_vmem_handle_create_fn; + decltype(hsa_amd_vmem_handle_release)* hsa_amd_vmem_handle_release_fn; + decltype(hsa_amd_vmem_map)* hsa_amd_vmem_map_fn; + decltype(hsa_amd_vmem_unmap)* hsa_amd_vmem_unmap_fn; + decltype(hsa_amd_vmem_set_access)* hsa_amd_vmem_set_access_fn; + decltype(hsa_amd_vmem_get_access)* hsa_amd_vmem_get_access_fn; + decltype(hsa_amd_vmem_export_shareable_handle)* hsa_amd_vmem_export_shareable_handle_fn; + decltype(hsa_amd_vmem_import_shareable_handle)* hsa_amd_vmem_import_shareable_handle_fn; + decltype(hsa_amd_vmem_retain_alloc_handle)* hsa_amd_vmem_retain_alloc_handle_fn; + decltype(hsa_amd_vmem_get_alloc_properties_from_handle)* + hsa_amd_vmem_get_alloc_properties_from_handle_fn; + decltype(hsa_amd_agent_set_async_scratch_limit)* hsa_amd_agent_set_async_scratch_limit_fn; + decltype(hsa_amd_queue_get_info)* hsa_amd_queue_get_info_fn; + decltype(hsa_amd_vmem_address_reserve_align)* hsa_amd_vmem_address_reserve_align_fn; +}; + +// Table to export HSA Core Runtime Apis +struct CoreApiTable { + ApiTableVersion version; + decltype(hsa_init)* hsa_init_fn; + decltype(hsa_shut_down)* hsa_shut_down_fn; + decltype(hsa_system_get_info)* hsa_system_get_info_fn; + decltype(hsa_system_extension_supported)* hsa_system_extension_supported_fn; + decltype(hsa_system_get_extension_table)* hsa_system_get_extension_table_fn; + decltype(hsa_iterate_agents)* hsa_iterate_agents_fn; + decltype(hsa_agent_get_info)* hsa_agent_get_info_fn; + decltype(hsa_queue_create)* hsa_queue_create_fn; + decltype(hsa_soft_queue_create)* hsa_soft_queue_create_fn; + decltype(hsa_queue_destroy)* hsa_queue_destroy_fn; + decltype(hsa_queue_inactivate)* hsa_queue_inactivate_fn; + decltype(hsa_queue_load_read_index_scacquire)* hsa_queue_load_read_index_scacquire_fn; + decltype(hsa_queue_load_read_index_relaxed)* hsa_queue_load_read_index_relaxed_fn; + decltype(hsa_queue_load_write_index_scacquire)* hsa_queue_load_write_index_scacquire_fn; + decltype(hsa_queue_load_write_index_relaxed)* hsa_queue_load_write_index_relaxed_fn; + decltype(hsa_queue_store_write_index_relaxed)* hsa_queue_store_write_index_relaxed_fn; + decltype(hsa_queue_store_write_index_screlease)* hsa_queue_store_write_index_screlease_fn; + decltype(hsa_queue_cas_write_index_scacq_screl)* hsa_queue_cas_write_index_scacq_screl_fn; + decltype(hsa_queue_cas_write_index_scacquire)* hsa_queue_cas_write_index_scacquire_fn; + decltype(hsa_queue_cas_write_index_relaxed)* hsa_queue_cas_write_index_relaxed_fn; + decltype(hsa_queue_cas_write_index_screlease)* hsa_queue_cas_write_index_screlease_fn; + decltype(hsa_queue_add_write_index_scacq_screl)* hsa_queue_add_write_index_scacq_screl_fn; + decltype(hsa_queue_add_write_index_scacquire)* hsa_queue_add_write_index_scacquire_fn; + decltype(hsa_queue_add_write_index_relaxed)* hsa_queue_add_write_index_relaxed_fn; + decltype(hsa_queue_add_write_index_screlease)* hsa_queue_add_write_index_screlease_fn; + decltype(hsa_queue_store_read_index_relaxed)* hsa_queue_store_read_index_relaxed_fn; + decltype(hsa_queue_store_read_index_screlease)* hsa_queue_store_read_index_screlease_fn; + decltype(hsa_agent_iterate_regions)* hsa_agent_iterate_regions_fn; + decltype(hsa_region_get_info)* hsa_region_get_info_fn; + decltype(hsa_agent_get_exception_policies)* hsa_agent_get_exception_policies_fn; + decltype(hsa_agent_extension_supported)* hsa_agent_extension_supported_fn; + decltype(hsa_memory_register)* hsa_memory_register_fn; + decltype(hsa_memory_deregister)* hsa_memory_deregister_fn; + decltype(hsa_memory_allocate)* hsa_memory_allocate_fn; + decltype(hsa_memory_free)* hsa_memory_free_fn; + decltype(hsa_memory_copy)* hsa_memory_copy_fn; + decltype(hsa_memory_assign_agent)* hsa_memory_assign_agent_fn; + decltype(hsa_signal_create)* hsa_signal_create_fn; + decltype(hsa_signal_destroy)* hsa_signal_destroy_fn; + decltype(hsa_signal_load_relaxed)* hsa_signal_load_relaxed_fn; + decltype(hsa_signal_load_scacquire)* hsa_signal_load_scacquire_fn; + decltype(hsa_signal_store_relaxed)* hsa_signal_store_relaxed_fn; + decltype(hsa_signal_store_screlease)* hsa_signal_store_screlease_fn; + decltype(hsa_signal_wait_relaxed)* hsa_signal_wait_relaxed_fn; + decltype(hsa_signal_wait_scacquire)* hsa_signal_wait_scacquire_fn; + decltype(hsa_signal_and_relaxed)* hsa_signal_and_relaxed_fn; + decltype(hsa_signal_and_scacquire)* hsa_signal_and_scacquire_fn; + decltype(hsa_signal_and_screlease)* hsa_signal_and_screlease_fn; + decltype(hsa_signal_and_scacq_screl)* hsa_signal_and_scacq_screl_fn; + decltype(hsa_signal_or_relaxed)* hsa_signal_or_relaxed_fn; + decltype(hsa_signal_or_scacquire)* hsa_signal_or_scacquire_fn; + decltype(hsa_signal_or_screlease)* hsa_signal_or_screlease_fn; + decltype(hsa_signal_or_scacq_screl)* hsa_signal_or_scacq_screl_fn; + decltype(hsa_signal_xor_relaxed)* hsa_signal_xor_relaxed_fn; + decltype(hsa_signal_xor_scacquire)* hsa_signal_xor_scacquire_fn; + decltype(hsa_signal_xor_screlease)* hsa_signal_xor_screlease_fn; + decltype(hsa_signal_xor_scacq_screl)* hsa_signal_xor_scacq_screl_fn; + decltype(hsa_signal_exchange_relaxed)* hsa_signal_exchange_relaxed_fn; + decltype(hsa_signal_exchange_scacquire)* hsa_signal_exchange_scacquire_fn; + decltype(hsa_signal_exchange_screlease)* hsa_signal_exchange_screlease_fn; + decltype(hsa_signal_exchange_scacq_screl)* hsa_signal_exchange_scacq_screl_fn; + decltype(hsa_signal_add_relaxed)* hsa_signal_add_relaxed_fn; + decltype(hsa_signal_add_scacquire)* hsa_signal_add_scacquire_fn; + decltype(hsa_signal_add_screlease)* hsa_signal_add_screlease_fn; + decltype(hsa_signal_add_scacq_screl)* hsa_signal_add_scacq_screl_fn; + decltype(hsa_signal_subtract_relaxed)* hsa_signal_subtract_relaxed_fn; + decltype(hsa_signal_subtract_scacquire)* hsa_signal_subtract_scacquire_fn; + decltype(hsa_signal_subtract_screlease)* hsa_signal_subtract_screlease_fn; + decltype(hsa_signal_subtract_scacq_screl)* hsa_signal_subtract_scacq_screl_fn; + decltype(hsa_signal_cas_relaxed)* hsa_signal_cas_relaxed_fn; + decltype(hsa_signal_cas_scacquire)* hsa_signal_cas_scacquire_fn; + decltype(hsa_signal_cas_screlease)* hsa_signal_cas_screlease_fn; + decltype(hsa_signal_cas_scacq_screl)* hsa_signal_cas_scacq_screl_fn; + + //===--- Instruction Set Architecture -----------------------------------===// + + decltype(hsa_isa_from_name)* hsa_isa_from_name_fn; + // Deprecated since v1.1. + decltype(hsa_isa_get_info)* hsa_isa_get_info_fn; + // Deprecated since v1.1. + decltype(hsa_isa_compatible)* hsa_isa_compatible_fn; + + //===--- Code Objects (deprecated) --------------------------------------===// + + // Deprecated since v1.1. + decltype(hsa_code_object_serialize)* hsa_code_object_serialize_fn; + // Deprecated since v1.1. + decltype(hsa_code_object_deserialize)* hsa_code_object_deserialize_fn; + // Deprecated since v1.1. + decltype(hsa_code_object_destroy)* hsa_code_object_destroy_fn; + // Deprecated since v1.1. + decltype(hsa_code_object_get_info)* hsa_code_object_get_info_fn; + // Deprecated since v1.1. + decltype(hsa_code_object_get_symbol)* hsa_code_object_get_symbol_fn; + // Deprecated since v1.1. + decltype(hsa_code_symbol_get_info)* hsa_code_symbol_get_info_fn; + // Deprecated since v1.1. + decltype(hsa_code_object_iterate_symbols)* hsa_code_object_iterate_symbols_fn; + + //===--- Executable -----------------------------------------------------===// + + // Deprecated since v1.1. + decltype(hsa_executable_create)* hsa_executable_create_fn; + decltype(hsa_executable_destroy)* hsa_executable_destroy_fn; + // Deprecated since v1.1. + decltype(hsa_executable_load_code_object)* hsa_executable_load_code_object_fn; + decltype(hsa_executable_freeze)* hsa_executable_freeze_fn; + decltype(hsa_executable_get_info)* hsa_executable_get_info_fn; + decltype(hsa_executable_global_variable_define)* + hsa_executable_global_variable_define_fn; + decltype(hsa_executable_agent_global_variable_define)* + hsa_executable_agent_global_variable_define_fn; + decltype(hsa_executable_readonly_variable_define)* + hsa_executable_readonly_variable_define_fn; + decltype(hsa_executable_validate)* hsa_executable_validate_fn; + // Deprecated since v1.1. + decltype(hsa_executable_get_symbol)* hsa_executable_get_symbol_fn; + decltype(hsa_executable_symbol_get_info)* hsa_executable_symbol_get_info_fn; + // Deprecated since v1.1. + decltype(hsa_executable_iterate_symbols)* hsa_executable_iterate_symbols_fn; + + //===--- Runtime Notifications ------------------------------------------===// + + decltype(hsa_status_string)* hsa_status_string_fn; + + // Start HSA v1.1 additions + decltype(hsa_extension_get_name)* hsa_extension_get_name_fn; + decltype(hsa_system_major_extension_supported)* hsa_system_major_extension_supported_fn; + decltype(hsa_system_get_major_extension_table)* hsa_system_get_major_extension_table_fn; + decltype(hsa_agent_major_extension_supported)* hsa_agent_major_extension_supported_fn; + decltype(hsa_cache_get_info)* hsa_cache_get_info_fn; + decltype(hsa_agent_iterate_caches)* hsa_agent_iterate_caches_fn; + decltype(hsa_signal_silent_store_relaxed)* hsa_signal_silent_store_relaxed_fn; + decltype(hsa_signal_silent_store_screlease)* hsa_signal_silent_store_screlease_fn; + decltype(hsa_signal_group_create)* hsa_signal_group_create_fn; + decltype(hsa_signal_group_destroy)* hsa_signal_group_destroy_fn; + decltype(hsa_signal_group_wait_any_scacquire)* hsa_signal_group_wait_any_scacquire_fn; + decltype(hsa_signal_group_wait_any_relaxed)* hsa_signal_group_wait_any_relaxed_fn; + + //===--- Instruction Set Architecture - HSA v1.1 additions --------------===// + + decltype(hsa_agent_iterate_isas)* hsa_agent_iterate_isas_fn; + decltype(hsa_isa_get_info_alt)* hsa_isa_get_info_alt_fn; + decltype(hsa_isa_get_exception_policies)* hsa_isa_get_exception_policies_fn; + decltype(hsa_isa_get_round_method)* hsa_isa_get_round_method_fn; + decltype(hsa_wavefront_get_info)* hsa_wavefront_get_info_fn; + decltype(hsa_isa_iterate_wavefronts)* hsa_isa_iterate_wavefronts_fn; + + //===--- Code Objects (deprecated) - HSA v1.1 additions -----------------===// + + // Deprecated since v1.1. + decltype(hsa_code_object_get_symbol_from_name)* + hsa_code_object_get_symbol_from_name_fn; + + //===--- Executable - HSA v1.1 additions --------------------------------===// + + decltype(hsa_code_object_reader_create_from_file)* + hsa_code_object_reader_create_from_file_fn; + decltype(hsa_code_object_reader_create_from_memory)* + hsa_code_object_reader_create_from_memory_fn; + decltype(hsa_code_object_reader_destroy)* hsa_code_object_reader_destroy_fn; + decltype(hsa_executable_create_alt)* hsa_executable_create_alt_fn; + decltype(hsa_executable_load_program_code_object)* + hsa_executable_load_program_code_object_fn; + decltype(hsa_executable_load_agent_code_object)* + hsa_executable_load_agent_code_object_fn; + decltype(hsa_executable_validate_alt)* hsa_executable_validate_alt_fn; + decltype(hsa_executable_get_symbol_by_name)* + hsa_executable_get_symbol_by_name_fn; + decltype(hsa_executable_iterate_agent_symbols)* + hsa_executable_iterate_agent_symbols_fn; + decltype(hsa_executable_iterate_program_symbols)* + hsa_executable_iterate_program_symbols_fn; +}; + +// Table to export HSA Apis from Core Runtime, Amd Extensions +// Finalizer and Images +struct HsaApiTable { + + // Version of Hsa Api Table + ApiTableVersion version; + + // Table of function pointers to HSA Core Runtime + CoreApiTable* core_; + + // Table of function pointers to AMD extensions + AmdExtTable* amd_ext_; + + // Table of function pointers to HSA Finalizer Extension + FinalizerExtTable* finalizer_ext_; + + // Table of function pointers to HSA Image Extension + ImageExtTable* image_ext_; + + // Table of function pointers for tools to use + ToolsApiTable* tools_; + + // Table of function pointers to AMD PC Sampling Extension + PcSamplingExtTable* pc_sampling_ext_; +}; + +// Structure containing instances of different api tables +struct HsaApiTableContainer { + HsaApiTable root; + CoreApiTable core; + AmdExtTable amd_ext; + FinalizerExtTable finalizer_ext; + ImageExtTable image_ext; + ToolsApiTable tools; + PcSamplingExtTable pc_sampling_ext; + + // Default initialization of a container instance + HsaApiTableContainer() { + root.version.major_id = HSA_API_TABLE_MAJOR_VERSION; + root.version.minor_id = sizeof(HsaApiTable); + root.version.step_id = HSA_API_TABLE_STEP_VERSION; + + core.version.major_id = HSA_CORE_API_TABLE_MAJOR_VERSION; + core.version.minor_id = sizeof(CoreApiTable); + core.version.step_id = HSA_CORE_API_TABLE_STEP_VERSION; + root.core_ = &core; + + amd_ext.version.major_id = HSA_AMD_EXT_API_TABLE_MAJOR_VERSION; + amd_ext.version.minor_id = sizeof(AmdExtTable); + amd_ext.version.step_id = HSA_AMD_EXT_API_TABLE_STEP_VERSION; + root.amd_ext_ = &amd_ext; + + finalizer_ext.version.major_id = HSA_FINALIZER_API_TABLE_MAJOR_VERSION; + finalizer_ext.version.minor_id = sizeof(FinalizerExtTable); + finalizer_ext.version.step_id = HSA_FINALIZER_API_TABLE_STEP_VERSION; + root.finalizer_ext_ = &finalizer_ext; + + image_ext.version.major_id = HSA_IMAGE_API_TABLE_MAJOR_VERSION; + image_ext.version.minor_id = sizeof(ImageExtTable); + image_ext.version.step_id = HSA_IMAGE_API_TABLE_STEP_VERSION; + root.image_ext_ = &image_ext; + + tools.version.major_id = HSA_TOOLS_API_TABLE_MAJOR_VERSION; + tools.version.minor_id = sizeof(ToolsApiTable); + tools.version.step_id = HSA_TOOLS_API_TABLE_STEP_VERSION; + root.tools_ = &tools; + + pc_sampling_ext.version.major_id = HSA_PC_SAMPLING_API_TABLE_MAJOR_VERSION; + pc_sampling_ext.version.minor_id = sizeof(PcSamplingExtTable); + pc_sampling_ext.version.step_id = HSA_PC_SAMPLING_API_TABLE_STEP_VERSION; + root.pc_sampling_ext_ = &pc_sampling_ext; + } +}; + +// Api to copy function pointers of a table +static +void inline copyApi(void* src, void* dest, size_t size) { + assert(size >= sizeof(ApiTableVersion)); + memcpy((char*)src + sizeof(ApiTableVersion), + (char*)dest + sizeof(ApiTableVersion), + (size - sizeof(ApiTableVersion))); +} + +// Copy Api child tables if valid. +static void inline copyElement(ApiTableVersion* dest, ApiTableVersion* src) { + if (src->major_id && (dest->major_id == src->major_id)) { + dest->step_id = src->step_id; + dest->minor_id = Min(dest->minor_id, src->minor_id); + copyApi(dest, src, dest->minor_id); + } else { + dest->major_id = 0; + dest->minor_id = 0; + dest->step_id = 0; + } +} + +// Copy constructor for all Api tables. The function assumes the +// user has initialized an instance of tables container correctly +// for the Major, Minor and Stepping Ids of Root and Child Api tables. +// The function will overwrite the value of Minor Id by taking the +// minimum of source and destination parameters. It will also overwrite +// the stepping Id with value from source parameter. +static void inline copyTables(const HsaApiTable* src, HsaApiTable* dest) { + // Verify Major Id of source and destination tables match + if (dest->version.major_id != src->version.major_id) { + dest->version.major_id = 0; + dest->version.minor_id = 0; + dest->version.step_id = 0; + return; + } + + // Initialize the stepping id and minor id of root table. For the + // minor id which encodes struct size, take the minimum of source + // and destination parameters + dest->version.step_id = src->version.step_id; + dest->version.minor_id = Min(dest->version.minor_id, src->version.minor_id); + + // Copy child tables if present + if ((offsetof(HsaApiTable, core_) < dest->version.minor_id)) + copyElement(&dest->core_->version, &src->core_->version); + if ((offsetof(HsaApiTable, amd_ext_) < dest->version.minor_id)) + copyElement(&dest->amd_ext_->version, &src->amd_ext_->version); + if ((offsetof(HsaApiTable, finalizer_ext_) < dest->version.minor_id)) + copyElement(&dest->finalizer_ext_->version, &src->finalizer_ext_->version); + if ((offsetof(HsaApiTable, image_ext_) < dest->version.minor_id)) + copyElement(&dest->image_ext_->version, &src->image_ext_->version); + if ((offsetof(HsaApiTable, tools_) < dest->version.minor_id)) + copyElement(&dest->tools_->version, &src->tools_->version); + if ((offsetof(HsaApiTable, pc_sampling_ext_) < dest->version.minor_id)) + copyElement(&dest->pc_sampling_ext_->version, &src->pc_sampling_ext_->version); +} +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_api_trace_version.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_api_trace_version.h new file mode 100644 index 0000000000000000000000000000000000000000..3393a776207bf0e63340e75d23ca83aa2595e41d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_api_trace_version.h @@ -0,0 +1,68 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// The University of Illinois/NCSA +// Open Source License (NCSA) +// +// Copyright (c) 2014-2024, Advanced Micro Devices, Inc. All rights reserved. +// +// Developed by: +// +// AMD Research and AMD HSA Software Development +// +// Advanced Micro Devices, Inc. +// +// www.amd.com +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal with 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: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimers in +// the documentation and/or other materials provided with the distribution. +// - Neither the names of Advanced Micro Devices, Inc, +// nor the names of its contributors may be used to endorse or promote +// products derived from this Software without specific prior written +// permission. +// +// 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 CONTRIBUTORS 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 WITH THE SOFTWARE. +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef HSA_RUNTIME_INC_HSA_API_TRACE_VERSION_H +#define HSA_RUNTIME_INC_HSA_API_TRACE_VERSION_H + +// CODE IN THIS FILE **MUST** BE C-COMPATIBLE + +// Major Ids of the Api tables exported by Hsa Core Runtime +#define HSA_API_TABLE_MAJOR_VERSION 0x03 +#define HSA_CORE_API_TABLE_MAJOR_VERSION 0x02 +#define HSA_AMD_EXT_API_TABLE_MAJOR_VERSION 0x02 +#define HSA_FINALIZER_API_TABLE_MAJOR_VERSION 0x02 +#define HSA_IMAGE_API_TABLE_MAJOR_VERSION 0x02 +#define HSA_AQLPROFILE_API_TABLE_MAJOR_VERSION 0x01 +#define HSA_TOOLS_API_TABLE_MAJOR_VERSION 0x01 +#define HSA_PC_SAMPLING_API_TABLE_MAJOR_VERSION 0x01 + +// Step Ids of the Api tables exported by Hsa Core Runtime +#define HSA_API_TABLE_STEP_VERSION 0x01 +#define HSA_CORE_API_TABLE_STEP_VERSION 0x00 +#define HSA_AMD_EXT_API_TABLE_STEP_VERSION 0x03 +#define HSA_FINALIZER_API_TABLE_STEP_VERSION 0x00 +#define HSA_IMAGE_API_TABLE_STEP_VERSION 0x00 +#define HSA_AQLPROFILE_API_TABLE_STEP_VERSION 0x00 +#define HSA_TOOLS_API_TABLE_STEP_VERSION 0x00 +#define HSA_PC_SAMPLING_API_TABLE_STEP_VERSION 0x00 + +#endif // HSA_RUNTIME_INC_HSA_API_TRACE_VERSION_H diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_ext_amd.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_ext_amd.h new file mode 100644 index 0000000000000000000000000000000000000000..df2266f4c1cb473eaae9b06a4c624e4ed6ebd93d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_ext_amd.h @@ -0,0 +1,3147 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// The University of Illinois/NCSA +// Open Source License (NCSA) +// +// Copyright (c) 2014-2020, Advanced Micro Devices, Inc. All rights reserved. +// +// Developed by: +// +// AMD Research and AMD HSA Software Development +// +// Advanced Micro Devices, Inc. +// +// www.amd.com +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal with 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: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimers in +// the documentation and/or other materials provided with the distribution. +// - Neither the names of Advanced Micro Devices, Inc, +// nor the names of its contributors may be used to endorse or promote +// products derived from this Software without specific prior written +// permission. +// +// 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 CONTRIBUTORS 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 WITH THE SOFTWARE. +// +//////////////////////////////////////////////////////////////////////////////// + +// HSA AMD extension. + +#ifndef HSA_RUNTIME_EXT_AMD_H_ +#define HSA_RUNTIME_EXT_AMD_H_ + +#include "hsa.h" +#include "hsa_ext_image.h" +#include "hsa_ven_amd_pc_sampling.h" + +/** + * - 1.0 - initial version + * - 1.1 - dmabuf export + * - 1.2 - hsa_amd_memory_async_copy_on_engine + * - 1.3 - HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_EXTENDED_SCOPE_FINE_GRAINED pool + * - 1.4 - Virtual Memory API + * - 1.5 - hsa_amd_agent_info: HSA_AMD_AGENT_INFO_MEMORY_PROPERTIES + * - 1.6 - Virtual Memory API: hsa_amd_vmem_address_reserve_align + */ +#define HSA_AMD_INTERFACE_VERSION_MAJOR 1 +#define HSA_AMD_INTERFACE_VERSION_MINOR 6 + +#ifdef __cplusplus +extern "C" { +#endif + +/** \addtogroup aql Architected Queuing Language + * @{ + */ + +/** + * @brief Macro to use to determine that a flag is set when querying flags within uint8_t[8] + * types + */ +static __inline__ __attribute__((always_inline)) bool hsa_flag_isset64(uint8_t* value, + uint32_t bit) { + unsigned int index = bit / 8; + unsigned int subBit = bit % 8; + return ((uint8_t*)value)[index] & (1 << subBit); +} + +/** + * @brief A fixed-size type used to represent ::hsa_signal_condition_t constants. + */ +typedef uint32_t hsa_signal_condition32_t; + +/** + * @brief AMD vendor specific packet type. + */ +typedef enum { + /** + * Packet used by agents to delay processing of subsequent packets until a + * configurable condition is satisfied by an HSA signal. Only kernel dispatch + * queues created from AMD GPU Agents support this packet. + */ + HSA_AMD_PACKET_TYPE_BARRIER_VALUE = 2, +} hsa_amd_packet_type_t; + +/** + * @brief A fixed-size type used to represent ::hsa_amd_packet_type_t constants. + */ +typedef uint8_t hsa_amd_packet_type8_t; + +/** + * @brief AMD vendor specific AQL packet header + */ +typedef struct hsa_amd_packet_header_s { + /** + * Packet header. Used to configure multiple packet parameters such as the + * packet type. The parameters are described by ::hsa_packet_header_t. + */ + uint16_t header; + + /** + *Format of the vendor specific packet. + */ + hsa_amd_packet_type8_t AmdFormat; + + /** + * Reserved. Must be 0. + */ + uint8_t reserved; +} hsa_amd_vendor_packet_header_t; + +/** + * @brief AMD barrier value packet. Halts packet processing and waits for + * (signal_value & ::mask) ::cond ::value to be satisfied, where signal_value + * is the value of the signal ::signal. + */ +typedef struct hsa_amd_barrier_value_packet_s { + /** + * AMD vendor specific packet header. + */ + hsa_amd_vendor_packet_header_t header; + + /** + * Reserved. Must be 0. + */ + uint32_t reserved0; + + /** + * Dependent signal object. A signal with a handle value of 0 is + * allowed and is interpreted by the packet processor a satisfied + * dependency. + */ + hsa_signal_t signal; + + /** + * Value to compare against. + */ + hsa_signal_value_t value; + + /** + * Bit mask to be combined by bitwise AND with ::signal's value. + */ + hsa_signal_value_t mask; + + /** + * Comparison operation. See ::hsa_signal_condition_t. + */ + hsa_signal_condition32_t cond; + + /** + * Reserved. Must be 0. + */ + uint32_t reserved1; + + /** + * Reserved. Must be 0. + */ + uint64_t reserved2; + + /** + * Reserved. Must be 0. + */ + uint64_t reserved3; + + /** + * Signal used to indicate completion of the job. The application can use the + * special signal handle 0 to indicate that no signal is used. + */ + hsa_signal_t completion_signal; +} hsa_amd_barrier_value_packet_t; + +/** @} */ + +/** + * @brief Enumeration constants added to ::hsa_status_t. + * + * @remark Additions to hsa_status_t + */ +enum { + /** + * The memory pool is invalid. + */ + HSA_STATUS_ERROR_INVALID_MEMORY_POOL = 40, + + /** + * Agent accessed memory beyond the maximum legal address. + */ + HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION = 41, + + /** + * Agent executed an invalid shader instruction. + */ + HSA_STATUS_ERROR_ILLEGAL_INSTRUCTION = 42, + + /** + * Agent attempted to access an inaccessible address. + * See hsa_amd_register_system_event_handler and + * HSA_AMD_GPU_MEMORY_FAULT_EVENT for more information on illegal accesses. + */ + HSA_STATUS_ERROR_MEMORY_FAULT = 43, + + /** + * The CU mask was successfully set but the mask attempted to enable a CU + * which was disabled for the process. CUs disabled for the process remain + * disabled. + */ + HSA_STATUS_CU_MASK_REDUCED = 44, + + /** + * Exceeded number of VGPRs available on this agent + */ + HSA_STATUS_ERROR_OUT_OF_REGISTERS = 45, + + /** + * Resource is busy or temporarily unavailable + */ + HSA_STATUS_ERROR_RESOURCE_BUSY = 46, +}; + +/** + * @brief IOMMU version supported + */ +typedef enum { + /** + * IOMMU not supported + */ + HSA_IOMMU_SUPPORT_NONE = 0, + /* IOMMU V1 support is not relevant to user applications, so not reporting it */ + /** + * IOMMU V2 supported + */ + HSA_IOMMU_SUPPORT_V2 = 1, +} hsa_amd_iommu_version_t; + +/** + * @brief Agent attributes. + */ +typedef enum hsa_amd_agent_info_s { + /** + * Chip identifier. The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_CHIP_ID = 0xA000, + /** + * Size of a cacheline in bytes. The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_CACHELINE_SIZE = 0xA001, + /** + * The number of compute unit available in the agent. The type of this + * attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_COMPUTE_UNIT_COUNT = 0xA002, + /** + * The maximum clock frequency of the agent in MHz. The type of this + * attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_MAX_CLOCK_FREQUENCY = 0xA003, + /** + * Internal driver node identifier. The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_DRIVER_NODE_ID = 0xA004, + /** + * Max number of watch points on memory address ranges to generate exception + * events when the watched addresses are accessed. The type of this + * attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_MAX_ADDRESS_WATCH_POINTS = 0xA005, + /** + * Agent BDF_ID, named LocationID in thunk. The type of this attribute is + * uint32_t. + */ + HSA_AMD_AGENT_INFO_BDFID = 0xA006, + /** + * Memory Interface width, the return value type is uint32_t. + * This attribute is deprecated. + */ + HSA_AMD_AGENT_INFO_MEMORY_WIDTH = 0xA007, + /** + * Max Memory Clock, the return value type is uint32_t. + */ + HSA_AMD_AGENT_INFO_MEMORY_MAX_FREQUENCY = 0xA008, + /** + * Board name of Agent - populated from MarketingName of Kfd Node + * The value is an Ascii string of 64 chars. + */ + HSA_AMD_AGENT_INFO_PRODUCT_NAME = 0xA009, + /** + * Maximum number of waves possible in a Compute Unit. + * The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_MAX_WAVES_PER_CU = 0xA00A, + /** + * Number of SIMD's per compute unit CU + * The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_NUM_SIMDS_PER_CU = 0xA00B, + /** + * Number of Shader Engines (SE) in Gpu + * The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_NUM_SHADER_ENGINES = 0xA00C, + /** + * Number of Shader Arrays Per Shader Engines in Gpu + * The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_NUM_SHADER_ARRAYS_PER_SE = 0xA00D, + /** + * Address of the HDP flush registers. Use of these registers does not conform to the HSA memory + * model and should be treated with caution. + * The type of this attribute is hsa_amd_hdp_flush_t. + */ + HSA_AMD_AGENT_INFO_HDP_FLUSH = 0xA00E, + /** + * PCIe domain for the agent. Pairs with HSA_AMD_AGENT_INFO_BDFID + * to give the full physical location of the Agent. + * The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_DOMAIN = 0xA00F, + /** + * Queries for support of cooperative queues. See ::HSA_QUEUE_TYPE_COOPERATIVE. + * The type of this attribute is bool. + */ + HSA_AMD_AGENT_INFO_COOPERATIVE_QUEUES = 0xA010, + /** + * Queries UUID of an agent. The value is an Ascii string with a maximum + * of 21 chars including NUL. The string value consists of two parts: header + * and body. The header identifies device type (GPU, CPU, DSP) while body + * encodes UUID as a 16 digit hex string + * + * Agents that do not support UUID will return the string "GPU-XX" or + * "CPU-XX" or "DSP-XX" depending upon their device type ::hsa_device_type_t + */ + HSA_AMD_AGENT_INFO_UUID = 0xA011, + /** + * Queries for the ASIC revision of an agent. The value is an integer that + * increments for each revision. This can be used by user-level software to + * change how it operates, depending on the hardware version. This allows + * selective workarounds for hardware errata. + * The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_ASIC_REVISION = 0xA012, + /** + * Queries whether or not the host can directly access SVM memory that is + * physically resident in the agent's local memory. + * The type of this attribute is bool. + */ + HSA_AMD_AGENT_INFO_SVM_DIRECT_HOST_ACCESS = 0xA013, + /** + * Some processors support more CUs than can reliably be used in a cooperative + * dispatch. This queries the count of CUs which are fully enabled for + * cooperative dispatch. + * The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_COOPERATIVE_COMPUTE_UNIT_COUNT = 0xA014, + /** + * Queries the amount of memory available in bytes accross all global pools + * owned by the agent. + * The type of this attribute is uint64_t. + */ + HSA_AMD_AGENT_INFO_MEMORY_AVAIL = 0xA015, + /** + * Timestamp value increase rate, in Hz. The timestamp (clock) frequency is + * in the range 1-400MHz. + * The type of this attribute is uint64_t. + */ + HSA_AMD_AGENT_INFO_TIMESTAMP_FREQUENCY = 0xA016, + /** + * Queries for the ASIC family ID of an agent. + * The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_ASIC_FAMILY_ID = 0xA107, + /** + * Queries for the Packet Processor(CP Firmware) ucode version of an agent. + * The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_UCODE_VERSION = 0xA108, + /** + * Queries for the SDMA engine ucode of an agent. + * The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_SDMA_UCODE_VERSION = 0xA109, + /** + * Queries the number of SDMA engines. + * If HSA_AMD_AGENT_INFO_NUM_SDMA_XGMI_ENG query returns non-zero, + * this query returns the number of SDMA engines optimized for + * host to device bidirectional traffic. + * The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_NUM_SDMA_ENG = 0xA10A, + /** + * Queries the number of additional SDMA engines optimized for D2D xGMI copies. + * The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_NUM_SDMA_XGMI_ENG = 0xA10B, + /** + * Queries for version of IOMMU supported by agent. + * The type of this attribute is hsa_amd_iommu_version_t. + */ + HSA_AMD_AGENT_INFO_IOMMU_SUPPORT = 0xA110, + /** + * Queries for number of XCCs within the agent. + * The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_NUM_XCC = 0xA111, + /** + * Queries for driver unique identifier. + * The type of this attribute is uint32_t. + */ + HSA_AMD_AGENT_INFO_DRIVER_UID = 0xA112, + /** + * Returns the hsa_agent_t of the nearest CPU agent + * The type of this attribute is hsa_agent_t. + */ + HSA_AMD_AGENT_INFO_NEAREST_CPU = 0xA113, + /** + * Bit-mask indicating memory properties of this agent. A memory property is set if the flag bit + * is set at that position. User may use the hsa_flag_isset64 macro to verify whether a flag + * is set. The type of this attribute is uint8_t[8]. + */ + HSA_AMD_AGENT_INFO_MEMORY_PROPERTIES = 0xA114, + /** + * Bit-mask indicating AQL Extensions supported by this agent. An AQL extension is set if the flag + * bit is set at that position. User may use the hsa_flag_isset64 macro to verify whether a flag + * is set. The type of this attribute is uint8_t[8]. + */ + HSA_AMD_AGENT_INFO_AQL_EXTENSIONS = 0xA115 /* Not implemented yet */ +} hsa_amd_agent_info_t; + +/** + * @brief Agent memory properties attributes + */ +typedef enum hsa_amd_agent_memory_properties_s { + HSA_AMD_MEMORY_PROPERTY_AGENT_IS_APU = (1 << 0), +} hsa_amd_agent_memory_properties_t; + +/** + * @brief SDMA engine IDs unique by single set bit position. + */ +typedef enum hsa_amd_sdma_engine_id { + HSA_AMD_SDMA_ENGINE_0 = 0x1, + HSA_AMD_SDMA_ENGINE_1 = 0x2, + HSA_AMD_SDMA_ENGINE_2 = 0x4, + HSA_AMD_SDMA_ENGINE_3 = 0x8, + HSA_AMD_SDMA_ENGINE_4 = 0x10, + HSA_AMD_SDMA_ENGINE_5 = 0x20, + HSA_AMD_SDMA_ENGINE_6 = 0x40, + HSA_AMD_SDMA_ENGINE_7 = 0x80, + HSA_AMD_SDMA_ENGINE_8 = 0x100, + HSA_AMD_SDMA_ENGINE_9 = 0x200, + HSA_AMD_SDMA_ENGINE_10 = 0x400, + HSA_AMD_SDMA_ENGINE_11 = 0x800, + HSA_AMD_SDMA_ENGINE_12 = 0x1000, + HSA_AMD_SDMA_ENGINE_13 = 0x2000, + HSA_AMD_SDMA_ENGINE_14 = 0x4000, + HSA_AMD_SDMA_ENGINE_15 = 0x8000 +} hsa_amd_sdma_engine_id_t; + +typedef struct hsa_amd_hdp_flush_s { + uint32_t* HDP_MEM_FLUSH_CNTL; + uint32_t* HDP_REG_FLUSH_CNTL; +} hsa_amd_hdp_flush_t; + +/** + * @brief Region attributes. + */ +typedef enum hsa_amd_region_info_s { + /** + * Determine if host can access the region. The type of this attribute + * is bool. + */ + HSA_AMD_REGION_INFO_HOST_ACCESSIBLE = 0xA000, + /** + * Base address of the region in flat address space. + */ + HSA_AMD_REGION_INFO_BASE = 0xA001, + /** + * Memory Interface width, the return value type is uint32_t. + * This attribute is deprecated. Use HSA_AMD_AGENT_INFO_MEMORY_WIDTH. + */ + HSA_AMD_REGION_INFO_BUS_WIDTH = 0xA002, + /** + * Max Memory Clock, the return value type is uint32_t. + * This attribute is deprecated. Use HSA_AMD_AGENT_INFO_MEMORY_MAX_FREQUENCY. + */ + HSA_AMD_REGION_INFO_MAX_CLOCK_FREQUENCY = 0xA003, +} hsa_amd_region_info_t; + +/** + * @brief Coherency attributes of fine grain region. + */ +typedef enum hsa_amd_coherency_type_s { + /** + * Coherent region. + */ + HSA_AMD_COHERENCY_TYPE_COHERENT = 0, + /** + * Non coherent region. + */ + HSA_AMD_COHERENCY_TYPE_NONCOHERENT = 1 +} hsa_amd_coherency_type_t; + +/** + * @brief Get the coherency type of the fine grain region of an agent. + * + * @param[in] agent A valid agent. + * + * @param[out] type Pointer to a memory location where the HSA runtime will + * store the coherency type of the fine grain region. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p type is NULL. + */ +hsa_status_t HSA_API hsa_amd_coherency_get_type(hsa_agent_t agent, + hsa_amd_coherency_type_t* type); + +/** + * @brief Set the coherency type of the fine grain region of an agent. + * Deprecated. This is supported on KV platforms. For backward compatibility + * other platforms will spuriously succeed. + * + * @param[in] agent A valid agent. + * + * @param[in] type The coherency type to be set. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p type is invalid. + */ +hsa_status_t HSA_API hsa_amd_coherency_set_type(hsa_agent_t agent, + hsa_amd_coherency_type_t type); + +/** + * @brief Structure containing profiling dispatch time information. + * + * Times are reported as ticks in the domain of the HSA system clock. + * The HSA system clock tick and frequency is obtained via hsa_system_get_info. + */ +typedef struct hsa_amd_profiling_dispatch_time_s { + /** + * Dispatch packet processing start time. + */ + uint64_t start; + /** + * Dispatch packet completion time. + */ + uint64_t end; +} hsa_amd_profiling_dispatch_time_t; + +/** + * @brief Structure containing profiling async copy time information. + * + * Times are reported as ticks in the domain of the HSA system clock. + * The HSA system clock tick and frequency is obtained via hsa_system_get_info. + */ +typedef struct hsa_amd_profiling_async_copy_time_s { + /** + * Async copy processing start time. + */ + uint64_t start; + /** + * Async copy completion time. + */ + uint64_t end; +} hsa_amd_profiling_async_copy_time_t; + +/** + * @brief Enable or disable profiling capability of a queue. + * + * @param[in] queue A valid queue. + * + * @param[in] enable 1 to enable profiling. 0 to disable profiling. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_QUEUE The queue is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p queue is NULL. + */ +hsa_status_t HSA_API + hsa_amd_profiling_set_profiler_enabled(hsa_queue_t* queue, int enable); + +/** + * @brief Enable or disable asynchronous memory copy profiling. + * + * @details The runtime will provide the copy processing start timestamp and + * completion timestamp of each call to hsa_amd_memory_async_copy if the + * async copy profiling is enabled prior to the call to + * hsa_amd_memory_async_copy. The completion signal object is used to + * hold the last async copy start and end timestamp. The client can retrieve + * these timestamps via call to hsa_amd_profiling_get_async_copy_time. + * + * @param[in] enable True to enable profiling. False to disable profiling. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES Failed on allocating resources + * needed to profile the asynchronous copy. + */ +hsa_status_t HSA_API + hsa_amd_profiling_async_copy_enable(bool enable); + +/** + * @brief Retrieve packet processing time stamps. + * + * @param[in] agent The agent with which the signal was last used. For + * instance, if the profiled dispatch packet is dispatched onto queue Q, + * which was created on agent A, then this parameter must be A. + * + * @param[in] signal A signal used as the completion signal of the dispatch + * packet to retrieve time stamps from. This dispatch packet must have been + * issued to a queue with profiling enabled and have already completed. Also + * the signal must not have yet been used in any other packet following the + * completion of the profiled dispatch packet. + * + * @param[out] time Packet processing timestamps in the HSA system clock + * domain. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_SIGNAL The signal is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p time is NULL. + */ +hsa_status_t HSA_API hsa_amd_profiling_get_dispatch_time( + hsa_agent_t agent, hsa_signal_t signal, + hsa_amd_profiling_dispatch_time_t* time); + +/** + * @brief Retrieve asynchronous copy timestamps. + * + * @details Async copy profiling is enabled via call to + * hsa_amd_profiling_async_copy_enable. + * + * @param[in] signal A signal used as the completion signal of the call to + * hsa_amd_memory_async_copy. + * + * @param[out] time Async copy processing timestamps in the HSA system clock + * domain. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_SIGNAL The signal is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p time is NULL. + */ +hsa_status_t HSA_API hsa_amd_profiling_get_async_copy_time( + hsa_signal_t signal, hsa_amd_profiling_async_copy_time_t* time); + +/** + * @brief Computes the frequency ratio and offset between the agent clock and + * HSA system clock and converts the agent's tick to HSA system domain tick. + * + * @param[in] agent The agent used to retrieve the agent_tick. It is user's + * responsibility to make sure the tick number is from this agent, otherwise, + * the behavior is undefined. + * + * @param[in] agent_tick The tick count retrieved from the specified @p agent. + * + * @param[out] system_tick The translated HSA system domain clock counter tick. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p system_tick is NULL; + */ +hsa_status_t HSA_API + hsa_amd_profiling_convert_tick_to_system_domain(hsa_agent_t agent, + uint64_t agent_tick, + uint64_t* system_tick); + +/** + * @brief Signal attribute flags. + */ +typedef enum { + /** + * Signal will only be consumed by AMD GPUs. Limits signal consumption to + * AMD GPU agents only. Ignored if @p num_consumers is not zero (all agents). + */ + HSA_AMD_SIGNAL_AMD_GPU_ONLY = 1, + /** + * Signal may be used for interprocess communication. + * IPC signals can be read, written, and waited on from any process. + * Profiling using an IPC enabled signal is only supported in a single process + * at a time. Producing profiling data in one process and consuming it in + * another process is undefined. + */ + HSA_AMD_SIGNAL_IPC = 2, +} hsa_amd_signal_attribute_t; + +/** + * @brief Create a signal with specific attributes. + * + * @param[in] initial_value Initial value of the signal. + * + * @param[in] num_consumers Size of @p consumers. A value of 0 indicates that + * any agent might wait on the signal. + * + * @param[in] consumers List of agents that might consume (wait on) the + * signal. If @p num_consumers is 0, this argument is ignored; otherwise, the + * HSA runtime might use the list to optimize the handling of the signal + * object. If an agent not listed in @p consumers waits on the returned + * signal, the behavior is undefined. The memory associated with @p consumers + * can be reused or freed after the function returns. + * + * @param[in] attributes Requested signal attributes. Multiple signal attributes + * may be requested by combining them with bitwise OR. Requesting no attributes + * (@p attributes == 0) results in the same signal as would have been obtained + * via hsa_signal_create. + * + * @param[out] signal Pointer to a memory location where the HSA runtime will + * store the newly created signal handle. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to allocate + * the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p signal is NULL, @p + * num_consumers is greater than 0 but @p consumers is NULL, or @p consumers + * contains duplicates. + */ +hsa_status_t HSA_API hsa_amd_signal_create(hsa_signal_value_t initial_value, uint32_t num_consumers, + const hsa_agent_t* consumers, uint64_t attributes, + hsa_signal_t* signal); + +/** + * @brief Returns a pointer to the value of a signal. + * + * Use of this API does not modify the lifetime of ::signal and any + * hsa_signal_value_t retrieved by this API has lifetime equal to that of + * ::signal. + * + * This API is intended for partial interoperability with non-HSA compatible + * devices and should not be used where HSA interfaces are available. + * + * Use of the signal value must comply with use restritions of ::signal. + * Use may result in data races if the operations performed are not platform + * atomic. Use with HSA_AMD_SIGNAL_AMD_GPU_ONLY or HSA_AMD_SIGNAL_IPC + * attributed signals is required. + * + * @param[in] Signal handle to extract the signal value pointer from. + * + * @param[out] Location where the extracted signal value pointer will be placed. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_SIGNAL signal is not a valid hsa_signal_t + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT value_ptr is NULL. + */ +hsa_status_t hsa_amd_signal_value_pointer(hsa_signal_t signal, + volatile hsa_signal_value_t** value_ptr); + +/** + * @brief Asyncronous signal handler function type. + * + * @details Type definition of callback function to be used with + * hsa_amd_signal_async_handler. This callback is invoked if the associated + * signal and condition are met. The callback receives the value of the signal + * which satisfied the associated wait condition and a user provided value. If + * the callback returns true then the callback will be called again if the + * associated signal and condition are satisfied again. If the callback returns + * false then it will not be called again. + * + * @param[in] value Contains the value of the signal observed by + * hsa_amd_signal_async_handler which caused the signal handler to be invoked. + * + * @param[in] arg Contains the user provided value given when the signal handler + * was registered with hsa_amd_signal_async_handler + * + * @retval true resumes monitoring the signal with this handler (as if calling + * hsa_amd_signal_async_handler again with identical parameters) + * + * @retval false stops monitoring the signal with this handler (handler will + * not be called again for this signal) + * + */ +typedef bool (*hsa_amd_signal_handler)(hsa_signal_value_t value, void* arg); + +/** + * @brief Register asynchronous signal handler function. + * + * @details Allows registering a callback function and user provided value with + * a signal and wait condition. The callback will be invoked if the associated + * signal and wait condition are satisfied. Callbacks will be invoked serially + * but in an arbitrary order so callbacks should be independent of each other. + * After being invoked a callback may continue to wait for its associated signal + * and condition and, possibly, be invoked again. Or the callback may stop + * waiting. If the callback returns true then it will continue waiting and may + * be called again. If false then the callback will not wait again and will not + * be called again for the associated signal and condition. It is possible to + * register the same callback multiple times with the same or different signals + * and/or conditions. Each registration of the callback will be treated entirely + * independently. + * + * @param[in] signal hsa signal to be asynchronously monitored + * + * @param[in] cond condition value to monitor for + * + * @param[in] value signal value used in condition expression + * + * @param[in] handler asynchronous signal handler invoked when signal's + * condition is met + * + * @param[in] arg user provided value which is provided to handler when handler + * is invoked + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_SIGNAL signal is not a valid hsa_signal_t + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT handler is invalid (NULL) + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime is out of + * resources or blocking signals are not supported by the HSA driver component. + * + */ +hsa_status_t HSA_API + hsa_amd_signal_async_handler(hsa_signal_t signal, + hsa_signal_condition_t cond, + hsa_signal_value_t value, + hsa_amd_signal_handler handler, void* arg); + +/** + * @brief Call a function asynchronously + * + * @details Provides access to the runtime's asynchronous event handling thread + * for general asynchronous functions. Functions queued this way are executed + * in the same manner as if they were a signal handler who's signal is + * satisfied. + * + * @param[in] callback asynchronous function to be invoked + * + * @param[in] arg user provided value which is provided to handler when handler + * is invoked + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT handler is invalid (NULL) + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime is out of + * resources or blocking signals are not supported by the HSA driver component. + * + */ +hsa_status_t HSA_API + hsa_amd_async_function(void (*callback)(void* arg), void* arg); + +/** + * @brief Wait for any signal-condition pair to be satisfied. + * + * @details Allows waiting for any of several signal and conditions pairs to be + * satisfied. The function returns the index into the list of signals of the + * first satisfying signal-condition pair. The value of the satisfying signal's + * value is returned in satisfying_value unless satisfying_value is NULL. This + * function provides only relaxed memory semantics. + */ +uint32_t HSA_API + hsa_amd_signal_wait_any(uint32_t signal_count, hsa_signal_t* signals, + hsa_signal_condition_t* conds, + hsa_signal_value_t* values, uint64_t timeout_hint, + hsa_wait_state_t wait_hint, + hsa_signal_value_t* satisfying_value); + +/** + * @brief Query image limits. + * + * @param[in] agent A valid agent. + * + * @param[in] attribute HSA image info attribute to query. + * + * @param[out] value Pointer to an application-allocated buffer where to store + * the value of the attribute. If the buffer passed by the application is not + * large enough to hold the value of @p attribute, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_QUEUE @p value is NULL or @p attribute < + * HSA_EXT_AGENT_INFO_IMAGE_1D_MAX_ELEMENTS or @p attribute > + * HSA_EXT_AGENT_INFO_IMAGE_ARRAY_MAX_LAYERS. + * + */ +hsa_status_t HSA_API hsa_amd_image_get_info_max_dim(hsa_agent_t agent, + hsa_agent_info_t attribute, + void* value); + +/** + * @brief Set a queue's CU affinity mask. + * + * @details Enables the queue to run on only selected CUs. The given mask is + * combined by bitwise AND with any device wide mask in HSA_CU_MASK before + * being applied. + * If num_cu_mask_count is 0 then the request is interpreted as a request to + * enable all CUs and no cu_mask array need be given. + * + * @param[in] queue A pointer to HSA queue. + * + * @param[in] num_cu_mask_count Size of CUMask bit array passed in, in bits. + * + * @param[in] cu_mask Bit-vector representing the CU mask. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_CU_MASK_REDUCED The function was successfully executed + * but the given mask attempted to enable a CU which was disabled by + * HSA_CU_MASK. CUs disabled by HSA_CU_MASK remain disabled. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_QUEUE @p queue is NULL or invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p num_cu_mask_count is not + * a multiple of 32 or @p num_cu_mask_count is not 0 and cu_mask is NULL. + * Devices with work group processors must even-index contiguous pairwise + * CU enable e.g. 0x33(b'110011) is valid while 0x5(0x101) and 0x6(b'0110) + * are invalid. + * + */ +hsa_status_t HSA_API hsa_amd_queue_cu_set_mask(const hsa_queue_t* queue, + uint32_t num_cu_mask_count, + const uint32_t* cu_mask); + +/** + * @brief Retrieve a queue's CU affinity mask. + * + * @details Returns the first num_cu_mask_count bits of a queue's CU mask. + * Ensure that num_cu_mask_count is at least as large as + * HSA_AMD_AGENT_INFO_COMPUTE_UNIT_COUNT to retrieve the entire mask. + * + * @param[in] queue A pointer to HSA queue. + * + * @param[in] num_cu_mask_count Size of CUMask bit array passed in, in bits. + * + * @param[out] cu_mask Bit-vector representing the CU mask. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_QUEUE @p queue is NULL or invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p num_cu_mask_count is 0, not + * a multiple of 32 or @p cu_mask is NULL. + * + */ +hsa_status_t HSA_API hsa_amd_queue_cu_get_mask(const hsa_queue_t* queue, uint32_t num_cu_mask_count, + uint32_t* cu_mask); + +/** + * @brief Memory segments associated with a memory pool. + */ +typedef enum { + /** + * Global segment. Used to hold data that is shared by all agents. + */ + HSA_AMD_SEGMENT_GLOBAL = 0, + /** + * Read-only segment. Used to hold data that remains constant during the + * execution of a kernel. + */ + HSA_AMD_SEGMENT_READONLY = 1, + /** + * Private segment. Used to hold data that is local to a single work-item. + */ + HSA_AMD_SEGMENT_PRIVATE = 2, + /** + * Group segment. Used to hold data that is shared by the work-items of a + * work-group. + */ + HSA_AMD_SEGMENT_GROUP = 3, +} hsa_amd_segment_t; + +/** + * @brief A memory pool encapsulates physical storage on an agent + * along with a memory access model. + * + * @details A memory pool encapsulates a physical partition of an agent's + * memory system along with a memory access model. Division of a single + * memory system into separate pools allows querying each partition's access + * path properties (see ::hsa_amd_agent_memory_pool_get_info). Allocations + * from a pool are preferentially bound to that pool's physical partition. + * Binding to the pool's preferential physical partition may not be + * possible or persistent depending on the system's memory policy + * and/or state which is beyond the scope of HSA APIs. + * + * For example, a multi-node NUMA memory system may be represented by multiple + * pool's with each pool providing size and access path information for the + * partition it represents. Allocations from a pool are preferentially bound + * to the pool's partition (which in this example is a NUMA node) while + * following its memory access model. The actual placement may vary or migrate + * due to the system's NUMA policy and state, which is beyond the scope of + * HSA APIs. + */ +typedef struct hsa_amd_memory_pool_s { + /** + * Opaque handle. + */ + uint64_t handle; +} hsa_amd_memory_pool_t; + +typedef enum hsa_amd_memory_pool_global_flag_s { + /** + * The application can use allocations in the memory pool to store kernel + * arguments, and provide the values for the kernarg segment of + * a kernel dispatch. + */ + HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_KERNARG_INIT = 1, + /** + * Updates to memory in this pool conform to HSA memory consistency model. + * If this flag is set, then ::HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_COARSE_GRAINED + * must not be set. + */ + HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_FINE_GRAINED = 2, + /** + * Writes to memory in this pool can be performed by a single agent at a time. + */ + HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_COARSE_GRAINED = 4, + + /** Updates to memory in this memory pool have extended scope, acting as + * system-scope atomics for variables in memory regions of this type. + * Note: On non-compliant systems, device-specific actions may be required + * for system-scope coherence. */ + HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_EXTENDED_SCOPE_FINE_GRAINED = 8, + +} hsa_amd_memory_pool_global_flag_t; + +typedef enum hsa_amd_memory_pool_location_s { + /** + * This memory pool resides on the host (CPU) + */ + HSA_AMD_MEMORY_POOL_LOCATION_CPU = 0, + /** + * This memory pool resides on a GPU + */ + HSA_AMD_MEMORY_POOL_LOCATION_GPU = 1 +} hsa_amd_memory_pool_location_t; + +/** + * @brief Memory pool features. + */ +typedef enum { + /** + * Segment where the memory pool resides. The type of this attribute is + * ::hsa_amd_segment_t. + */ + HSA_AMD_MEMORY_POOL_INFO_SEGMENT = 0, + /** + * Flag mask. The value of this attribute is undefined if the value of + * ::HSA_AMD_MEMORY_POOL_INFO_SEGMENT is not ::HSA_AMD_SEGMENT_GLOBAL. The type + * of + * this attribute is uint32_t, a bit-field of + * ::hsa_amd_memory_pool_global_flag_t + * values. + */ + HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS = 1, + /** + * Size of this pool, in bytes. The type of this attribute is size_t. + */ + HSA_AMD_MEMORY_POOL_INFO_SIZE = 2, + /** + * Indicates whether memory in this pool can be allocated using + * ::hsa_amd_memory_pool_allocate. The type of this attribute is bool. + * + * The value of this flag is always false for memory pools in the group and + * private segments. + */ + HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED = 5, + /** + * Allocation granularity of buffers allocated by + * ::hsa_amd_memory_pool_allocate + * in this memory pool. The size of a buffer allocated in this pool is a + * multiple of the value of this attribute. While this is the minimum size of + * allocation allowed, it is recommened to use + * HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_REC_GRANULE to obtain the recommended + * allocation granularity size for this pool. + * The value of this attribute is only defined if + * ::HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED is true for + * this pool. The type of this attribute is size_t. + */ + HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_GRANULE = 6, + /** + * Alignment of buffers allocated by ::hsa_amd_memory_pool_allocate in this + * pool. The value of this attribute is only defined if + * ::HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED is true for this pool, and + * must be a power of 2. The type of this attribute is size_t. + */ + HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALIGNMENT = 7, + /** + * This memory_pool can be made directly accessible by all the agents in the + * system (::hsa_amd_agent_memory_pool_get_info does not return + * ::HSA_AMD_MEMORY_POOL_ACCESS_NEVER_ALLOWED for any agent). The type of this + * attribute is bool. + */ + HSA_AMD_MEMORY_POOL_INFO_ACCESSIBLE_BY_ALL = 15, + /** + * Maximum aggregate allocation size in bytes. The type of this attribute + * is size_t. + */ + HSA_AMD_MEMORY_POOL_INFO_ALLOC_MAX_SIZE = 16, + /** + * Location of this memory pool. The type of this attribute + * is hsa_amd_memory_pool_location_t. + */ + HSA_AMD_MEMORY_POOL_INFO_LOCATION = 17, + /** + * Internal block size for allocations. This would also be the recommended + * granularity size for allocations as this prevents internal fragmentation. + * The value of this attribute is only defined if + * ::HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED is true for this pool. + * The size of this attribute is size_t. + */ + HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_REC_GRANULE = 18, +} hsa_amd_memory_pool_info_t; + +/** + * @brief Memory pool flag used to specify allocation directives + * + */ +typedef enum hsa_amd_memory_pool_flag_s { + /** + * Allocates memory that conforms to standard HSA memory consistency model + */ + HSA_AMD_MEMORY_POOL_STANDARD_FLAG = 0, + /** + * Allocates fine grain memory type where memory ordering is per point to point + * connection. Atomic memory operations on these memory buffers are not + * guaranteed to be visible at system scope. + */ + HSA_AMD_MEMORY_POOL_PCIE_FLAG = (1 << 0), + /** + * Allocates physically contiguous memory + */ + HSA_AMD_MEMORY_POOL_CONTIGUOUS_FLAG = (1 << 1), + +} hsa_amd_memory_pool_flag_t; + +/** + * @brief Get the current value of an attribute of a memory pool. + * + * @param[in] memory_pool A valid memory pool. + * + * @param[in] attribute Attribute to query. + * + * @param[out] value Pointer to a application-allocated buffer where to store + * the value of the attribute. If the buffer passed by the application is not + * large enough to hold the value of @p attribute, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + */ +hsa_status_t HSA_API + hsa_amd_memory_pool_get_info(hsa_amd_memory_pool_t memory_pool, + hsa_amd_memory_pool_info_t attribute, + void* value); + +/** + * @brief Iterate over the memory pools associated with a given agent, and + * invoke an application-defined callback on every iteration. + * + * @details An agent can directly access buffers located in some memory pool, or + * be enabled to access them by the application (see ::hsa_amd_agents_allow_access), + * yet that memory pool may not be returned by this function for that given + * agent. + * + * A memory pool of fine-grained type must be associated only with the host. + * + * @param[in] agent A valid agent. + * + * @param[in] callback Callback to be invoked on the same thread that called + * ::hsa_amd_agent_iterate_memory_pools, serially, once per memory pool that is + * associated with the agent. The HSA runtime passes two arguments to the + * callback: the memory pool, and the application data. If @p callback + * returns a status other than ::HSA_STATUS_SUCCESS for a particular iteration, + * the traversal stops and ::hsa_amd_agent_iterate_memory_pools returns that status + * value. + * + * @param[in] data Application data that is passed to @p callback on every + * iteration. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p callback is NULL. + */ +hsa_status_t HSA_API hsa_amd_agent_iterate_memory_pools( + hsa_agent_t agent, + hsa_status_t (*callback)(hsa_amd_memory_pool_t memory_pool, void* data), + void* data); + +/** + * @brief Allocate a block of memory (or buffer) in the specified pool. + * + * @param[in] memory_pool Memory pool where to allocate memory from. The memory + * pool must have the ::HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED flag set. + * + * @param[in] size Allocation size, in bytes. Must not be zero. This value is + * rounded up to the nearest multiple of + * ::HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_GRANULE in @p memory_pool. + * + * @param[in] flags A bit-field that is used to specify allocation + * directives. + * + * @param[out] ptr Pointer to the location where to store the base virtual + * address of + * the allocated block. The returned base address is aligned to the value of + * ::HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALIGNMENT in @p memory_pool. If the + * allocation fails, the returned value is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES No memory is available. + * + * @retval ::HSA_STATUS_ERROR_INVALID_MEMORY_POOL The memory pool is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ALLOCATION The host is not allowed to + * allocate memory in @p memory_pool, or @p size is greater than + * the value of HSA_AMD_MEMORY_POOL_INFO_ALLOC_MAX_SIZE in @p memory_pool. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p ptr is NULL, or @p size is 0, + * or flags is not 0. + * + */ +hsa_status_t HSA_API + hsa_amd_memory_pool_allocate(hsa_amd_memory_pool_t memory_pool, size_t size, + uint32_t flags, void** ptr); + +/** + * @brief Deallocate a block of memory previously allocated using + * ::hsa_amd_memory_pool_allocate. + * + * @param[in] ptr Pointer to a memory block. If @p ptr does not match a value + * previously returned by ::hsa_amd_memory_pool_allocate, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + */ +hsa_status_t HSA_API hsa_amd_memory_pool_free(void* ptr); + +/** + * @brief Asynchronously copy a block of memory from the location pointed to by + * @p src on the @p src_agent to the memory block pointed to by @p dst on the @p + * dst_agent. + * Because the DMA engines used may not be in the same coherency domain, the caller must ensure + * that buffers are system-level coherent. In general this requires the sending device to have + * released the buffer to system scope prior to executing the copy API and the receiving device + * must execute a system scope acquire fence prior to use of the destination buffer. + * + * @param[out] dst Buffer where the content is to be copied. + * + * @param[in] dst_agent Agent associated with the @p dst. The agent must be able to directly + * access both the source and destination buffers in their current locations. + * May be zero in which case the runtime will attempt to discover the destination agent. + * Discovery may have variable and/or high latency. + * + * @param[in] src A valid pointer to the source of data to be copied. The source + * buffer must not overlap with the destination buffer, otherwise the copy will succeed + * but contents of @p dst is undefined. + * + * @param[in] src_agent Agent associated with the @p src. The agent must be able to directly + * access both the source and destination buffers in their current locations. + * May be zero in which case the runtime will attempt to discover the destination agent. + * Discovery may have variable and/or high latency. + * + * @param[in] size Number of bytes to copy. If @p size is 0, no copy is + * performed and the function returns success. Copying a number of bytes larger + * than the size of the buffers pointed by @p dst or @p src results in undefined + * behavior. + * + * @param[in] num_dep_signals Number of dependent signals. Can be 0. + * + * @param[in] dep_signals List of signals that must be waited on before the copy + * operation starts. The copy will start after every signal has been observed with + * the value 0. The dependent signal should not include completion signal from + * hsa_amd_memory_async_copy operation to be issued in future as that can result + * in a deadlock. If @p num_dep_signals is 0, this argument is ignored. + * + * @param[in] completion_signal Signal used to indicate completion of the copy + * operation. When the copy operation is finished, the value of the signal is + * decremented. The runtime indicates that an error has occurred during the copy + * operation by setting the value of the completion signal to a negative + * number. The signal handle must not be 0. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. The + * application is responsible for checking for asynchronous error conditions + * (see the description of @p completion_signal). + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT An agent is invalid or no discovered agent has access. + * + * @retval ::HSA_STATUS_ERROR_INVALID_SIGNAL @p completion_signal is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT The source or destination + * pointers are NULL, or the completion signal is 0. + */ +hsa_status_t HSA_API + hsa_amd_memory_async_copy(void* dst, hsa_agent_t dst_agent, const void* src, + hsa_agent_t src_agent, size_t size, + uint32_t num_dep_signals, + const hsa_signal_t* dep_signals, + hsa_signal_t completion_signal); + +/** + * @brief Asynchronously copy a block of memory from the location pointed to by + * @p src on the @p src_agent to the memory block pointed to by @p dst on the @p + * dst_agent on engine_id. + * + * WARNING: Concurrent use of this call with hsa_amd_memory_async_copy can result + * in resource conflicts as HSA runtime will auto assign engines with the latter + * call. Approach using both calls concurrently with caution. + * + * All param definitions are identical to hsa_amd_memory_async_copy with the + * exception of engine_id and force_copy_on_sdma. + * + * @param[in] - engine_id Target engine defined by hsa_amd_sdma_engine_id_t. + * Client should use hsa_amd_memory_copy_engine_status first to get the ID + * availability. + * + * @param[in] - force_copy_on_sdma By default, blit kernel copies are used when + * dst_agent == src_agent. Setting this to true will force the copy over SDMA1. + * + * All return definitions are identical to hsa_amd_memory_async_copy with the + * following ammendments: + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT The source or destination + * pointers are NULL, or the completion signal is 0 or engine_id is improperly + * bounded. + */ +hsa_status_t HSA_API + hsa_amd_memory_async_copy_on_engine(void* dst, hsa_agent_t dst_agent, const void* src, + hsa_agent_t src_agent, size_t size, + uint32_t num_dep_signals, + const hsa_signal_t* dep_signals, + hsa_signal_t completion_signal, + hsa_amd_sdma_engine_id_t engine_id, + bool force_copy_on_sdma); +/** + * @brief Reports the availability of SDMA copy engines. + * + * @param[in] dst_agent Destination agent of copy status direction. + * + * @param[in] src_agent Source agent of copy status direction. + * + * @param[out] engine_ids_mask returns available SDMA engine IDs that can be masked + * with hsa_amd_sdma_engine_id_t. + * + * @retval ::HSA_STATUS_SUCCESS Agent has available SDMA engines. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES Agent does not have available SDMA engines. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT dst_agent and src_agent are the same as + * dst_agent == src_agent is generally used for shader copies. + */ +hsa_status_t HSA_API + hsa_amd_memory_copy_engine_status(hsa_agent_t dst_agent, hsa_agent_t src_agent, + uint32_t *engine_ids_mask); + +/* +[Provisional API] +Pitched memory descriptor. +All elements must be 4 byte aligned. Pitch and slice are in bytes. +*/ +typedef struct hsa_pitched_ptr_s { + void* base; + size_t pitch; + size_t slice; +} hsa_pitched_ptr_t; + +/* +[Provisional API] +Copy direction flag. +*/ +typedef enum { + hsaHostToHost = 0, + hsaHostToDevice = 1, + hsaDeviceToHost = 2, + hsaDeviceToDevice = 3 +} hsa_amd_copy_direction_t; + +/* +[Provisional API] +SDMA 3D memory copy API. The same requirements must be met by src and dst as in +hsa_amd_memory_async_copy. +Both src and dst must be directly accessible to the copy_agent during the copy, src and dst rects +must not overlap. +CPU agents are not supported. API requires SDMA and will return an error if SDMA is not available. +Offsets and range carry x in bytes, y and z in rows and layers. +*/ +hsa_status_t HSA_API hsa_amd_memory_async_copy_rect( + const hsa_pitched_ptr_t* dst, const hsa_dim3_t* dst_offset, const hsa_pitched_ptr_t* src, + const hsa_dim3_t* src_offset, const hsa_dim3_t* range, hsa_agent_t copy_agent, + hsa_amd_copy_direction_t dir, uint32_t num_dep_signals, const hsa_signal_t* dep_signals, + hsa_signal_t completion_signal); + +/** + * @brief Type of accesses to a memory pool from a given agent. + */ +typedef enum { + /** + * The agent cannot directly access any buffer in the memory pool. + */ + HSA_AMD_MEMORY_POOL_ACCESS_NEVER_ALLOWED = 0, + /** + * The agent can directly access a buffer located in the pool; the application + * does not need to invoke ::hsa_amd_agents_allow_access. + */ + HSA_AMD_MEMORY_POOL_ACCESS_ALLOWED_BY_DEFAULT = 1, + /** + * The agent can directly access a buffer located in the pool, but only if the + * application has previously requested access to that buffer using + * ::hsa_amd_agents_allow_access. + */ + HSA_AMD_MEMORY_POOL_ACCESS_DISALLOWED_BY_DEFAULT = 2 +} hsa_amd_memory_pool_access_t; + +/** + * @brief Properties of the relationship between an agent a memory pool. + */ +typedef enum { + /** + * Hyper-transport bus type. + */ + HSA_AMD_LINK_INFO_TYPE_HYPERTRANSPORT = 0, + + /** + * QPI bus type. + */ + HSA_AMD_LINK_INFO_TYPE_QPI = 1, + + /** + * PCIe bus type. + */ + HSA_AMD_LINK_INFO_TYPE_PCIE = 2, + + /** + * Infiniband bus type. + */ + HSA_AMD_LINK_INFO_TYPE_INFINBAND = 3, + + /** + * xGMI link type. + */ + HSA_AMD_LINK_INFO_TYPE_XGMI = 4 + +} hsa_amd_link_info_type_t; + +/** + * @brief Link properties when accessing the memory pool from the specified + * agent. + */ +typedef struct hsa_amd_memory_pool_link_info_s { + /** + * Minimum transfer latency (rounded to ns). + */ + uint32_t min_latency; + + /** + * Maximum transfer latency (rounded to ns). + */ + uint32_t max_latency; + + /** + * Minimum link interface bandwidth in MB/s. + */ + uint32_t min_bandwidth; + + /** + * Maximum link interface bandwidth in MB/s. + */ + uint32_t max_bandwidth; + + /** + * Support for 32-bit atomic transactions. + */ + bool atomic_support_32bit; + + /** + * Support for 64-bit atomic transactions. + */ + bool atomic_support_64bit; + + /** + * Support for cache coherent transactions. + */ + bool coherent_support; + + /** + * The type of bus/link. + */ + hsa_amd_link_info_type_t link_type; + + /** + * NUMA distance of memory pool relative to querying agent + */ + uint32_t numa_distance; +} hsa_amd_memory_pool_link_info_t; + +/** + * @brief Properties of the relationship between an agent a memory pool. + */ +typedef enum { + /** + * Access to buffers located in the memory pool. The type of this attribute + * is ::hsa_amd_memory_pool_access_t. + * + * An agent can always directly access buffers currently located in a memory + * pool that is associated (the memory_pool is one of the values returned by + * ::hsa_amd_agent_iterate_memory_pools on the agent) with that agent. If the + * buffer is currently located in a memory pool that is not associated with + * the agent, and the value returned by this function for the given + * combination of agent and memory pool is not + * HSA_AMD_MEMORY_POOL_ACCESS_NEVER_ALLOWED, the application still needs to invoke + * ::hsa_amd_agents_allow_access in order to gain direct access to the buffer. + * + * If the given agent can directly access buffers the pool, the result is not + * HSA_AMD_MEMORY_POOL_ACCESS_NEVER_ALLOWED. If the memory pool is associated with + * the agent, or it is of fined-grained type, the result must not be + * HSA_AMD_MEMORY_POOL_ACCESS_NEVER_ALLOWED. If the memory pool is not associated + * with the agent, and does not reside in the global segment, the result must + * be HSA_AMD_MEMORY_POOL_ACCESS_NEVER_ALLOWED. + */ + HSA_AMD_AGENT_MEMORY_POOL_INFO_ACCESS = 0, + + /** + * Number of links to hop when accessing the memory pool from the specified + * agent. The value of this attribute is zero if the memory pool is associated + * with the agent, or if the access type is + * HSA_AMD_MEMORY_POOL_ACCESS_NEVER_ALLOWED. The type of this attribute is + * uint32_t. + */ + HSA_AMD_AGENT_MEMORY_POOL_INFO_NUM_LINK_HOPS = 1, + + /** + * Details of each link hop when accessing the memory pool starting from the + * specified agent. The type of this attribute is an array size of + * HSA_AMD_AGENT_MEMORY_POOL_INFO_NUM_LINK_HOPS with each element containing + * ::hsa_amd_memory_pool_link_info_t. + */ + HSA_AMD_AGENT_MEMORY_POOL_INFO_LINK_INFO = 2 + +} hsa_amd_agent_memory_pool_info_t; + +/** + * @brief Get the current value of an attribute of the relationship between an + * agent and a memory pool. + * + * @param[in] agent Agent. + * + * @param[in] memory_pool Memory pool. + * + * @param[in] attribute Attribute to query. + * + * @param[out] value Pointer to a application-allocated buffer where to store + * the value of the attribute. If the buffer passed by the application is not + * large enough to hold the value of @p attribute, the behavior is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + */ +hsa_status_t HSA_API hsa_amd_agent_memory_pool_get_info( + hsa_agent_t agent, hsa_amd_memory_pool_t memory_pool, + hsa_amd_agent_memory_pool_info_t attribute, void* value); + +/** + * @brief Enable direct access to a buffer from a given set of agents. + * + * @details + * + * Upon return, only the listed agents and the agent associated with the + * buffer's memory pool have direct access to the @p ptr. + * + * Any agent that has access to the buffer before and after the call to + * ::hsa_amd_agents_allow_access will also have access while + * ::hsa_amd_agents_allow_access is in progress. + * + * The caller is responsible for ensuring that each agent in the list + * must be able to access the memory pool containing @p ptr + * (using ::hsa_amd_agent_memory_pool_get_info with ::HSA_AMD_AGENT_MEMORY_POOL_INFO_ACCESS attribute), + * otherwise error code is returned. + * + * @param[in] num_agents Size of @p agents. + * + * @param[in] agents List of agents. If @p num_agents is 0, this argument is + * ignored. + * + * @param[in] flags A list of bit-field that is used to specify access + * information in a per-agent basis. This is currently reserved and must be NULL. + * + * @param[in] ptr A buffer previously allocated using ::hsa_amd_memory_pool_allocate. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p num_agents is 0, or @p agents + * is NULL, @p flags is not NULL, or attempting to enable access to agent(s) + * because @p ptr is allocated from an inaccessible pool. + * + */ +hsa_status_t HSA_API + hsa_amd_agents_allow_access(uint32_t num_agents, const hsa_agent_t* agents, + const uint32_t* flags, const void* ptr); + +/** + * @brief Query if buffers currently located in some memory pool can be + * relocated to a destination memory pool. + * + * @details If the returned value is non-zero, a migration of a buffer to @p + * dst_memory_pool using ::hsa_amd_memory_migrate may nevertheless fail due to + * resource limitations. + * + * @param[in] src_memory_pool Source memory pool. + * + * @param[in] dst_memory_pool Destination memory pool. + * + * @param[out] result Pointer to a memory location where the result of the query + * is stored. Must not be NULL. If buffers currently located in @p + * src_memory_pool can be relocated to @p dst_memory_pool, the result is + * true. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_MEMORY_POOL One of the memory pools is + * invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p result is NULL. + */ +hsa_status_t HSA_API + hsa_amd_memory_pool_can_migrate(hsa_amd_memory_pool_t src_memory_pool, + hsa_amd_memory_pool_t dst_memory_pool, + bool* result); + +/** + * @brief Relocate a buffer to a new memory pool. + * + * @details When a buffer is migrated, its virtual address remains the same but + * its physical contents are moved to the indicated memory pool. + * + * After migration, only the agent associated with the destination pool will have access. + * + * The caller is also responsible for ensuring that the allocation in the + * source memory pool where the buffer is currently located can be migrated to the + * specified destination memory pool (using ::hsa_amd_memory_pool_can_migrate returns a value of true + * for the source and destination memory pools), otherwise behavior is undefined. + * + * The caller must ensure that the buffer is not accessed while it is migrated. + * + * @param[in] ptr Buffer to be relocated. The buffer must have been released to system + * prior to call this API. The buffer will be released to system upon completion. + * + * @param[in] memory_pool Memory pool where to place the buffer. + * + * @param[in] flags A bit-field that is used to specify migration + * information. Must be zero. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_MEMORY_POOL The destination memory pool is + * invalid. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES There is a failure in + * allocating the necessary resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p flags is not 0. + */ +hsa_status_t HSA_API hsa_amd_memory_migrate(const void* ptr, + hsa_amd_memory_pool_t memory_pool, + uint32_t flags); + +/** + * + * @brief Pin a host pointer allocated by C/C++ or OS allocator (i.e. ordinary system DRAM) and + * return a new pointer accessible by the @p agents. If the @p host_ptr overlaps with previously + * locked memory, then the overlap area is kept locked (i.e multiple mappings are permitted). In + * this case, the same input @p host_ptr may give different locked @p agent_ptr and when it does, + * they are not necessarily coherent (i.e. accessing either @p agent_ptr is not equivalent). + * Accesses to @p agent_ptr are coarse grained. + * + * @param[in] host_ptr A buffer allocated by C/C++ or OS allocator. + * + * @param[in] size The size to be locked. + * + * @param[in] agents Array of agent handle to gain access to the @p host_ptr. + * If this parameter is NULL and the @p num_agent is 0, all agents + * in the platform will gain access to the @p host_ptr. + * + * @param[out] agent_ptr Pointer to the location where to store the new address. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES There is a failure in + * allocating the necessary resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT One or more agent in @p agents is + * invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p size is 0 or @p host_ptr or + * @p agent_ptr is NULL or @p agents not NULL but @p num_agent is 0 or @p agents + * is NULL but @p num_agent is not 0. + */ +hsa_status_t HSA_API hsa_amd_memory_lock(void* host_ptr, size_t size, + hsa_agent_t* agents, int num_agent, + void** agent_ptr); + +/** + * + * @brief Pin a host pointer allocated by C/C++ or OS allocator (i.e. ordinary system DRAM) and + * return a new pointer accessible by the @p agents. If the @p host_ptr overlaps with previously + * locked memory, then the overlap area is kept locked (i.e. multiple mappings are permitted). + * In this case, the same input @p host_ptr may give different locked @p agent_ptr and when it + * does, they are not necessarily coherent (i.e. accessing either @p agent_ptr is not equivalent). + * Acesses to the memory via @p agent_ptr have the same access properties as memory allocated from + * @p pool as determined by ::hsa_amd_memory_pool_get_info and ::hsa_amd_agent_memory_pool_get_info + * (ex. coarse/fine grain, platform atomic support, link info). Physical composition and placement + * of the memory (ex. page size, NUMA binding) is not changed. + * + * @param[in] host_ptr A buffer allocated by C/C++ or OS allocator. + * + * @param[in] size The size to be locked. + * + * @param[in] agents Array of agent handle to gain access to the @p host_ptr. + * If this parameter is NULL and the @p num_agent is 0, all agents + * in the platform will gain access to the @p host_ptr. + * + * @param[in] pool Global memory pool owned by a CPU agent. + * + * @param[in] flags A bit-field that is used to specify allocation + * directives. Reserved parameter, must be 0. + * + * @param[out] agent_ptr Pointer to the location where to store the new address. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES There is a failure in + * allocating the necessary resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT One or more agent in @p agents is + * invalid or can not access @p pool. + * + * @retval ::HSA_STATUS_ERROR_INVALID_MEMORY_POOL @p pool is invalid or not owned + * by a CPU agent. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p size is 0 or @p host_ptr or + * @p agent_ptr is NULL or @p agents not NULL but @p num_agent is 0 or @p agents + * is NULL but @p num_agent is not 0 or flags is not 0. + */ +hsa_status_t HSA_API hsa_amd_memory_lock_to_pool(void* host_ptr, size_t size, hsa_agent_t* agents, + int num_agent, hsa_amd_memory_pool_t pool, + uint32_t flags, void** agent_ptr); + +/** + * + * @brief Unpin the host pointer previously pinned via ::hsa_amd_memory_lock or + * ::hsa_amd_memory_lock_to_pool. + * + * @details The behavior is undefined if the host pointer being unpinned does not + * match previous pinned address or if the host pointer was already deallocated. + * + * @param[in] host_ptr A buffer allocated by C/C++ or OS allocator that was + * pinned previously via ::hsa_amd_memory_lock or ::hsa_amd_memory_lock_to_pool. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + */ +hsa_status_t HSA_API hsa_amd_memory_unlock(void* host_ptr); + +/** + * @brief Sets the first @p count of uint32_t of the block of memory pointed by + * @p ptr to the specified @p value. + * + * @param[in] ptr Pointer to the block of memory to fill. + * + * @param[in] value Value to be set. + * + * @param[in] count Number of uint32_t element to be set to the value. + * + * @retval HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval HSA_STATUS_ERROR_INVALID_ARGUMENT @p ptr is NULL or + * not 4 bytes aligned + * + * @retval HSA_STATUS_ERROR_INVALID_ALLOCATION if the given memory + * region was not allocated with HSA runtime APIs. + * + */ +hsa_status_t HSA_API + hsa_amd_memory_fill(void* ptr, uint32_t value, size_t count); + +/** + * @brief Maps an interop object into the HSA flat address space and establishes + * memory residency. The metadata pointer is valid during the lifetime of the + * map (until hsa_amd_interop_unmap_buffer is called). + * Multiple calls to hsa_amd_interop_map_buffer with the same interop_handle + * result in multiple mappings with potentially different addresses and + * different metadata pointers. Concurrent operations on these addresses are + * not coherent. Memory must be fenced to system scope to ensure consistency, + * between mappings and with any views of this buffer in the originating + * software stack. + * + * @param[in] num_agents Number of agents which require access to the memory + * + * @param[in] agents List of accessing agents. + * + * @param[in] interop_handle Handle of interop buffer (dmabuf handle in Linux) + * + * @param [in] flags Reserved, must be 0 + * + * @param[out] size Size in bytes of the mapped object + * + * @param[out] ptr Base address of the mapped object + * + * @param[out] metadata_size Size of metadata in bytes, may be NULL + * + * @param[out] metadata Pointer to metadata, may be NULL + * + * @retval HSA_STATUS_SUCCESS if successfully mapped + * + * @retval HSA_STATUS_ERROR_NOT_INITIALIZED if HSA is not initialized + * + * @retval HSA_STATUS_ERROR_OUT_OF_RESOURCES if there is a failure in allocating + * necessary resources + * + * @retval HSA_STATUS_ERROR_INVALID_ARGUMENT all other errors + */ +hsa_status_t HSA_API hsa_amd_interop_map_buffer(uint32_t num_agents, + hsa_agent_t* agents, + int interop_handle, + uint32_t flags, + size_t* size, + void** ptr, + size_t* metadata_size, + const void** metadata); + +/** + * @brief Removes a previously mapped interop object from HSA's flat address space. + * Ends lifetime for the mapping's associated metadata pointer. + */ +hsa_status_t HSA_API hsa_amd_interop_unmap_buffer(void* ptr); + +/** + * @brief Encodes an opaque vendor specific image format. The length of data + * depends on the underlying format. This structure must not be copied as its + * true length can not be determined. + */ +typedef struct hsa_amd_image_descriptor_s { + /* + Version number of the descriptor + */ + uint32_t version; + + /* + Vendor and device PCI IDs for the format as VENDOR_ID<<16|DEVICE_ID. + */ + uint32_t deviceID; + + /* + Start of vendor specific data. + */ + uint32_t data[1]; +} hsa_amd_image_descriptor_t; + +/** + * @brief Creates an image from an opaque vendor specific image format. + * Does not modify data at image_data. Intended initially for + * accessing interop images. + * + * @param agent[in] Agent on which to create the image + * + * @param[in] image_descriptor[in] Vendor specific image format + * + * @param[in] image_data Pointer to image backing store + * + * @param[in] access_permission Access permissions for the image object + * + * @param[out] image Created image object. + * + * @retval HSA_STATUS_SUCCESS Image created successfully + * + * @retval HSA_STATUS_ERROR_NOT_INITIALIZED if HSA is not initialized + * + * @retval HSA_STATUS_ERROR_OUT_OF_RESOURCES if there is a failure in allocating + * necessary resources + * + * @retval HSA_STATUS_ERROR_INVALID_ARGUMENT Bad or mismatched descriptor, + * null image_data, or mismatched access_permission. + */ +hsa_status_t HSA_API hsa_amd_image_create( + hsa_agent_t agent, + const hsa_ext_image_descriptor_t *image_descriptor, + const hsa_amd_image_descriptor_t *image_layout, + const void *image_data, + hsa_access_permission_t access_permission, + hsa_ext_image_t *image +); + +/** + * @brief Denotes the type of memory in a pointer info query. + */ +typedef enum { + /* + Memory is not known to the HSA driver. Unallocated or unlocked system memory. + */ + HSA_EXT_POINTER_TYPE_UNKNOWN = 0, + /* + Memory was allocated with an HSA memory allocator. + */ + HSA_EXT_POINTER_TYPE_HSA = 1, + /* + System memory which has been locked for use with an HSA agent. + + Memory of this type is normal malloc'd memory and is always accessible to + the CPU. Pointer info queries may not include CPU agents in the accessible + agents list as the CPU has implicit access. + */ + HSA_EXT_POINTER_TYPE_LOCKED = 2, + /* + Memory originated in a graphics component and is shared with ROCr. + */ + HSA_EXT_POINTER_TYPE_GRAPHICS = 3, + /* + Memory has been shared with the local process via ROCr IPC APIs. + */ + HSA_EXT_POINTER_TYPE_IPC = 4 +} hsa_amd_pointer_type_t; + +/** + * @brief Describes a memory allocation known to ROCr. + * Within a ROCr major version this structure can only grow. + */ +typedef struct hsa_amd_pointer_info_s { + /* + Size in bytes of this structure. Used for version control within a major ROCr + revision. Set to sizeof(hsa_amd_pointer_t) prior to calling + hsa_amd_pointer_info. If the runtime supports an older version of pointer + info then size will be smaller on return. Members starting after the return + value of size will not be updated by hsa_amd_pointer_info. + */ + uint32_t size; + /* + The type of allocation referenced. + */ + hsa_amd_pointer_type_t type; + /* + Base address at which non-host agents may access the allocation. This field is + not meaningful if the type of the allocation is HSA_EXT_POINTER_TYPE_UNKNOWN. + */ + void* agentBaseAddress; + /* + Base address at which the host agent may access the allocation. This field is + not meaningful if the type of the allocation is HSA_EXT_POINTER_TYPE_UNKNOWN. + */ + void* hostBaseAddress; + /* + Size of the allocation. This field is not meaningful if the type of the allocation + is HSA_EXT_POINTER_TYPE_UNKNOWN. + */ + size_t sizeInBytes; + /* + Application provided value. This field is not meaningful if the type of the + allocation is HSA_EXT_POINTER_TYPE_UNKNOWN. + */ + void* userData; + /* + Reports an agent which "owns" (ie has preferred access to) the pool in which the + allocation was + made. When multiple agents share equal access to a pool (ex: multiple CPU agents, or multi-die + GPU boards) any such agent may be returned. This field is not meaningful if + the type of the allocation is HSA_EXT_POINTER_TYPE_UNKNOWN or if this agent is not available in + this process, for e.g if this agent is masked using ROCR_VISIBLE_DEVICES. + */ + hsa_agent_t agentOwner; + /* + Contains a bitfield of hsa_amd_memory_pool_global_flag_t values. + Reports the effective global flags bitmask for the allocation. This field is not + meaningful if the type of the allocation is HSA_EXT_POINTER_TYPE_UNKNOWN. + */ + uint32_t global_flags; +} hsa_amd_pointer_info_t; + +/** + * @brief Retrieves information about the allocation referenced by the given + * pointer. Optionally returns the number and list of agents which can + * directly access the allocation. In case this virtual address is unknown, the + * pointer type returned will be HSA_EXT_POINTER_TYPE_UNKNOWN and the only fields + * that are valid after hsa_amd_pointer_info returns are size and type. + * + * @param[in] ptr Pointer which references the allocation to retrieve info for. + * + * @param[in, out] info Pointer to structure to be filled with allocation info. + * Data member size must be set to the size of the structure prior to calling + * hsa_amd_pointer_info. On return size will be set to the size of the + * pointer info structure supported by the runtime, if smaller. Members + * beyond the returned value of size will not be updated by the API. + * Must not be NULL. + * + * @param[in] alloc Function pointer to an allocator used to allocate the + * @p accessible array. If NULL @p accessible will not be returned. + * + * @param[out] num_agents_accessible Recieves the count of agents in + * @p accessible. If NULL @p accessible will not be returned. + * + * @param[out] accessible Recieves a pointer to the array, allocated by @p alloc, + * holding the list of agents which may directly access the allocation. + * May be NULL. + * + * @retval HSA_STATUS_SUCCESS Info retrieved successfully + * + * @retval HSA_STATUS_ERROR_NOT_INITIALIZED if HSA is not initialized + * + * @retval HSA_STATUS_ERROR_OUT_OF_RESOURCES if there is a failure in allocating + * necessary resources + * + * @retval HSA_STATUS_ERROR_INVALID_ARGUMENT NULL in @p ptr or @p info. + */ +hsa_status_t HSA_API hsa_amd_pointer_info(const void* ptr, + hsa_amd_pointer_info_t* info, + void* (*alloc)(size_t), + uint32_t* num_agents_accessible, + hsa_agent_t** accessible); + +/** + * @brief Associates an arbitrary pointer with an allocation known to ROCr. + * The pointer can be fetched by hsa_amd_pointer_info in the userData field. + * + * @param[in] ptr Pointer to the first byte of an allocation known to ROCr + * with which to associate @p userdata. + * + * @param[in] userdata Abitrary pointer to associate with the allocation. + * + * @retval HSA_STATUS_SUCCESS @p userdata successfully stored. + * + * @retval HSA_STATUS_ERROR_NOT_INITIALIZED if HSA is not initialized + * + * @retval HSA_STATUS_ERROR_OUT_OF_RESOURCES if there is a failure in allocating + * necessary resources + * + * @retval HSA_STATUS_ERROR_INVALID_ARGUMENT @p ptr is not known to ROCr. + */ +hsa_status_t HSA_API hsa_amd_pointer_info_set_userdata(const void* ptr, + void* userdata); + +/** + * @brief 256-bit process independent identifier for a ROCr shared memory + * allocation. + */ +typedef struct hsa_amd_ipc_memory_s { + uint32_t handle[8]; +} hsa_amd_ipc_memory_t; + +/** + * @brief Prepares an allocation for interprocess sharing and creates a + * handle of type hsa_amd_ipc_memory_t uniquely identifying the allocation. A + * handle is valid while the allocation it references remains accessible in + * any process. In general applications should confirm that a shared memory + * region has been attached (via hsa_amd_ipc_memory_attach) in the remote + * process prior to releasing that memory in the local process. + * Repeated calls for the same allocation may, but are not required to, return + * unique handles. The allocation needs to be on memory on an agent of type + * HSA_DEVICE_TYPE_GPU. + * + * @param[in] ptr Pointer to device memory allocated via ROCr APIs to prepare for + * sharing. + * + * @param[in] len Length in bytes of the allocation to share. + * + * @param[out] handle Process independent identifier referencing the shared + * allocation. + * + * @retval HSA_STATUS_SUCCESS allocation is prepared for interprocess sharing. + * + * @retval HSA_STATUS_ERROR_NOT_INITIALIZED if HSA is not initialized + * + * @retval HSA_STATUS_ERROR_OUT_OF_RESOURCES if there is a failure in allocating + * necessary resources + * + * @retval HSA_STATUS_ERROR_INVALID_ARGUMENT @p ptr does not point to the + * first byte of an allocation made through ROCr, or len is not the full length + * of the allocation or handle is NULL. + */ +hsa_status_t HSA_API hsa_amd_ipc_memory_create(void* ptr, size_t len, + hsa_amd_ipc_memory_t* handle); + +/** + * @brief Imports shared memory into the local process and makes it accessible + * by the given agents. If a shared memory handle is attached multiple times + * in a process each attach may return a different address. Each returned + * address is refcounted and requires a matching number of calls to + * hsa_amd_ipc_memory_detach to release the shared memory mapping. + * + * @param[in] handle Pointer to the identifier for the shared memory. + * + * @param[in] len Length of the shared memory to import. + * Reserved. Must be the full length of the shared allocation in this version. + * + * @param[in] num_agents Count of agents in @p mapping_agents. + * May be zero if all agents are to be allowed access. + * + * @param[in] mapping_agents List of agents to access the shared memory. + * Ignored if @p num_agents is zero. + * + * @param[out] mapped_ptr Recieves a process local pointer to the shared memory. + * + * @retval HSA_STATUS_SUCCESS if memory is successfully imported. + * + * @retval HSA_STATUS_ERROR_NOT_INITIALIZED if HSA is not initialized + * + * @retval HSA_STATUS_ERROR_OUT_OF_RESOURCES if there is a failure in allocating + * necessary resources + * + * @retval HSA_STATUS_ERROR_INVALID_ARGUMENT @p handle is not valid, @p len is + * incorrect, @p mapped_ptr is NULL, or some agent for which access was + * requested can not access the shared memory. + */ +hsa_status_t HSA_API hsa_amd_ipc_memory_attach( + const hsa_amd_ipc_memory_t* handle, size_t len, + uint32_t num_agents, + const hsa_agent_t* mapping_agents, + void** mapped_ptr); + +/** + * @brief Decrements the reference count for the shared memory mapping and + * releases access to shared memory imported with hsa_amd_ipc_memory_attach. + * + * @param[in] mapped_ptr Pointer to the first byte of a shared allocation + * imported with hsa_amd_ipc_memory_attach. + * + * @retval HSA_STATUS_SUCCESS if @p mapped_ptr was imported with + * hsa_amd_ipc_memory_attach. + * + * @retval HSA_STATUS_ERROR_NOT_INITIALIZED if HSA is not initialized + * + * @retval HSA_STATUS_ERROR_INVALID_ARGUMENT @p mapped_ptr was not imported + * with hsa_amd_ipc_memory_attach. + */ +hsa_status_t HSA_API hsa_amd_ipc_memory_detach(void* mapped_ptr); + +/** + * @brief 256-bit process independent identifier for a ROCr IPC signal. + */ +typedef hsa_amd_ipc_memory_t hsa_amd_ipc_signal_t; + +/** + * @brief Obtains an interprocess sharing handle for a signal. The handle is + * valid while the signal it references remains valid in any process. In + * general applications should confirm that the signal has been attached (via + * hsa_amd_ipc_signal_attach) in the remote process prior to destroying that + * signal in the local process. + * Repeated calls for the same signal may, but are not required to, return + * unique handles. + * + * @param[in] signal Signal created with attribute HSA_AMD_SIGNAL_IPC. + * + * @param[out] handle Process independent identifier referencing the shared + * signal. + * + * @retval HSA_STATUS_SUCCESS @p handle is ready to use for interprocess sharing. + * + * @retval HSA_STATUS_ERROR_NOT_INITIALIZED if HSA is not initialized + * + * @retval HSA_STATUS_ERROR_OUT_OF_RESOURCES if there is a failure in allocating + * necessary resources + * + * @retval HSA_STATUS_ERROR_INVALID_ARGUMENT @p signal is not a valid signal + * created with attribute HSA_AMD_SIGNAL_IPC or handle is NULL. + */ +hsa_status_t HSA_API hsa_amd_ipc_signal_create(hsa_signal_t signal, hsa_amd_ipc_signal_t* handle); + +/** + * @brief Imports an IPC capable signal into the local process. If an IPC + * signal handle is attached multiple times in a process each attach may return + * a different signal handle. Each returned signal handle is refcounted and + * requires a matching number of calls to hsa_signal_destroy to release the + * shared signal. + * + * @param[in] handle Pointer to the identifier for the shared signal. + * + * @param[out] signal Recieves a process local signal handle to the shared signal. + * + * @retval HSA_STATUS_SUCCESS if the signal is successfully imported. + * + * @retval HSA_STATUS_ERROR_NOT_INITIALIZED if HSA is not initialized + * + * @retval HSA_STATUS_ERROR_OUT_OF_RESOURCES if there is a failure in allocating + * necessary resources + * + * @retval HSA_STATUS_ERROR_INVALID_ARGUMENT @p handle is not valid. + */ +hsa_status_t HSA_API hsa_amd_ipc_signal_attach(const hsa_amd_ipc_signal_t* handle, + hsa_signal_t* signal); + +/** + * @brief GPU system event type. + */ +typedef enum hsa_amd_event_type_s { + /* + AMD GPU memory fault. + */ + HSA_AMD_GPU_MEMORY_FAULT_EVENT = 0, + /* + AMD GPU HW Exception. + */ + HSA_AMD_GPU_HW_EXCEPTION_EVENT, +} hsa_amd_event_type_t; + +/** + * @brief Flags denoting the cause of a memory fault. + */ +typedef enum { + // Page not present or supervisor privilege. + HSA_AMD_MEMORY_FAULT_PAGE_NOT_PRESENT = 1 << 0, + // Write access to a read-only page. + HSA_AMD_MEMORY_FAULT_READ_ONLY = 1 << 1, + // Execute access to a page marked NX. + HSA_AMD_MEMORY_FAULT_NX = 1 << 2, + // GPU attempted access to a host only page. + HSA_AMD_MEMORY_FAULT_HOST_ONLY = 1 << 3, + // DRAM ECC failure. + HSA_AMD_MEMORY_FAULT_DRAMECC = 1 << 4, + // Can't determine the exact fault address. + HSA_AMD_MEMORY_FAULT_IMPRECISE = 1 << 5, + // SRAM ECC failure (ie registers, no fault address). + HSA_AMD_MEMORY_FAULT_SRAMECC = 1 << 6, + // GPU reset following unspecified hang. + HSA_AMD_MEMORY_FAULT_HANG = 1U << 31 +} hsa_amd_memory_fault_reason_t; + +/** + * @brief AMD GPU memory fault event data. + */ +typedef struct hsa_amd_gpu_memory_fault_info_s { + /* + The agent where the memory fault occurred. + */ + hsa_agent_t agent; + /* + Virtual address accessed. + */ + uint64_t virtual_address; + /* + Bit field encoding the memory access failure reasons. There could be multiple bits set + for one fault. Bits are defined in hsa_amd_memory_fault_reason_t. + */ + uint32_t fault_reason_mask; +} hsa_amd_gpu_memory_fault_info_t; + +/** + * @brief Flags denoting the type of a HW exception + */ +typedef enum { + // Unused for now + HSA_AMD_HW_EXCEPTION_RESET_TYPE_OTHER = 1 << 0, +} hsa_amd_hw_exception_reset_type_t; + +/** + * @brief Flags denoting the cause of a HW exception + */ +typedef enum { + // GPU Hang + HSA_AMD_HW_EXCEPTION_CAUSE_GPU_HANG = 1 << 0, + // SRAM ECC + HSA_AMD_HW_EXCEPTION_CAUSE_ECC = 1 << 1, +} hsa_amd_hw_exception_reset_cause_t; + +/** + * @brief AMD GPU HW Exception event data. + */ +typedef struct hsa_amd_gpu_hw_exception_info_s { + /* + The agent where the HW exception occurred. + */ + hsa_agent_t agent; + hsa_amd_hw_exception_reset_type_t reset_type; + hsa_amd_hw_exception_reset_cause_t reset_cause; +} hsa_amd_gpu_hw_exception_info_t; + +/** + * @brief AMD GPU event data passed to event handler. + */ +typedef struct hsa_amd_event_s { + /* + The event type. + */ + hsa_amd_event_type_t event_type; + union { + /* + The memory fault info, only valid when @p event_type is HSA_AMD_GPU_MEMORY_FAULT_EVENT. + */ + hsa_amd_gpu_memory_fault_info_t memory_fault; + /* + The memory fault info, only valid when @p event_type is HSA_AMD_GPU_HW_EXCEPTION_EVENT. + */ + hsa_amd_gpu_hw_exception_info_t hw_exception; + }; +} hsa_amd_event_t; + +typedef hsa_status_t (*hsa_amd_system_event_callback_t)(const hsa_amd_event_t* event, void* data); + +/** + * @brief Register AMD GPU event handler. + * + * @param[in] callback Callback to be invoked when an event is triggered. + * The HSA runtime passes two arguments to the callback: @p event + * is defined per event by the HSA runtime, and @p data is the user data. + * + * @param[in] data User data that is passed to @p callback. May be NULL. + * + * @retval HSA_STATUS_SUCCESS The handler has been registered successfully. + * + * @retval HSA_STATUS_ERROR An event handler has already been registered. + * + * @retval HSA_STATUS_ERROR_INVALID_ARGUMENT @p event is invalid. + */ +hsa_status_t HSA_API hsa_amd_register_system_event_handler(hsa_amd_system_event_callback_t callback, + void* data); + +/** + * @brief Per-queue dispatch and wavefront scheduling priority. + */ +typedef enum hsa_amd_queue_priority_s { + /* + Below normal/high priority compute and all graphics + */ + HSA_AMD_QUEUE_PRIORITY_LOW = 0, + /* + Above low priority compute, below high priority compute and all graphics + */ + HSA_AMD_QUEUE_PRIORITY_NORMAL = 1, + /* + Above low/normal priority compute and all graphics + */ + HSA_AMD_QUEUE_PRIORITY_HIGH = 2, +} hsa_amd_queue_priority_t; + +/** + * @brief Modifies the dispatch and wavefront scheduling prioirty for a + * given compute queue. The default is HSA_AMD_QUEUE_PRIORITY_NORMAL. + * + * @param[in] queue Compute queue to apply new priority to. + * + * @param[in] priority Priority to associate with queue. + * + * @retval HSA_STATUS_SUCCESS if priority was changed successfully. + * + * @retval HSA_STATUS_ERROR_INVALID_QUEUE if queue is not a valid + * compute queue handle. + * + * @retval HSA_STATUS_ERROR_INVALID_ARGUMENT if priority is not a valid + * value from hsa_amd_queue_priority_t. + */ +hsa_status_t HSA_API hsa_amd_queue_set_priority(hsa_queue_t* queue, + hsa_amd_queue_priority_t priority); + +/** + * @brief Deallocation notifier function type. + */ +typedef void (*hsa_amd_deallocation_callback_t)(void* ptr, void* user_data); + +/** + * @brief Registers a deallocation notifier monitoring for release of agent + * accessible address @p ptr. If successful, @p callback will be invoked when + * @p ptr is removed from accessibility from all agents. + * + * Notification callbacks are automatically deregistered when they are invoked. + * + * Note: The current version supports notifications of address release + * originating from ::hsa_amd_memory_pool_free. Support for other address + * release APIs will follow. + * + * @param[in] ptr Agent accessible address to monitor for deallocation. Passed + * to @p callback. + * + * @param[in] callback Notifier to be invoked when @p ptr is released from + * agent accessibility. + * + * @param[in] user_data User provided value passed to @p callback. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The notifier registered successfully + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ALLOCATION @p ptr does not refer to a valid agent accessible + * address. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p callback is NULL or @p ptr is NULL. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES if there is a failure in allocating + * necessary resources + */ +hsa_status_t HSA_API hsa_amd_register_deallocation_callback(void* ptr, + hsa_amd_deallocation_callback_t callback, + void* user_data); + +/** + * @brief Removes a deallocation notifier previously registered with + * ::hsa_amd_register_deallocation_callback. Arguments must be identical to + * those given in ::hsa_amd_register_deallocation_callback. + * + * @param[in] ptr Agent accessible address which was monitored for deallocation. + * + * @param[in] callback Notifier to be removed. + * + * @retval ::HSA_STATUS_SUCCESS The notifier has been removed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT The given notifier was not registered. + */ +hsa_status_t HSA_API hsa_amd_deregister_deallocation_callback(void* ptr, + hsa_amd_deallocation_callback_t callback); + +typedef enum hsa_amd_svm_model_s { + /** + * Updates to memory with this attribute conform to HSA memory consistency + * model. + */ + HSA_AMD_SVM_GLOBAL_FLAG_FINE_GRAINED = 0, + /** + * Writes to memory with this attribute can be performed by a single agent + * at a time. + */ + HSA_AMD_SVM_GLOBAL_FLAG_COARSE_GRAINED = 1, + /** + * Memory region queried contains subregions with both + * HSA_AMD_SVM_GLOBAL_FLAG_COARSE_GRAINED and + * HSA_AMD_SVM_GLOBAL_FLAG_FINE_GRAINED attributes. + * + * This attribute can not be used in hsa_amd_svm_attributes_set. It is a + * possible return from hsa_amd_svm_attributes_get indicating that the query + * region contains both coarse and fine grained memory. + */ + HSA_AMD_SVM_GLOBAL_FLAG_INDETERMINATE = 2 +} hsa_amd_svm_model_t; + +typedef enum hsa_amd_svm_attribute_s { + // Memory model attribute. + // Type of this attribute is hsa_amd_svm_model_t. + HSA_AMD_SVM_ATTRIB_GLOBAL_FLAG = 0, + // Marks the range read only. This allows multiple physical copies to be + // placed local to each accessing device. + // Type of this attribute is bool. + HSA_AMD_SVM_ATTRIB_READ_ONLY = 1, + // Automatic migrations should attempt to keep the memory within the xgmi hive + // containing accessible agents. + // Type of this attribute is bool. + HSA_AMD_SVM_ATTRIB_HIVE_LOCAL = 2, + // Page granularity to migrate at once. Page granularity is specified as + // log2(page_count). + // Type of this attribute is uint64_t. + HSA_AMD_SVM_ATTRIB_MIGRATION_GRANULARITY = 3, + // Physical location to prefer when automatic migration occurs. + // Set to the null agent handle (handle == 0) to indicate there + // is no preferred location. + // Type of this attribute is hsa_agent_t. + HSA_AMD_SVM_ATTRIB_PREFERRED_LOCATION = 4, + // This attribute can not be used in ::hsa_amd_svm_attributes_set (see + // ::hsa_amd_svm_prefetch_async). + // Queries the physical location of most recent prefetch command. + // If the prefetch location has not been set or is not uniform across the + // address range then returned hsa_agent_t::handle will be 0. + // Querying this attribute will return the destination agent of the most + // recent ::hsa_amd_svm_prefetch_async targeting the address range. If + // multiple async prefetches have been issued targeting the region and the + // most recently issued prefetch has completed then the query will return + // the location of the most recently completed prefetch. + // Type of this attribute is hsa_agent_t. + HSA_AMD_SVM_ATTRIB_PREFETCH_LOCATION = 5, + // Optimizes with the anticipation that the majority of operations to the + // range will be read operations. + // Type of this attribute is bool. + HSA_AMD_SVM_ATTRIB_READ_MOSTLY = 6, + // Allows the execution on GPU. + // Type of this attribute is bool. + HSA_AMD_SVM_ATTRIB_GPU_EXEC = 7, + // This attribute can not be used in ::hsa_amd_svm_attributes_get. + // Enables an agent for access to the range. Access may incur a page fault + // and associated memory migration. Either this or + // HSA_AMD_SVM_ATTRIB_AGENT_ACCESSIBLE_IN_PLACE is required prior to SVM + // access if HSA_AMD_SYSTEM_INFO_SVM_ACCESSIBLE_BY_DEFAULT is false. + // Type of this attribute is hsa_agent_t. + HSA_AMD_SVM_ATTRIB_AGENT_ACCESSIBLE = 0x200, + // This attribute can not be used in ::hsa_amd_svm_attributes_get. + // Enables an agent for access to the range without page faults. Access + // will not incur a page fault and will not cause access based migration. + // and associated memory migration. Either this or + // HSA_AMD_SVM_ATTRIB_AGENT_ACCESSIBLE is required prior to SVM access if + // HSA_AMD_SYSTEM_INFO_SVM_ACCESSIBLE_BY_DEFAULT is false. + // Type of this attribute is hsa_agent_t. + HSA_AMD_SVM_ATTRIB_AGENT_ACCESSIBLE_IN_PLACE = 0x201, + // This attribute can not be used in ::hsa_amd_svm_attributes_get. + // Denies an agent access to the memory range. Access will cause a terminal + // segfault. + // Type of this attribute is hsa_agent_t. + HSA_AMD_SVM_ATTRIB_AGENT_NO_ACCESS = 0x202, + // This attribute can not be used in ::hsa_amd_svm_attributes_set. + // Returns the access attribute associated with the agent. + // The agent to query must be set in the attribute value field. + // The attribute enum will be replaced with the agent's current access + // attribute for the address range. + // TODO: Clarify KFD return value for non-uniform access attribute. + // Type of this attribute is hsa_agent_t. + HSA_AMD_SVM_ATTRIB_ACCESS_QUERY = 0x203, +} hsa_amd_svm_attribute_t; + +// List type for hsa_amd_svm_attributes_set/get. +typedef struct hsa_amd_svm_attribute_pair_s { + // hsa_amd_svm_attribute_t value. + uint64_t attribute; + // Attribute value. Bit values should be interpreted according to the type + // given in the associated attribute description. + uint64_t value; +} hsa_amd_svm_attribute_pair_t; + +/** + * @brief Sets SVM memory attributes. + * + * If HSA_AMD_SYSTEM_INFO_SVM_ACCESSIBLE_BY_DEFAULT returns false then enabling + * access to an Agent via this API (setting HSA_AMD_SVM_ATTRIB_AGENT_ACCESSIBLE + * or HSA_AMD_SVM_ATTRIB_AGENT_ACCESSIBLE_IN_PLACE) is required prior to SVM + * memory access by that Agent. + * + * Attributes HSA_AMD_SVM_ATTRIB_ACCESS_QUERY and HSA_AMD_SVM_ATTRIB_PREFETCH_LOCATION + * may not be used with this API. + * + * @param[in] ptr Will be aligned down to nearest page boundary. + * + * @param[in] size Will be aligned up to nearest page boundary. + * + * @param[in] attribute_list List of attributes to set for the address range. + * + * @param[in] attribute_count Length of @p attribute_list. + */ +hsa_status_t hsa_amd_svm_attributes_set(void* ptr, size_t size, + hsa_amd_svm_attribute_pair_t* attribute_list, + size_t attribute_count); + +/** + * @brief Gets SVM memory attributes. + * + * Attributes HSA_AMD_SVM_ATTRIB_AGENT_ACCESSIBLE, + * HSA_AMD_SVM_ATTRIB_AGENT_ACCESSIBLE_IN_PLACE and + * HSA_AMD_SVM_ATTRIB_PREFETCH_LOCATION may not be used with this API. + * + * Note that attribute HSA_AMD_SVM_ATTRIB_ACCESS_QUERY takes as input an + * hsa_agent_t and returns the current access type through its attribute field. + * + * @param[in] ptr Will be aligned down to nearest page boundary. + * + * @param[in] size Will be aligned up to nearest page boundary. + * + * @param[in] attribute_list List of attributes to set for the address range. + * + * @param[in] attribute_count Length of @p attribute_list. + */ +hsa_status_t hsa_amd_svm_attributes_get(void* ptr, size_t size, + hsa_amd_svm_attribute_pair_t* attribute_list, + size_t attribute_count); + +/** + * @brief Asynchronously migrates memory to an agent. + * + * Schedules memory migration to @p agent when @p dep_signals have been observed equal to zero. + * @p completion_signal will decrement when the migration is complete. + * + * @param[in] ptr Will be aligned down to nearest page boundary. + * + * @param[in] size Will be aligned up to nearest page boundary. + * + * @param[in] agent Agent to migrate to. + * + * @param[in] num_dep_signals Number of dependent signals. Can be 0. + * + * @param[in] dep_signals List of signals that must be waited on before the migration + * operation starts. The migration will start after every signal has been observed with + * the value 0. If @p num_dep_signals is 0, this argument is ignored. + * + * @param[in] completion_signal Signal used to indicate completion of the migration + * operation. When the migration operation is finished, the value of the signal is + * decremented. The runtime indicates that an error has occurred during the copy + * operation by setting the value of the completion signal to a negative + * number. If no completion signal is required this handle may be null. + */ +hsa_status_t hsa_amd_svm_prefetch_async(void* ptr, size_t size, hsa_agent_t agent, + uint32_t num_dep_signals, const hsa_signal_t* dep_signals, + hsa_signal_t completion_signal); + +/** + * @brief Acquire Stream Performance Monitor on an agent + * + * Acquire exclusive use of SPM on @p preferred_agent. + * See hsa_amd_spm_set_dest_buffer to provide a destination buffer to KFD to start recording and + * retrieve this data. + * @param[in] preferred_agent Agent on which to acquire SPM + */ +hsa_status_t hsa_amd_spm_acquire(hsa_agent_t preferred_agent); + +/** + * @brief Release Stream Performance Monitor on an agent + * + * Release exclusive use of SPM on @p preferred_agent. This will stop KFD writing SPM data. + * If a destination buffer is set, then data in the destination buffer is available to user + * when this function returns. + * + * @param[in] preferred_agent Agent on which to release SPM + */ +hsa_status_t hsa_amd_spm_release(hsa_agent_t preferred_agent); + +/** + * @brief Set up the current destination user mode buffer for stream performance + * counter data. KFD will start writing SPM data into the destination buffer. KFD will continue + * to copy data into the current destination buffer until any of the following functions are called + * - hsa_amd_spm_release + * - hsa_amd_spm_set_dest_buffer with dest set to NULL + * - hsa_amd_spm_set_dest_buffer with dest set to a new buffer + * + * if @p timeout is non-0, the call will wait for up to @p timeout ms for the previous + * buffer to be filled. If previous buffer to be filled before timeout, the @p timeout + * will be updated value with the time remaining. If the timeout is exceeded, the function + * copies any partial data available into the previous user buffer and returns success. + * User should not access destination data while KFD is copying data. + * If the previous destination buffer was full, then @p is_data_loss flag is set. + * @p dest is CPU accessible memory. It could be malloc'ed memory or host allocated memory + * + * @param[in] preferred_agent Agent on which to set the dest buffer + * + * @param[in] size_in_bytes size of the buffer + * + * @param[in/out] timeout timeout in milliseconds + * + * @param[out] size_copied number of bytes copied + * + * @param[in] dest destination address. Set to NULL to stop copy on previous buffer + * + * @param[out] is_data_loss true is data was lost + */ +hsa_status_t hsa_amd_spm_set_dest_buffer(hsa_agent_t preferred_agent, size_t size_in_bytes, + uint32_t* timeout, uint32_t* size_copied, void* dest, + bool* is_data_loss); +/** + * @brief Obtains an OS specific, vendor neutral, handle to a memory allocation. + * + * Obtains an OS specific handle to GPU agent memory. The memory must be part + * of a single allocation from an hsa_amd_memory_pool_t exposed by a GPU Agent. + * The handle may be used with other APIs (e.g. Vulkan) to obtain shared access + * to the allocation. + * + * Shared access to the memory is not guaranteed to be fine grain coherent even + * if the allocation exported is from a fine grain pool. The shared memory + * consistency model will be no stronger than the model exported from, consult + * the importing API to determine the final consistency model. + * + * The allocation's memory remains valid as long as the handle and any mapping + * of the handle remains valid. When the handle and all mappings are closed + * the backing memory will be released for reuse. + * + * @param[in] ptr Pointer to the allocation being exported. + * + * @param[in] size Size in bytes to export following @p ptr. The entire range + * being exported must be contained within a single allocation. + * + * @param[out] dmabuf Pointer to a dma-buf file descriptor holding a reference to the + * allocation. Contents will not be altered in the event of failure. + * + * @param[out] offset Offset in bytes into the memory referenced by the dma-buf + * object at which @p ptr resides. Contents will not be altered in the event + * of failure. + * + * @retval ::HSA_STATUS_SUCCESS Export completed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT One or more arguments is NULL. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ALLOCATION The address range described by + * @p ptr and @p size are not contained within a single allocation. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The allocation described by @p ptr + * and @p size was allocated on a device which can not export memory. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The return file descriptor, + * @p dmabuf, could not be created. + */ +hsa_status_t hsa_amd_portable_export_dmabuf(const void* ptr, size_t size, int* dmabuf, + uint64_t* offset); + +/** + * @brief Closes an OS specific, vendor neutral, handle to a memory allocation. + * + * Closes an OS specific handle to GPU agent memory. + * + * Applications should close a handle after imports are complete. The handle + * is not required to remain open for the lifetime of imported mappings. The + * referenced allocation will remain valid until all handles and mappings + * are closed. + * + * @param[in] dmabuf Handle to be closed. + * + * @retval ::HSA_STATUS_SUCCESS Handle closed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_RESOURCE_FREE A generic error was encountered + * when closing the handle. The handle may have been closed already or an + * async IO error may have occured. + */ +hsa_status_t hsa_amd_portable_close_dmabuf(int dmabuf); + +/** + * @brief Allocate a reserved address range + * + * Reserve a virtual address range. The size must be a multiple of the system page size. + * If it is not possible to allocate the address specified by @p address, then @p va will be + * a different address range. + * Address range should be released by calling hsa_amd_vmem_address_free. + * + * @param[out] va virtual address allocated + * @param[in] size of address range requested + * @param[in] address requested + * @param[in] flags currently unsupported + * + * @retval ::HSA_STATUS_SUCCESS Address range allocated successfully + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES Insufficient resources to allocate an address + * range of this size. + * + * Note that this API will be deprecated in a future release and replaced by + * hsa_amd_vmem_address_reserve_align + */ +hsa_status_t hsa_amd_vmem_address_reserve(void** va, size_t size, uint64_t address, + uint64_t flags); + +/** + * @brief Allocate a reserved address range + * + * Reserve a virtual address range. The size must be a multiple of the system page size. + * If it is not possible to allocate the address specified by @p address, then @p va will be + * a different address range. + * Address range should be released by calling hsa_amd_vmem_address_free. + * + * @param[out] va virtual address allocated + * @param[in] size of address range requested + * @param[in] address requested + * @param[in] alignment requested. 0 for default. Must be >= page-size and a power of 2 + * @param[in] flags currently unsupported + * + * @retval ::HSA_STATUS_SUCCESS Address range allocated successfully + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES Insufficient resources to allocate an address + * range of this size. + */ +hsa_status_t hsa_amd_vmem_address_reserve_align(void** va, size_t size, uint64_t address, + uint64_t alignment, uint64_t flags); + +/** + * @brief Free a reserved address range + * + * Free a previously allocated address range. The size must match the size of a previously + * allocated address range. + * + * @param[out] va virtual address to be freed + * @param[in] size of address range + * + * @retval ::HSA_STATUS_SUCCESS Address range released successfully + * + * @retval ::HSA_STATUS_ERROR_INVALID_ALLOCATION Invalid va specified + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT Invalid size specified + * @retval ::HSA_STATUS_ERROR_RESOURCE_FREE Address range is still in use + * @retval ::HSA_STATUS_ERROR Internal unexpected error + */ +hsa_status_t hsa_amd_vmem_address_free(void* va, size_t size); + +/** + * @brief Struct containing an opaque handle to a memory allocation handle + */ +typedef struct hsa_amd_vmem_alloc_handle_s { + /** + * Opaque handle. Two handles reference the same object of the enclosing type + * if and only if they are equal. + */ + uint64_t handle; +} hsa_amd_vmem_alloc_handle_t; + +typedef enum { + MEMORY_TYPE_NONE, + MEMORY_TYPE_PINNED, +} hsa_amd_memory_type_t; + +/** + * @brief Create a virtual memory handle + * + * Create a virtual memory handle within this pool + * @p size must be a aligned to allocation granule size for this memory pool, see + * HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_GRANULE + * To minimize internal memory fragmentation, align the size to the recommended allocation granule + * size, see HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_REC_GRANULE + * + * @param[in] pool memory to use + * @param[in] size of the memory allocation + * @param[in] type of memory + * @param[in] flags - currently unsupported + * @param[out] memory_handle - handle for the allocation + * + * @retval ::HSA_STATUS_SUCCESS memory allocated successfully + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT Invalid arguments + * + * @retval ::HSA_STATUS_ERROR_INVALID_ALLOCATION This memory pool does not support allocations + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES Insufficient resources to allocate this memory + */ +hsa_status_t hsa_amd_vmem_handle_create(hsa_amd_memory_pool_t pool, size_t size, + hsa_amd_memory_type_t type, uint64_t flags, + hsa_amd_vmem_alloc_handle_t* memory_handle); + +/** + * @brief Release a virtual memory handle + * + * @param[in] memory handle that was previously allocated + * + * @retval ::HSA_STATUS_SUCCESS Address range allocated successfully + * + * @retval ::HSA_STATUS_ERROR_INVALID_ALLOCATION Invalid memory handle + */ +hsa_status_t hsa_amd_vmem_handle_release(hsa_amd_vmem_alloc_handle_t memory_handle); + +/** + * @brief Map a virtual memory handle + * + * Map a virtual memory handle to a reserved address range. The virtual address requested must be + * within a previously reserved address range. @p va and (@p va + size) must be must be within + * (va + size) of the previous allocated address range. + * @p size must be equal to size of the @p memory_handle + * hsa_amd_vmem_set_access needs to be called to make the memory accessible to specific agents + * + * @param[in] va virtual address range where memory will be mapped + * @param[in] size of memory mapping + * @param[in] in_offset offset into memory. Currently unsupported + * @param[in] memory_handle virtual memory handle to be mapped + * @param[in] flags. Currently unsupported + * + * @retval ::HSA_STATUS_SUCCESS Memory mapped successfully + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT va, size or memory_handle are invalid + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES Insufficient resources + * + * @retval ::HSA_STATUS_ERROR Unexpected internal error + */ +hsa_status_t hsa_amd_vmem_map(void* va, size_t size, size_t in_offset, + hsa_amd_vmem_alloc_handle_t memory_handle, uint64_t flags); + +/** + * @brief Unmap a virtual memory handle + * + * Unmap previously mapped virtual address range + * + * @param[in] va virtual address range where memory will be mapped + * @param[in] size of memory mapping + * + * @retval ::HSA_STATUS_SUCCESS Memory backing unmapped successfully + * + * @retval ::HSA_STATUS_ERROR_INVALID_ALLOCATION memory_handle is invalid + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT size is invalid + * + * @retval ::HSA_STATUS_ERROR Unexpected internal error + */ +hsa_status_t hsa_amd_vmem_unmap(void* va, size_t size); + +typedef struct hsa_amd_memory_access_desc_s { + hsa_access_permission_t permissions; + hsa_agent_t agent_handle; +} hsa_amd_memory_access_desc_t; + +/** + * @brief Make a memory mapping accessible + * + * Make previously mapped virtual address accessible to specific agents. @p size must be equal to + * size of previously mapped virtual memory handle. + * Calling hsa_amd_vmem_set_access multiple times on the same @p va will overwrite previous + * permissions for all agents + * + * @param[in] va previously mapped virtual address + * @param[in] size of memory mapping + * @param[in] desc list of access permissions for each agent + * @param[in] desc_cnt number of elements in desc + * + * @retval ::HSA_STATUS_SUCCESS + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT va, size or memory_handle are invalid + * + * @retval ::HSA_STATUS_ERROR_INVALID_ALLOCATION memory_handle is invalid + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES Insufficient resources + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT Invalid agent in desc + * + * @retval ::HSA_STATUS_ERROR Unexpected internal error + */ +hsa_status_t hsa_amd_vmem_set_access(void* va, size_t size, + const hsa_amd_memory_access_desc_t* desc, + size_t desc_cnt); + +/** + * @brief Get current access permissions for memory mapping + * + * Get access permissions for memory mapping for specific agent. + * + * @param[in] va previously mapped virtual address + * @param[in] perms current permissions + * @param[in] agent_handle agent + * + * @retval ::HSA_STATUS_SUCCESS + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT Invalid agent + * + * @retval ::HSA_STATUS_ERROR_INVALID_ALLOCATION va is not mapped or permissions never set for this + * agent + * + * @retval ::HSA_STATUS_ERROR Unexpected internal error + */ +hsa_status_t hsa_amd_vmem_get_access(void* va, hsa_access_permission_t* perms, + hsa_agent_t agent_handle); + +/** + * @brief Get an exportable shareable handle + * + * Get an exportable shareable handle for a memory_handle. This shareabl handle can then be used to + * re-create a virtual memory handle using hsa_amd_vmem_import_shareable_handle. The shareable + * handle can be transferred using mechanisms that support posix file descriptors Once all shareable + * handles are closed, the memory_handle is released. + * + * @param[out] dmabuf_fd shareable handle + * @param[in] handle previously allocated virtual memory handle + * @param[in] flags Currently unsupported + * + * @retval ::HSA_STATUS_SUCCESS + * + * @retval ::HSA_STATUS_ERROR_INVALID_ALLOCATION Invalid memory handle + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES Out of resources + * + * @retval ::HSA_STATUS_ERROR Unexpected internal error + */ +hsa_status_t hsa_amd_vmem_export_shareable_handle(int* dmabuf_fd, + hsa_amd_vmem_alloc_handle_t handle, + uint64_t flags); +/** + * @brief Import a shareable handle + * + * Import a shareable handle for a memory handle. Importing a shareable handle that has been closed + * and released results in undefined behavior. + * + * @param[in] dmabuf_fd shareable handle exported with hsa_amd_vmem_export_shareable_handle + * @param[out] handle virtual memory handle + * + * @retval ::HSA_STATUS_SUCCESS + * + * @retval ::HSA_STATUS_ERROR_INVALID_ALLOCATION Invalid memory handle + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES Out of resources + * + * @retval ::HSA_STATUS_ERROR Unexpected internal error + */ +hsa_status_t hsa_amd_vmem_import_shareable_handle(int dmabuf_fd, + hsa_amd_vmem_alloc_handle_t* handle); + +/** + * @brief Returns memory handle for mapped memory + * + * Return a memory handle for previously mapped memory. The handle will be the same value of handle + * used to map the memory. The returned handle must be released with corresponding number of calls + * to hsa_amd_vmem_handle_release. + * + * @param[out] memory_handle memory handle for this mapped address + * @param[in] mapped address + * + * @retval ::HSA_STATUS_SUCCESS + * + * @retval ::HSA_STATUS_ERROR_INVALID_ALLOCATION Invalid address + */ +hsa_status_t hsa_amd_vmem_retain_alloc_handle(hsa_amd_vmem_alloc_handle_t* memory_handle, + void* addr); + +/** + * @brief Returns the current allocation properties of a handle + * + * Returns the allocation properties of an existing handle + * + * @param[in] memory_handle memory handle to be queried + * @param[out] pool memory pool that owns this handle + * @param[out] memory type + + * @retval ::HSA_STATUS_SUCCESS + * + * @retval ::HSA_STATUS_ERROR_INVALID_ALLOCATION Invalid memory_handle + */ +hsa_status_t hsa_amd_vmem_get_alloc_properties_from_handle( + hsa_amd_vmem_alloc_handle_t memory_handle, hsa_amd_memory_pool_t* pool, + hsa_amd_memory_type_t* type); + +/** + * @brief Set the asynchronous scratch limit threshold on all the queues for this agent. + * Dispatches that are enqueued on HW queues on this agent that are smaller than threshold will not + * result in a scratch use-once method. + * + * Increasing this threshold will only increase the internal limit and not cause immediate allocation + * of additional scratch memory. Decreasing this threshold will result in a release in scratch memory + * on queues where the current amount of allocated scratch exceeds the new limit. + * + * This API is only supported on devices that support asynchronous scratch reclaim. + * + * @param[in] agent A valid agent. + * + * @param[in] threshold Threshold size in bytes + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT This agent does not support asynchronous scratch + * reclaim + */ +hsa_status_t HSA_API hsa_amd_agent_set_async_scratch_limit(hsa_agent_t agent, size_t threshold); + +typedef enum { + /* + * Returns the agent that owns the underlying HW queue. + * The type of this attribute is hsa_agent_t. + */ + HSA_AMD_QUEUE_INFO_AGENT, + /* + * Returns the doorbell ID of the completion signal of the queue + * The type of this attribute is uint64_t. + */ + HSA_AMD_QUEUE_INFO_DOORBELL_ID, +} hsa_queue_info_attribute_t; + +hsa_status_t hsa_amd_queue_get_info(hsa_queue_t* queue, hsa_queue_info_attribute_t attribute, + void* value); + +#ifdef __cplusplus +} // end extern "C" block +#endif + +#endif // header guard diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_ext_finalize.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_ext_finalize.h new file mode 100644 index 0000000000000000000000000000000000000000..94c45820551f5e0823c5107e0e590e296bc62bf8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_ext_finalize.h @@ -0,0 +1,531 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// The University of Illinois/NCSA +// Open Source License (NCSA) +// +// Copyright (c) 2014-2020, Advanced Micro Devices, Inc. All rights reserved. +// +// Developed by: +// +// AMD Research and AMD HSA Software Development +// +// Advanced Micro Devices, Inc. +// +// www.amd.com +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal with 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: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimers in +// the documentation and/or other materials provided with the distribution. +// - Neither the names of Advanced Micro Devices, Inc, +// nor the names of its contributors may be used to endorse or promote +// products derived from this Software without specific prior written +// permission. +// +// 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 CONTRIBUTORS 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 WITH THE SOFTWARE. +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef HSA_RUNTIME_INC_HSA_EXT_FINALIZE_H_ +#define HSA_RUNTIME_INC_HSA_EXT_FINALIZE_H_ + +#include "hsa.h" + +#undef HSA_API +#ifdef HSA_EXPORT_FINALIZER +#define HSA_API HSA_API_EXPORT +#else +#define HSA_API HSA_API_IMPORT +#endif + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +struct BrigModuleHeader; +typedef struct BrigModuleHeader* BrigModule_t; + +/** \defgroup ext-alt-finalizer-extensions Finalization Extensions + * @{ + */ + +/** + * @brief Enumeration constants added to ::hsa_status_t by this extension. + */ +enum { + /** + * The HSAIL program is invalid. + */ + HSA_EXT_STATUS_ERROR_INVALID_PROGRAM = 0x2000, + /** + * The HSAIL module is invalid. + */ + HSA_EXT_STATUS_ERROR_INVALID_MODULE = 0x2001, + /** + * Machine model or profile of the HSAIL module do not match the machine model + * or profile of the HSAIL program. + */ + HSA_EXT_STATUS_ERROR_INCOMPATIBLE_MODULE = 0x2002, + /** + * The HSAIL module is already a part of the HSAIL program. + */ + HSA_EXT_STATUS_ERROR_MODULE_ALREADY_INCLUDED = 0x2003, + /** + * Compatibility mismatch between symbol declaration and symbol definition. + */ + HSA_EXT_STATUS_ERROR_SYMBOL_MISMATCH = 0x2004, + /** + * The finalization encountered an error while finalizing a kernel or + * indirect function. + */ + HSA_EXT_STATUS_ERROR_FINALIZATION_FAILED = 0x2005, + /** + * Mismatch between a directive in the control directive structure and in + * the HSAIL kernel. + */ + HSA_EXT_STATUS_ERROR_DIRECTIVE_MISMATCH = 0x2006 +}; + +/** @} */ + +/** \defgroup ext-alt-finalizer-program Finalization Program + * @{ + */ + +/** + * @brief HSAIL (BRIG) module. The HSA Programmer's Reference Manual contains + * the definition of the BrigModule_t type. + */ +typedef BrigModule_t hsa_ext_module_t; + +/** + * @brief An opaque handle to a HSAIL program, which groups a set of HSAIL + * modules that collectively define functions and variables used by kernels and + * indirect functions. + */ +typedef struct hsa_ext_program_s { + /** + * Opaque handle. + */ + uint64_t handle; +} hsa_ext_program_t; + +/** + * @brief Create an empty HSAIL program. + * + * @param[in] machine_model Machine model used in the HSAIL program. + * + * @param[in] profile Profile used in the HSAIL program. + * + * @param[in] default_float_rounding_mode Default float rounding mode used in + * the HSAIL program. + * + * @param[in] options Vendor-specific options. May be NULL. + * + * @param[out] program Memory location where the HSA runtime stores the newly + * created HSAIL program handle. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES There is a failure to allocate + * resources required for the operation. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p machine_model is invalid, + * @p profile is invalid, @p default_float_rounding_mode is invalid, or + * @p program is NULL. + */ +hsa_status_t HSA_API hsa_ext_program_create( + hsa_machine_model_t machine_model, + hsa_profile_t profile, + hsa_default_float_rounding_mode_t default_float_rounding_mode, + const char *options, + hsa_ext_program_t *program); + +/** + * @brief Destroy a HSAIL program. + * + * @details The HSAIL program handle becomes invalid after it has been + * destroyed. Code object handles produced by ::hsa_ext_program_finalize are + * still valid after the HSAIL program has been destroyed, and can be used as + * intended. Resources allocated outside and associated with the HSAIL program + * (such as HSAIL modules that are added to the HSAIL program) can be released + * after the finalization program has been destroyed. + * + * @param[in] program HSAIL program. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_EXT_STATUS_ERROR_INVALID_PROGRAM The HSAIL program is + * invalid. + */ +hsa_status_t HSA_API hsa_ext_program_destroy( + hsa_ext_program_t program); + +/** + * @brief Add a HSAIL module to an existing HSAIL program. + * + * @details The HSA runtime does not perform a deep copy of the HSAIL module + * upon addition. Instead, it stores a pointer to the HSAIL module. The + * ownership of the HSAIL module belongs to the application, which must ensure + * that @p module is not released before destroying the HSAIL program. + * + * The HSAIL module is successfully added to the HSAIL program if @p module is + * valid, if all the declarations and definitions for the same symbol are + * compatible, and if @p module specify machine model and profile that matches + * the HSAIL program. + * + * @param[in] program HSAIL program. + * + * @param[in] module HSAIL module. The application can add the same HSAIL module + * to @p program at most once. The HSAIL module must specify the same machine + * model and profile as @p program. If the floating-mode rounding mode of @p + * module is not default, then it should match that of @p program. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES There is a failure to allocate + * resources required for the operation. + * + * @retval ::HSA_EXT_STATUS_ERROR_INVALID_PROGRAM The HSAIL program is invalid. + * + * @retval ::HSA_EXT_STATUS_ERROR_INVALID_MODULE The HSAIL module is invalid. + * + * @retval ::HSA_EXT_STATUS_ERROR_INCOMPATIBLE_MODULE The machine model of @p + * module does not match machine model of @p program, or the profile of @p + * module does not match profile of @p program. + * + * @retval ::HSA_EXT_STATUS_ERROR_MODULE_ALREADY_INCLUDED The HSAIL module is + * already a part of the HSAIL program. + * + * @retval ::HSA_EXT_STATUS_ERROR_SYMBOL_MISMATCH Symbol declaration and symbol + * definition compatibility mismatch. See the symbol compatibility rules in the + * HSA Programming Reference Manual. + */ +hsa_status_t HSA_API hsa_ext_program_add_module( + hsa_ext_program_t program, + hsa_ext_module_t module); + +/** + * @brief Iterate over the HSAIL modules in a program, and invoke an + * application-defined callback on every iteration. + * + * @param[in] program HSAIL program. + * + * @param[in] callback Callback to be invoked once per HSAIL module in the + * program. The HSA runtime passes three arguments to the callback: the program, + * a HSAIL module, and the application data. If @p callback returns a status + * other than ::HSA_STATUS_SUCCESS for a particular iteration, the traversal + * stops and ::hsa_ext_program_iterate_modules returns that status value. + * + * @param[in] data Application data that is passed to @p callback on every + * iteration. May be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_EXT_STATUS_ERROR_INVALID_PROGRAM The program is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p callback is NULL. + */ +hsa_status_t HSA_API hsa_ext_program_iterate_modules( + hsa_ext_program_t program, + hsa_status_t (*callback)(hsa_ext_program_t program, hsa_ext_module_t module, + void* data), + void* data); + +/** + * @brief HSAIL program attributes. + */ +typedef enum { + /** + * Machine model specified when the HSAIL program was created. The type + * of this attribute is ::hsa_machine_model_t. + */ + HSA_EXT_PROGRAM_INFO_MACHINE_MODEL = 0, + /** + * Profile specified when the HSAIL program was created. The type of + * this attribute is ::hsa_profile_t. + */ + HSA_EXT_PROGRAM_INFO_PROFILE = 1, + /** + * Default float rounding mode specified when the HSAIL program was + * created. The type of this attribute is ::hsa_default_float_rounding_mode_t. + */ + HSA_EXT_PROGRAM_INFO_DEFAULT_FLOAT_ROUNDING_MODE = 2 +} hsa_ext_program_info_t; + +/** + * @brief Get the current value of an attribute for a given HSAIL program. + * + * @param[in] program HSAIL program. + * + * @param[in] attribute Attribute to query. + * + * @param[out] value Pointer to an application-allocated buffer where to store + * the value of the attribute. If the buffer passed by the application is not + * large enough to hold the value of @p attribute, the behaviour is undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_EXT_STATUS_ERROR_INVALID_PROGRAM The HSAIL program is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p attribute is an invalid + * HSAIL program attribute, or @p value is NULL. + */ +hsa_status_t HSA_API hsa_ext_program_get_info( + hsa_ext_program_t program, + hsa_ext_program_info_t attribute, + void *value); + +/** + * @brief Finalizer-determined call convention. + */ +typedef enum { + /** + * Finalizer-determined call convention. + */ + HSA_EXT_FINALIZER_CALL_CONVENTION_AUTO = -1 +} hsa_ext_finalizer_call_convention_t; + +/** + * @brief Control directives specify low-level information about the + * finalization process. + */ +typedef struct hsa_ext_control_directives_s { + /** + * Bitset indicating which control directives are enabled. The bit assigned to + * a control directive is determined by the corresponding value in + * BrigControlDirective. + * + * If a control directive is disabled, its corresponding field value (if any) + * must be 0. Control directives that are only present or absent (such as + * partial workgroups) have no corresponding field as the presence of the bit + * in this mask is sufficient. + */ + uint64_t control_directives_mask; + /** + * Bitset of HSAIL exceptions that must have the BREAK policy enabled. The bit + * assigned to an HSAIL exception is determined by the corresponding value + * in BrigExceptionsMask. If the kernel contains a enablebreakexceptions + * control directive, the finalizer uses the union of the two masks. + */ + uint16_t break_exceptions_mask; + /** + * Bitset of HSAIL exceptions that must have the DETECT policy enabled. The + * bit assigned to an HSAIL exception is determined by the corresponding value + * in BrigExceptionsMask. If the kernel contains a enabledetectexceptions + * control directive, the finalizer uses the union of the two masks. + */ + uint16_t detect_exceptions_mask; + /** + * Maximum size (in bytes) of dynamic group memory that will be allocated by + * the application for any dispatch of the kernel. If the kernel contains a + * maxdynamicsize control directive, the two values should match. + */ + uint32_t max_dynamic_group_size; + /** + * Maximum number of grid work-items that will be used by the application to + * launch the kernel. If the kernel contains a maxflatgridsize control + * directive, the value of @a max_flat_grid_size must not be greater than the + * value of the directive, and takes precedence. + * + * The value specified for maximum absolute grid size must be greater than or + * equal to the product of the values specified by @a required_grid_size. + * + * If the bit at position BRIG_CONTROL_MAXFLATGRIDSIZE is set in @a + * control_directives_mask, this field must be greater than 0. + */ + uint64_t max_flat_grid_size; + /** + * Maximum number of work-group work-items that will be used by the + * application to launch the kernel. If the kernel contains a + * maxflatworkgroupsize control directive, the value of @a + * max_flat_workgroup_size must not be greater than the value of the + * directive, and takes precedence. + * + * The value specified for maximum absolute grid size must be greater than or + * equal to the product of the values specified by @a required_workgroup_size. + * + * If the bit at position BRIG_CONTROL_MAXFLATWORKGROUPSIZE is set in @a + * control_directives_mask, this field must be greater than 0. + */ + uint32_t max_flat_workgroup_size; + /** + * Reserved. Must be 0. + */ + uint32_t reserved1; + /** + * Grid size that will be used by the application in any dispatch of the + * kernel. If the kernel contains a requiredgridsize control directive, the + * dimensions should match. + * + * The specified grid size must be consistent with @a required_workgroup_size + * and @a required_dim. Also, the product of the three dimensions must not + * exceed @a max_flat_grid_size. Note that the listed invariants must hold + * only if all the corresponding control directives are enabled. + * + * If the bit at position BRIG_CONTROL_REQUIREDGRIDSIZE is set in @a + * control_directives_mask, the three dimension values must be greater than 0. + */ + uint64_t required_grid_size[3]; + /** + * Work-group size that will be used by the application in any dispatch of the + * kernel. If the kernel contains a requiredworkgroupsize control directive, + * the dimensions should match. + * + * The specified work-group size must be consistent with @a required_grid_size + * and @a required_dim. Also, the product of the three dimensions must not + * exceed @a max_flat_workgroup_size. Note that the listed invariants must + * hold only if all the corresponding control directives are enabled. + * + * If the bit at position BRIG_CONTROL_REQUIREDWORKGROUPSIZE is set in @a + * control_directives_mask, the three dimension values must be greater than 0. + */ + hsa_dim3_t required_workgroup_size; + /** + * Number of dimensions that will be used by the application to launch the + * kernel. If the kernel contains a requireddim control directive, the two + * values should match. + * + * The specified dimensions must be consistent with @a required_grid_size and + * @a required_workgroup_size. This invariant must hold only if all the + * corresponding control directives are enabled. + * + * If the bit at position BRIG_CONTROL_REQUIREDDIM is set in @a + * control_directives_mask, this field must be 1, 2, or 3. + */ + uint8_t required_dim; + /** + * Reserved. Must be 0. + */ + uint8_t reserved2[75]; +} hsa_ext_control_directives_t; + +/** + * @brief Finalize an HSAIL program for a given instruction set architecture. + * + * @details Finalize all of the kernels and indirect functions that belong to + * the same HSAIL program for a specific instruction set architecture (ISA). The + * transitive closure of all functions specified by call or scall must be + * defined. Kernels and indirect functions that are being finalized must be + * defined. Kernels and indirect functions that are referenced in kernels and + * indirect functions being finalized may or may not be defined, but must be + * declared. All the global/readonly segment variables that are referenced in + * kernels and indirect functions being finalized may or may not be defined, but + * must be declared. + * + * @param[in] program HSAIL program. + * + * @param[in] isa Instruction set architecture to finalize for. + * + * @param[in] call_convention A call convention used in a finalization. Must + * have a value between ::HSA_EXT_FINALIZER_CALL_CONVENTION_AUTO (inclusive) + * and the value of the attribute ::HSA_ISA_INFO_CALL_CONVENTION_COUNT in @p + * isa (not inclusive). + * + * @param[in] control_directives Low-level control directives that influence + * the finalization process. + * + * @param[in] options Vendor-specific options. May be NULL. + * + * @param[in] code_object_type Type of code object to produce. + * + * @param[out] code_object Code object generated by the Finalizer, which + * contains the machine code for the kernels and indirect functions in the HSAIL + * program. The code object is independent of the HSAIL module that was used to + * generate it. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES There is a failure to allocate + * resources required for the operation. + * + * @retval ::HSA_EXT_STATUS_ERROR_INVALID_PROGRAM The HSAIL program is + * invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ISA @p isa is invalid. + * + * @retval ::HSA_EXT_STATUS_ERROR_DIRECTIVE_MISMATCH The directive in + * the control directive structure and in the HSAIL kernel mismatch, or if the + * same directive is used with a different value in one of the functions used by + * this kernel. + * + * @retval ::HSA_EXT_STATUS_ERROR_FINALIZATION_FAILED The Finalizer + * encountered an error while compiling a kernel or an indirect function. + */ +hsa_status_t HSA_API hsa_ext_program_finalize( + hsa_ext_program_t program, + hsa_isa_t isa, + int32_t call_convention, + hsa_ext_control_directives_t control_directives, + const char *options, + hsa_code_object_type_t code_object_type, + hsa_code_object_t *code_object); + +/** @} */ + +#define hsa_ext_finalizer_1_00 + +typedef struct hsa_ext_finalizer_1_00_pfn_s { + hsa_status_t (*hsa_ext_program_create)( + hsa_machine_model_t machine_model, hsa_profile_t profile, + hsa_default_float_rounding_mode_t default_float_rounding_mode, + const char *options, hsa_ext_program_t *program); + + hsa_status_t (*hsa_ext_program_destroy)(hsa_ext_program_t program); + + hsa_status_t (*hsa_ext_program_add_module)(hsa_ext_program_t program, + hsa_ext_module_t module); + + hsa_status_t (*hsa_ext_program_iterate_modules)( + hsa_ext_program_t program, + hsa_status_t (*callback)(hsa_ext_program_t program, + hsa_ext_module_t module, void *data), + void *data); + + hsa_status_t (*hsa_ext_program_get_info)( + hsa_ext_program_t program, hsa_ext_program_info_t attribute, + void *value); + + hsa_status_t (*hsa_ext_program_finalize)( + hsa_ext_program_t program, hsa_isa_t isa, int32_t call_convention, + hsa_ext_control_directives_t control_directives, const char *options, + hsa_code_object_type_t code_object_type, hsa_code_object_t *code_object); +} hsa_ext_finalizer_1_00_pfn_t; + +#ifdef __cplusplus +} // extern "C" block +#endif // __cplusplus + +#endif // HSA_RUNTIME_INC_HSA_EXT_FINALIZE_H_ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_ext_image.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_ext_image.h new file mode 100644 index 0000000000000000000000000000000000000000..b25f168395ccfca22ad2f22797572a1d72904d71 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_ext_image.h @@ -0,0 +1,1454 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// The University of Illinois/NCSA +// Open Source License (NCSA) +// +// Copyright (c) 2014-2020, Advanced Micro Devices, Inc. All rights reserved. +// +// Developed by: +// +// AMD Research and AMD HSA Software Development +// +// Advanced Micro Devices, Inc. +// +// www.amd.com +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal with 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: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimers in +// the documentation and/or other materials provided with the distribution. +// - Neither the names of Advanced Micro Devices, Inc, +// nor the names of its contributors may be used to endorse or promote +// products derived from this Software without specific prior written +// permission. +// +// 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 CONTRIBUTORS 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 WITH THE SOFTWARE. +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef HSA_EXT_IMAGE_H +#define HSA_EXT_IMAGE_H + +#include "hsa.h" + +#undef HSA_API +#ifdef HSA_EXPORT_IMAGES +#define HSA_API HSA_API_EXPORT +#else +#define HSA_API HSA_API_IMPORT +#endif + +#ifdef __cplusplus +extern "C" { +#endif /*__cplusplus*/ + +/** \defgroup ext-images Images and Samplers + * @{ + */ + +/** + * @brief Enumeration constants added to ::hsa_status_t by this extension. + * + * @remark Additions to hsa_status_t + */ +enum { + /** + * Image format is not supported. + */ + HSA_EXT_STATUS_ERROR_IMAGE_FORMAT_UNSUPPORTED = 0x3000, + /** + * Image size is not supported. + */ + HSA_EXT_STATUS_ERROR_IMAGE_SIZE_UNSUPPORTED = 0x3001, + /** + * Image pitch is not supported or invalid. + */ + HSA_EXT_STATUS_ERROR_IMAGE_PITCH_UNSUPPORTED = 0x3002, + /** + * Sampler descriptor is not supported or invalid. + */ + HSA_EXT_STATUS_ERROR_SAMPLER_DESCRIPTOR_UNSUPPORTED = 0x3003 +}; + +/** + * @brief Enumeration constants added to ::hsa_agent_info_t by this + * extension. + * + * @remark Additions to hsa_agent_info_t + */ +enum { + /** + * Maximum number of elements in 1D images. Must be at least 16384. The type + * of this attribute is size_t. + */ + HSA_EXT_AGENT_INFO_IMAGE_1D_MAX_ELEMENTS = 0x3000, + /** + * Maximum number of elements in 1DA images. Must be at least 16384. The type + * of this attribute is size_t. + */ + HSA_EXT_AGENT_INFO_IMAGE_1DA_MAX_ELEMENTS = 0x3001, + /** + * Maximum number of elements in 1DB images. Must be at least 65536. The type + * of this attribute is size_t. + */ + HSA_EXT_AGENT_INFO_IMAGE_1DB_MAX_ELEMENTS = 0x3002, + /** + * Maximum dimensions (width, height) of 2D images, in image elements. The X + * and Y maximums must be at least 16384. The type of this attribute is + * size_t[2]. + */ + HSA_EXT_AGENT_INFO_IMAGE_2D_MAX_ELEMENTS = 0x3003, + /** + * Maximum dimensions (width, height) of 2DA images, in image elements. The X + * and Y maximums must be at least 16384. The type of this attribute is + * size_t[2]. + */ + HSA_EXT_AGENT_INFO_IMAGE_2DA_MAX_ELEMENTS = 0x3004, + /** + * Maximum dimensions (width, height) of 2DDEPTH images, in image + * elements. The X and Y maximums must be at least 16384. The type of this + * attribute is size_t[2]. + */ + HSA_EXT_AGENT_INFO_IMAGE_2DDEPTH_MAX_ELEMENTS = 0x3005, + /** + * Maximum dimensions (width, height) of 2DADEPTH images, in image + * elements. The X and Y maximums must be at least 16384. The type of this + * attribute is size_t[2]. + */ + HSA_EXT_AGENT_INFO_IMAGE_2DADEPTH_MAX_ELEMENTS = 0x3006, + /** + * Maximum dimensions (width, height, depth) of 3D images, in image + * elements. The maximum along any dimension must be at least 2048. The type + * of this attribute is size_t[3]. + */ + HSA_EXT_AGENT_INFO_IMAGE_3D_MAX_ELEMENTS = 0x3007, + /** + * Maximum number of image layers in a image array. Must be at least 2048. The + * type of this attribute is size_t. + */ + HSA_EXT_AGENT_INFO_IMAGE_ARRAY_MAX_LAYERS = 0x3008, + /** + * Maximum number of read-only image handles that can be created for an agent at any one + * time. Must be at least 128. The type of this attribute is size_t. + */ + HSA_EXT_AGENT_INFO_MAX_IMAGE_RD_HANDLES = 0x3009, + /** + * Maximum number of write-only and read-write image handles (combined) that + * can be created for an agent at any one time. Must be at least 64. The type of this + * attribute is size_t. + */ + HSA_EXT_AGENT_INFO_MAX_IMAGE_RORW_HANDLES = 0x300A, + /** + * Maximum number of sampler handlers that can be created for an agent at any one + * time. Must be at least 16. The type of this attribute is size_t. + */ + HSA_EXT_AGENT_INFO_MAX_SAMPLER_HANDLERS = 0x300B, + /** + * Image pitch alignment. The agent only supports linear image data + * layouts with a row pitch that is a multiple of this value. Must be + * a power of 2. The type of this attribute is size_t. + */ + HSA_EXT_AGENT_INFO_IMAGE_LINEAR_ROW_PITCH_ALIGNMENT = 0x300C +}; + +/** + * @brief Image handle, populated by ::hsa_ext_image_create or + * ::hsa_ext_image_create_with_layout. Image + * handles are only unique within an agent, not across agents. + * + */ +typedef struct hsa_ext_image_s { + /** + * Opaque handle. For a given agent, two handles reference the same object of + * the enclosing type if and only if they are equal. + */ + uint64_t handle; + +} hsa_ext_image_t; + +/** + * @brief Geometry associated with the image. This specifies the + * number of image dimensions and whether the image is an image + * array. See the Image Geometry section in the HSA + * Programming Reference Manual for definitions on each + * geometry. The enumeration values match the BRIG type @p + * hsa_ext_brig_image_geometry_t. + */ +typedef enum { +/** + * One-dimensional image addressed by width coordinate. + */ + HSA_EXT_IMAGE_GEOMETRY_1D = 0, + + /** + * Two-dimensional image addressed by width and height coordinates. + */ + HSA_EXT_IMAGE_GEOMETRY_2D = 1, + + /** + * Three-dimensional image addressed by width, height, and depth coordinates. + */ + HSA_EXT_IMAGE_GEOMETRY_3D = 2, + + /** + * Array of one-dimensional images with the same size and format. 1D arrays + * are addressed by width and index coordinate. + */ + HSA_EXT_IMAGE_GEOMETRY_1DA = 3, + + /** + * Array of two-dimensional images with the same size and format. 2D arrays + * are addressed by width, height, and index coordinates. + */ + HSA_EXT_IMAGE_GEOMETRY_2DA = 4, + + /** + * One-dimensional image addressed by width coordinate. It has + * specific restrictions compared to ::HSA_EXT_IMAGE_GEOMETRY_1D. An + * image with an opaque image data layout will always use a linear + * image data layout, and one with an explicit image data layout + * must specify ::HSA_EXT_IMAGE_DATA_LAYOUT_LINEAR. + */ + HSA_EXT_IMAGE_GEOMETRY_1DB = 5, + + /** + * Two-dimensional depth image addressed by width and height coordinates. + */ + HSA_EXT_IMAGE_GEOMETRY_2DDEPTH = 6, + + /** + * Array of two-dimensional depth images with the same size and format. 2D + * arrays are addressed by width, height, and index coordinates. + */ + HSA_EXT_IMAGE_GEOMETRY_2DADEPTH = 7 +} hsa_ext_image_geometry_t; + +/** + * @brief Channel type associated with the elements of an image. See + * the Channel Type section in the HSA Programming Reference + * Manual for definitions on each channel type. The + * enumeration values and definition match the BRIG type @p + * hsa_ext_brig_image_channel_type_t. + */ +typedef enum { + HSA_EXT_IMAGE_CHANNEL_TYPE_SNORM_INT8 = 0, + HSA_EXT_IMAGE_CHANNEL_TYPE_SNORM_INT16 = 1, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_INT8 = 2, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_INT16 = 3, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_INT24 = 4, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_SHORT_555 = 5, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_SHORT_565 = 6, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNORM_SHORT_101010 = 7, + HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT8 = 8, + HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT16 = 9, + HSA_EXT_IMAGE_CHANNEL_TYPE_SIGNED_INT32 = 10, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT8 = 11, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT16 = 12, + HSA_EXT_IMAGE_CHANNEL_TYPE_UNSIGNED_INT32 = 13, + HSA_EXT_IMAGE_CHANNEL_TYPE_HALF_FLOAT = 14, + HSA_EXT_IMAGE_CHANNEL_TYPE_FLOAT = 15 +} hsa_ext_image_channel_type_t; + +/** + * @brief A fixed-size type used to represent ::hsa_ext_image_channel_type_t constants. + */ +typedef uint32_t hsa_ext_image_channel_type32_t; + +/** + * + * @brief Channel order associated with the elements of an image. See + * the Channel Order section in the HSA Programming Reference + * Manual for definitions on each channel order. The + * enumeration values match the BRIG type @p + * hsa_ext_brig_image_channel_order_t. + */ +typedef enum { + HSA_EXT_IMAGE_CHANNEL_ORDER_A = 0, + HSA_EXT_IMAGE_CHANNEL_ORDER_R = 1, + HSA_EXT_IMAGE_CHANNEL_ORDER_RX = 2, + HSA_EXT_IMAGE_CHANNEL_ORDER_RG = 3, + HSA_EXT_IMAGE_CHANNEL_ORDER_RGX = 4, + HSA_EXT_IMAGE_CHANNEL_ORDER_RA = 5, + HSA_EXT_IMAGE_CHANNEL_ORDER_RGB = 6, + HSA_EXT_IMAGE_CHANNEL_ORDER_RGBX = 7, + HSA_EXT_IMAGE_CHANNEL_ORDER_RGBA = 8, + HSA_EXT_IMAGE_CHANNEL_ORDER_BGRA = 9, + HSA_EXT_IMAGE_CHANNEL_ORDER_ARGB = 10, + HSA_EXT_IMAGE_CHANNEL_ORDER_ABGR = 11, + HSA_EXT_IMAGE_CHANNEL_ORDER_SRGB = 12, + HSA_EXT_IMAGE_CHANNEL_ORDER_SRGBX = 13, + HSA_EXT_IMAGE_CHANNEL_ORDER_SRGBA = 14, + HSA_EXT_IMAGE_CHANNEL_ORDER_SBGRA = 15, + HSA_EXT_IMAGE_CHANNEL_ORDER_INTENSITY = 16, + HSA_EXT_IMAGE_CHANNEL_ORDER_LUMINANCE = 17, + HSA_EXT_IMAGE_CHANNEL_ORDER_DEPTH = 18, + HSA_EXT_IMAGE_CHANNEL_ORDER_DEPTH_STENCIL = 19 +} hsa_ext_image_channel_order_t; + +/** + * @brief A fixed-size type used to represent ::hsa_ext_image_channel_order_t constants. + */ +typedef uint32_t hsa_ext_image_channel_order32_t; + + +/** + * @brief Image format. + */ +typedef struct hsa_ext_image_format_s { + /** + * Channel type. + */ + hsa_ext_image_channel_type32_t channel_type; + + /** + * Channel order. + */ + hsa_ext_image_channel_order32_t channel_order; +} hsa_ext_image_format_t; + +/** + * @brief Implementation independent image descriptor. + */ +typedef struct hsa_ext_image_descriptor_s { + /** + * Image geometry. + */ + hsa_ext_image_geometry_t geometry; + /** + * Width of the image, in components. + */ + size_t width; + /** + * Height of the image, in components. Only used if the geometry is + * ::HSA_EXT_IMAGE_GEOMETRY_2D, ::HSA_EXT_IMAGE_GEOMETRY_3D, + * HSA_EXT_IMAGE_GEOMETRY_2DA, HSA_EXT_IMAGE_GEOMETRY_2DDEPTH, or + * HSA_EXT_IMAGE_GEOMETRY_2DADEPTH, otherwise must be 0. + */ + size_t height; + /** + * Depth of the image, in components. Only used if the geometry is + * ::HSA_EXT_IMAGE_GEOMETRY_3D, otherwise must be 0. + */ + size_t depth; + /** + * Number of image layers in the image array. Only used if the geometry is + * ::HSA_EXT_IMAGE_GEOMETRY_1DA, ::HSA_EXT_IMAGE_GEOMETRY_2DA, or + * HSA_EXT_IMAGE_GEOMETRY_2DADEPTH, otherwise must be 0. + */ + size_t array_size; + /** + * Image format. + */ + hsa_ext_image_format_t format; +} hsa_ext_image_descriptor_t; + +/** + * @brief Image capability. + */ +typedef enum { + /** + * Images of this geometry, format, and layout are not supported by + * the agent. + */ + HSA_EXT_IMAGE_CAPABILITY_NOT_SUPPORTED = 0x0, + /** + * Read-only images of this geometry, format, and layout are + * supported by the agent. + */ + HSA_EXT_IMAGE_CAPABILITY_READ_ONLY = 0x1, + /** + * Write-only images of this geometry, format, and layout are + * supported by the agent. + */ + HSA_EXT_IMAGE_CAPABILITY_WRITE_ONLY = 0x2, + /** + * Read-write images of this geometry, format, and layout are + * supported by the agent. + */ + HSA_EXT_IMAGE_CAPABILITY_READ_WRITE = 0x4, + /** + * @deprecated Images of this geometry, format, and layout can be accessed from + * read-modify-write atomic operations in the agent. + */ + HSA_EXT_IMAGE_CAPABILITY_READ_MODIFY_WRITE = 0x8, + /** + * Images of this geometry, format, and layout are guaranteed to + * have a consistent data layout regardless of how they are + * accessed by the associated agent. + */ + HSA_EXT_IMAGE_CAPABILITY_ACCESS_INVARIANT_DATA_LAYOUT = 0x10 +} hsa_ext_image_capability_t; + +/** + * @brief Image data layout. + * + * @details An image data layout denotes such aspects of image data + * layout as tiling and organization of channels in memory. Some image + * data layouts may only apply to specific image geometries, formats, + * and access permissions. Different agents may support different + * image layout identifiers, including vendor specific layouts. Note + * that an agent may not support the same image data layout for + * different access permissions to images with the same image + * geometry, size, and format. If multiple agents support the same + * image data layout then it is possible to use separate image handles + * for each agent that references the same image data. + */ + +typedef enum { + /** + * An implementation specific opaque image data layout which can + * vary depending on the agent, geometry, image format, image size, + * and access permissions. + */ + HSA_EXT_IMAGE_DATA_LAYOUT_OPAQUE = 0x0, + /** + * The image data layout is specified by the following rules in + * ascending byte address order. For a 3D image, 2DA image array, + * or 1DA image array, the image data is stored as a linear sequence + * of adjacent 2D image slices, 2D images, or 1D images + * respectively, spaced according to the slice pitch. Each 2D image + * is stored as a linear sequence of adjacent image rows, spaced + * according to the row pitch. Each 1D or 1DB image is stored as a + * single image row. Each image row is stored as a linear sequence + * of image elements. Each image element is stored as a linear + * sequence of image components specified by the left to right + * channel order definition. Each image component is stored using + * the memory type specified by the channel type. + * + * The 1DB image geometry always uses the linear image data layout. + */ + HSA_EXT_IMAGE_DATA_LAYOUT_LINEAR = 0x1 +} hsa_ext_image_data_layout_t; + +/** + * @brief Retrieve the supported image capabilities for a given combination of + * agent, geometry, and image format for an image created with an opaque image + * data layout. + * + * @param[in] agent Agent to be associated with the image handle. + * + * @param[in] geometry Geometry. + * + * @param[in] image_format Pointer to an image format. Must not be NULL. + * + * @param[out] capability_mask Pointer to a memory location where the HSA + * runtime stores a bit-mask of supported image capability + * (::hsa_ext_image_capability_t) values. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p image_format is + * NULL, or @p capability_mask is NULL. + */ +hsa_status_t HSA_API hsa_ext_image_get_capability( + hsa_agent_t agent, + hsa_ext_image_geometry_t geometry, + const hsa_ext_image_format_t *image_format, + uint32_t *capability_mask); + +/** + * @brief Retrieve the supported image capabilities for a given combination of + * agent, geometry, image format, and image layout for an image created with + * an explicit image data layout. + * + * @param[in] agent Agent to be associated with the image handle. + * + * @param[in] geometry Geometry. + * + * @param[in] image_format Pointer to an image format. Must not be NULL. + * + * @param[in] image_data_layout The image data layout. + * It is invalid to use ::HSA_EXT_IMAGE_DATA_LAYOUT_OPAQUE; use + * ::hsa_ext_image_get_capability instead. + * + * @param[out] capability_mask Pointer to a memory location where the HSA + * runtime stores a bit-mask of supported image capability + * (::hsa_ext_image_capability_t) values. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p image_format is + * NULL, @p image_data_layout is ::HSA_EXT_IMAGE_DATA_LAYOUT_OPAQUE, + * or @p capability_mask is NULL. + */ +hsa_status_t HSA_API hsa_ext_image_get_capability_with_layout( + hsa_agent_t agent, + hsa_ext_image_geometry_t geometry, + const hsa_ext_image_format_t *image_format, + hsa_ext_image_data_layout_t image_data_layout, + uint32_t *capability_mask); + +/** + * @brief Agent specific image size and alignment requirements, populated by + * ::hsa_ext_image_data_get_info and ::hsa_ext_image_data_get_info_with_layout. + */ +typedef struct hsa_ext_image_data_info_s { + /** + * Image data size, in bytes. + */ + size_t size; + + /** + * Image data alignment, in bytes. Must always be a power of 2. + */ + size_t alignment; + +} hsa_ext_image_data_info_t; + +/** + * @brief Retrieve the image data requirements for a given combination of agent, image + * descriptor, and access permission for an image created with an opaque image + * data layout. + * + * @details The optimal image data size and alignment requirements may + * vary depending on the image attributes specified in @p + * image_descriptor, the @p access_permission, and the @p agent. Also, + * different implementations of the HSA runtime may return different + * requirements for the same input values. + * + * The implementation must return the same image data requirements for + * different access permissions with matching image descriptors as long + * as ::hsa_ext_image_get_capability reports + * ::HSA_EXT_IMAGE_CAPABILITY_ACCESS_INVARIANT_DATA_LAYOUT. Image + * descriptors match if they have the same values, with the exception + * that s-form channel orders match the corresponding non-s-form + * channel order and vice versa. + * + * @param[in] agent Agent to be associated with the image handle. + * + * @param[in] image_descriptor Pointer to an image descriptor. Must not be NULL. + * + * @param[in] access_permission Access permission of the image when + * accessed by @p agent. The access permission defines how the agent + * is allowed to access the image and must match the corresponding + * HSAIL image handle type. The @p agent must support the image format + * specified in @p image_descriptor for the given @p + * access_permission. + * + * @param[out] image_data_info Memory location where the runtime stores the + * size and alignment requirements. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_EXT_STATUS_ERROR_IMAGE_FORMAT_UNSUPPORTED The @p + * agent does not support the image format specified by @p + * image_descriptor with the specified @p access_permission. + * + * @retval ::HSA_EXT_STATUS_ERROR_IMAGE_SIZE_UNSUPPORTED The agent + * does not support the image dimensions specified by @p + * image_descriptor with the specified @p access_permission. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p image_descriptor is NULL, @p + * access_permission is not a valid access permission value, or @p + * image_data_info is NULL. + */ +hsa_status_t HSA_API hsa_ext_image_data_get_info( + hsa_agent_t agent, + const hsa_ext_image_descriptor_t *image_descriptor, + hsa_access_permission_t access_permission, + hsa_ext_image_data_info_t *image_data_info); + +/** + * @brief Retrieve the image data requirements for a given combination of + * image descriptor, access permission, image data layout, image data row pitch, + * and image data slice pitch for an image created with an explicit image + * data layout. + * + * @details The image data size and alignment requirements may vary + * depending on the image attributes specified in @p image_descriptor, + * the @p access_permission, and the image layout. However, different + * implementations of the HSA runtime will return the same + * requirements for the same input values. + * + * The implementation must return the same image data requirements for + * different access permissions with matching image descriptors and + * matching image layouts as long as ::hsa_ext_image_get_capability + * reports + * ::HSA_EXT_IMAGE_CAPABILITY_ACCESS_INVARIANT_DATA_LAYOUT. Image + * descriptors match if they have the same values, with the exception + * that s-form channel orders match the corresponding non-s-form + * channel order and vice versa. Image layouts match if they are the + * same image data layout and use the same image row and slice pitch + * values. + * + * @param[in] image_descriptor Pointer to an image descriptor. Must not be NULL. + * + * @param[in] access_permission Access permission of the image when + * accessed by an agent. The access permission defines how the agent + * is allowed to access the image and must match the corresponding + * HSAIL image handle type. + * + * @param[in] image_data_layout The image data layout to use. + * It is invalid to use ::HSA_EXT_IMAGE_DATA_LAYOUT_OPAQUE; use + * ::hsa_ext_image_data_get_info instead. + * + * @param[in] image_data_row_pitch The size in bytes for a single row + * of the image in the image data. If 0 is specified then the default + * row pitch value is used: image width * image element byte size. + * The value used must be greater than or equal to the default row + * pitch, and be a multiple of the image element byte size. For the + * linear image layout it must also be a multiple of the image linear + * row pitch alignment for the agents that will access the image data + * using image instructions. + * + * @param[in] image_data_slice_pitch The size in bytes of a single + * slice of a 3D image, or the size in bytes of each image layer in an + * image array in the image data. If 0 is specified then the default + * slice pitch value is used: row pitch * height if geometry is + * ::HSA_EXT_IMAGE_GEOMETRY_3D, ::HSA_EXT_IMAGE_GEOMETRY_2DA, or + * ::HSA_EXT_IMAGE_GEOMETRY_2DADEPTH; row pitch if geometry is + * ::HSA_EXT_IMAGE_GEOMETRY_1DA; and 0 otherwise. The value used must + * be 0 if the default slice pitch is 0, be greater than or equal to + * the default slice pitch, and be a multiple of the row pitch. + * + * @param[out] image_data_info Memory location where the runtime stores the + * size and alignment requirements. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_EXT_STATUS_ERROR_IMAGE_FORMAT_UNSUPPORTED The image + * format specified by @p image_descriptor is not supported for the + * @p access_permission and @p image_data_layout specified. + * + * @retval ::HSA_EXT_STATUS_ERROR_IMAGE_SIZE_UNSUPPORTED The image + * dimensions specified by @p image_descriptor are not supported for + * the @p access_permission and @p image_data_layout specified. + * + * @retval ::HSA_EXT_STATUS_ERROR_IMAGE_PITCH_UNSUPPORTED The row and + * slice pitch specified by @p image_data_row_pitch and @p + * image_data_slice_pitch are invalid or not supported. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p image_descriptor is + * NULL, @p image_data_layout is ::HSA_EXT_IMAGE_DATA_LAYOUT_OPAQUE, + * or @p image_data_info is NULL. + */ +hsa_status_t HSA_API hsa_ext_image_data_get_info_with_layout( + hsa_agent_t agent, + const hsa_ext_image_descriptor_t *image_descriptor, + hsa_access_permission_t access_permission, + hsa_ext_image_data_layout_t image_data_layout, + size_t image_data_row_pitch, + size_t image_data_slice_pitch, + hsa_ext_image_data_info_t *image_data_info); + +/** + * @brief Creates an agent specific image handle to an image with an + * opaque image data layout. + * + * @details Images with an opaque image data layout created with + * different access permissions but matching image descriptors and + * same agent can share the same image data if + * ::HSA_EXT_IMAGE_CAPABILITY_ACCESS_INVARIANT_DATA_LAYOUT is reported + * by ::hsa_ext_image_get_capability for the image format specified in + * the image descriptor. Image descriptors match if they have the same + * values, with the exception that s-form channel orders match the + * corresponding non-s-form channel order and vice versa. + * + * If necessary, an application can use image operations (import, + * export, copy, clear) to prepare the image for the intended use + * regardless of the access permissions. + * + * @param[in] agent agent to be associated with the image handle created. + * + * @param[in] image_descriptor Pointer to an image descriptor. Must not be NULL. + * + * @param[in] image_data Image data buffer that must have been allocated + * according to the size and alignment requirements dictated by + * ::hsa_ext_image_data_get_info. Must not be NULL. + * + * Any previous memory contents are preserved upon creation. The application is + * responsible for ensuring that the lifetime of the image data exceeds that of + * all the associated images. + * + * @param[in] access_permission Access permission of the image when + * accessed by agent. The access permission defines how the agent + * is allowed to access the image using the image handle created and + * must match the corresponding HSAIL image handle type. The agent + * must support the image format specified in @p image_descriptor for + * the given @p access_permission. + * + * @param[out] image Pointer to a memory location where the HSA runtime stores + * the newly created image handle. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_EXT_STATUS_ERROR_IMAGE_FORMAT_UNSUPPORTED The agent + * does not have the capability to support the image format contained + * in @p image_descriptor using the specified @p access_permission. + * + * @retval ::HSA_EXT_STATUS_ERROR_IMAGE_SIZE_UNSUPPORTED The agent + * does not support the image dimensions specified by @p + * image_descriptor using the specified @p access_permission. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to allocate + * the required resources. + * + * support the creation of more image handles with the given @p access_permission). + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p image_descriptor is NULL, @p + * image_data is NULL, @p image_data does not have a valid alignment, + * @p access_permission is not a valid access permission + * value, or @p image is NULL. + */ +hsa_status_t HSA_API hsa_ext_image_create( + hsa_agent_t agent, + const hsa_ext_image_descriptor_t *image_descriptor, + const void *image_data, + hsa_access_permission_t access_permission, + hsa_ext_image_t *image); + +/** + * @brief Creates an agent specific image handle to an image with an explicit + * image data layout. + * + * @details Images with an explicit image data layout created with + * different access permissions but matching image descriptors and + * matching image layout can share the same image data if + * ::HSA_EXT_IMAGE_CAPABILITY_ACCESS_INVARIANT_DATA_LAYOUT is reported + * by ::hsa_ext_image_get_capability_with_layout for the image format + * specified in the image descriptor and specified image data + * layout. Image descriptors match if they have the same values, with + * the exception that s-form channel orders match the corresponding + * non-s-form channel order and vice versa. Image layouts match if + * they are the same image data layout and use the same image row and + * slice values. + * + * If necessary, an application can use image operations (import, export, copy, + * clear) to prepare the image for the intended use regardless of the access + * permissions. + * + * @param[in] agent agent to be associated with the image handle created. + * + * @param[in] image_descriptor Pointer to an image descriptor. Must not be NULL. + * + * @param[in] image_data Image data buffer that must have been allocated + * according to the size and alignment requirements dictated by + * ::hsa_ext_image_data_get_info_with_layout. Must not be NULL. + * + * Any previous memory contents are preserved upon creation. The application is + * responsible for ensuring that the lifetime of the image data exceeds that of + * all the associated images. + * + * @param[in] access_permission Access permission of the image when + * accessed by the agent. The access permission defines how the agent + * is allowed to access the image and must match the corresponding + * HSAIL image handle type. The agent must support the image format + * specified in @p image_descriptor for the given @p access_permission + * and @p image_data_layout. + * + * @param[in] image_data_layout The image data layout to use for the + * @p image_data. It is invalid to use + * ::HSA_EXT_IMAGE_DATA_LAYOUT_OPAQUE; use ::hsa_ext_image_create + * instead. + * + * @param[in] image_data_row_pitch The size in bytes for a single row + * of the image in the image data. If 0 is specified then the default + * row pitch value is used: image width * image element byte size. + * The value used must be greater than or equal to the default row + * pitch, and be a multiple of the image element byte size. For the + * linear image layout it must also be a multiple of the image linear + * row pitch alignment for the agents that will access the image data + * using image instructions. + * + * @param[in] image_data_slice_pitch The size in bytes of a single + * slice of a 3D image, or the size in bytes of each image layer in an + * image array in the image data. If 0 is specified then the default + * slice pitch value is used: row pitch * height if geometry is + * ::HSA_EXT_IMAGE_GEOMETRY_3D, ::HSA_EXT_IMAGE_GEOMETRY_2DA, or + * ::HSA_EXT_IMAGE_GEOMETRY_2DADEPTH; row pitch if geometry is + * ::HSA_EXT_IMAGE_GEOMETRY_1DA; and 0 otherwise. The value used must + * be 0 if the default slice pitch is 0, be greater than or equal to + * the default slice pitch, and be a multiple of the row pitch. + * + * @param[out] image Pointer to a memory location where the HSA runtime stores + * the newly created image handle. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_EXT_STATUS_ERROR_IMAGE_FORMAT_UNSUPPORTED The agent does + * not have the capability to support the image format contained in the image + * descriptor using the specified @p access_permission and @p image_data_layout. + * + * @retval ::HSA_EXT_STATUS_ERROR_IMAGE_SIZE_UNSUPPORTED The agent + * does not support the image dimensions specified by @p + * image_descriptor using the specified @p access_permission and @p + * image_data_layout. + * + * @retval ::HSA_EXT_STATUS_ERROR_IMAGE_PITCH_UNSUPPORTED The agent does + * not support the row and slice pitch specified by @p image_data_row_pitch + * and @p image_data_slice_pitch, or the values are invalid. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to allocate + * the required resources. + * + * support the creation of more image handles with the given @p access_permission). + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p image_descriptor is NULL, @p + * image_data is NULL, @p image_data does not have a valid alignment, + * @p image_data_layout is ::HSA_EXT_IMAGE_DATA_LAYOUT_OPAQUE, + * or @p image is NULL. + */ +hsa_status_t HSA_API hsa_ext_image_create_with_layout( + hsa_agent_t agent, + const hsa_ext_image_descriptor_t *image_descriptor, + const void *image_data, + hsa_access_permission_t access_permission, + hsa_ext_image_data_layout_t image_data_layout, + size_t image_data_row_pitch, + size_t image_data_slice_pitch, + hsa_ext_image_t *image); + +/** + * @brief Destroy an image handle previously created using ::hsa_ext_image_create or + * ::hsa_ext_image_create_with_layout. + * + * @details Destroying the image handle does not free the associated image data, + * or modify its contents. The application should not destroy an image handle while + * there are references to it queued for execution or currently being used in a + * kernel dispatch. + * + * @param[in] agent Agent associated with the image handle. + * + * @param[in] image Image handle to destroy. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + */ +hsa_status_t HSA_API hsa_ext_image_destroy( + hsa_agent_t agent, + hsa_ext_image_t image); + +/** + * @brief Copies a portion of one image (the source) to another image (the + * destination). + * + * @details The source and destination image formats should be the + * same, with the exception that s-form channel orders match the + * corresponding non-s-form channel order and vice versa. For example, + * it is allowed to copy a source image with a channel order of + * HSA_EXT_IMAGE_CHANNEL_ORDER_SRGB to a destination image with a + * channel order of HSA_EXT_IMAGE_CHANNEL_ORDER_RGB. + * + * The source and destination images do not have to be of the same geometry and + * appropriate scaling is performed by the HSA runtime. It is possible to copy + * subregions between any combinations of source and destination geometries, provided + * that the dimensions of the subregions are the same. For example, it is + * allowed to copy a rectangular region from a 2D image to a slice of a 3D + * image. + * + * If the source and destination image data overlap, or the combination of + * offset and range references an out-out-bounds element in any of the images, + * the behavior is undefined. + * + * @param[in] agent Agent associated with both the source and destination image handles. + * + * @param[in] src_image Image handle of source image. The agent associated with the source + * image handle must be identical to that of the destination image. + * + * @param[in] src_offset Pointer to the offset within the source image where to + * copy the data from. Must not be NULL. + * + * @param[in] dst_image Image handle of destination image. + * + * @param[in] dst_offset Pointer to the offset within the destination + * image where to copy the data. Must not be NULL. + * + * @param[in] range Dimensions of the image portion to be copied. The HSA + * runtime computes the size of the image data to be copied using this + * argument. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p src_offset is + * NULL, @p dst_offset is NULL, or @p range is NULL. + */ +hsa_status_t HSA_API hsa_ext_image_copy( + hsa_agent_t agent, + hsa_ext_image_t src_image, + const hsa_dim3_t* src_offset, + hsa_ext_image_t dst_image, + const hsa_dim3_t* dst_offset, + const hsa_dim3_t* range); + +/** + * @brief Image region. + */ +typedef struct hsa_ext_image_region_s { + /** + * Offset within an image (in coordinates). + */ + hsa_dim3_t offset; + + /** + * Dimension size of the image range (in coordinates). The x, y, and z dimensions + * correspond to width, height, and depth or index respectively. + */ + hsa_dim3_t range; +} hsa_ext_image_region_t; + +/** + * @brief Import a linearly organized image data from memory directly to an + * image handle. + * + * @details This operation updates the image data referenced by the image handle + * from the source memory. The size of the data imported from memory is + * implicitly derived from the image region. + * + * It is the application's responsibility to avoid out of bounds memory access. + * + * None of the source memory or destination image data memory can + * overlap. Overlapping of any of the source and destination image + * data memory within the import operation produces undefined results. + * + * @param[in] agent Agent associated with the image handle. + * + * @param[in] src_memory Source memory. Must not be NULL. + * + * @param[in] src_row_pitch The size in bytes of a single row of the image in the + * source memory. If the value is smaller than the destination image region + * width * image element byte size, then region width * image element byte + * size is used. + * + * @param[in] src_slice_pitch The size in bytes of a single 2D slice of a 3D image, + * or the size in bytes of each image layer in an image array in the source memory. + * If the geometry is ::HSA_EXT_IMAGE_GEOMETRY_1DA and the value is smaller than the + * value used for @p src_row_pitch, then the value used for @p src_row_pitch is used. + * If the geometry is ::HSA_EXT_IMAGE_GEOMETRY_3D, ::HSA_EXT_IMAGE_GEOMETRY_2DA, or + * HSA_EXT_IMAGE_GEOMETRY_2DADEPTH and the value is smaller than the value used for + * @p src_row_pitch * destination image region height, then the value used for + * @p src_row_pitch * destination image region height is used. + * Otherwise, the value is not used. + * + * @param[in] dst_image Image handle of destination image. + * + * @param[in] image_region Pointer to the image region to be updated. Must not + * be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p src_memory is NULL, or @p + * image_region is NULL. + * + */ +hsa_status_t HSA_API hsa_ext_image_import( + hsa_agent_t agent, + const void *src_memory, + size_t src_row_pitch, + size_t src_slice_pitch, + hsa_ext_image_t dst_image, + const hsa_ext_image_region_t *image_region); + +/** + * @brief Export the image data to linearly organized memory. + * + * @details The operation updates the destination memory with the image data of + * @p src_image. The size of the data exported to memory is implicitly derived + * from the image region. + * + * It is the application's responsibility to avoid out of bounds memory access. + * + * None of the destination memory or source image data memory can + * overlap. Overlapping of any of the source and destination image + * data memory within the export operation produces undefined results. + * + * @param[in] agent Agent associated with the image handle. + * + * @param[in] src_image Image handle of source image. + * + * @param[in] dst_memory Destination memory. Must not be NULL. + * + * @param[in] dst_row_pitch The size in bytes of a single row of the image in the + * destination memory. If the value is smaller than the source image region + * width * image element byte size, then region width * image element byte + * size is used. + * + * @param[in] dst_slice_pitch The size in bytes of a single 2D slice of a 3D image, + * or the size in bytes of each image in an image array in the destination memory. + * If the geometry is ::HSA_EXT_IMAGE_GEOMETRY_1DA and the value is smaller than the + * value used for @p dst_row_pitch, then the value used for @p dst_row_pitch is used. + * If the geometry is ::HSA_EXT_IMAGE_GEOMETRY_3D, ::HSA_EXT_IMAGE_GEOMETRY_2DA, or + * HSA_EXT_IMAGE_GEOMETRY_2DADEPTH and the value is smaller than the value used for + * @p dst_row_pitch * source image region height, then the value used for + * @p dst_row_pitch * source image region height is used. + * Otherwise, the value is not used. + * + * @param[in] image_region Pointer to the image region to be exported. Must not + * be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p dst_memory is NULL, or @p + * image_region is NULL. + */ +hsa_status_t HSA_API hsa_ext_image_export( + hsa_agent_t agent, + hsa_ext_image_t src_image, + void *dst_memory, + size_t dst_row_pitch, + size_t dst_slice_pitch, + const hsa_ext_image_region_t *image_region); + +/** + * @brief Clear a region of an image so that every image element has + * the specified value. + * + * @param[in] agent Agent associated with the image handle. + * + * @param[in] image Image handle for image to be cleared. + * + * @param[in] data The value to which to set each image element being + * cleared. It is specified as an array of image component values. The + * number of array elements must match the number of access components + * for the image channel order. The type of each array element must + * match the image access type of the image channel type. When the + * value is used to set the value of an image element, the conversion + * method corresponding to the image channel type is used. See the + * Channel Order section and Channel Type section in + * the HSA Programming Reference Manual for more + * information. Must not be NULL. + * + * @param[in] image_region Pointer to the image region to clear. Must not be + * NULL. If the region references an out-out-bounds element, the behavior is + * undefined. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p data is NULL, or @p + * image_region is NULL. + */ +hsa_status_t HSA_API hsa_ext_image_clear( + hsa_agent_t agent, + hsa_ext_image_t image, + const void* data, + const hsa_ext_image_region_t *image_region); + +/** + * @brief Sampler handle. Samplers are populated by + * ::hsa_ext_sampler_create. Sampler handles are only unique within an + * agent, not across agents. + */ +typedef struct hsa_ext_sampler_s { + /** + * Opaque handle. For a given agent, two handles reference the same object of + * the enclosing type if and only if they are equal. + */ + uint64_t handle; +} hsa_ext_sampler_t; + +/** + * @brief Sampler address modes. The sampler address mode describes + * the processing of out-of-range image coordinates. See the + * Addressing Mode section in the HSA Programming Reference + * Manual for definitions on each address mode. The values + * match the BRIG type @p hsa_ext_brig_sampler_addressing_t. + */ +typedef enum { + /** + * Out-of-range coordinates are not handled. + */ + HSA_EXT_SAMPLER_ADDRESSING_MODE_UNDEFINED = 0, + + /** + * Clamp out-of-range coordinates to the image edge. + */ + HSA_EXT_SAMPLER_ADDRESSING_MODE_CLAMP_TO_EDGE = 1, + + /** + * Clamp out-of-range coordinates to the image border color. + */ + HSA_EXT_SAMPLER_ADDRESSING_MODE_CLAMP_TO_BORDER = 2, + + /** + * Wrap out-of-range coordinates back into the valid coordinate + * range so the image appears as repeated tiles. + */ + HSA_EXT_SAMPLER_ADDRESSING_MODE_REPEAT = 3, + + /** + * Mirror out-of-range coordinates back into the valid coordinate + * range so the image appears as repeated tiles with every other + * tile a reflection. + */ + HSA_EXT_SAMPLER_ADDRESSING_MODE_MIRRORED_REPEAT = 4 + +} hsa_ext_sampler_addressing_mode_t; + +/** + * @brief A fixed-size type used to represent ::hsa_ext_sampler_addressing_mode_t constants. + */ +typedef uint32_t hsa_ext_sampler_addressing_mode32_t; + +/** + * @brief Sampler coordinate normalization modes. See the + * Coordinate Normalization Mode section in the HSA + * Programming Reference Manual for definitions on each + * coordinate normalization mode. The values match the BRIG type @p + * hsa_ext_brig_sampler_coord_normalization_t. + */ +typedef enum { + + /** + * Coordinates are used to directly address an image element. + */ + HSA_EXT_SAMPLER_COORDINATE_MODE_UNNORMALIZED = 0, + + /** + * Coordinates are scaled by the image dimension size before being + * used to address an image element. + */ + HSA_EXT_SAMPLER_COORDINATE_MODE_NORMALIZED = 1 + +} hsa_ext_sampler_coordinate_mode_t; + +/** + * @brief A fixed-size type used to represent ::hsa_ext_sampler_coordinate_mode_t constants. + */ +typedef uint32_t hsa_ext_sampler_coordinate_mode32_t; + + +/** + * @brief Sampler filter modes. See the Filter Mode section + * in the HSA Programming Reference Manual for definitions + * on each address mode. The enumeration values match the BRIG type @p + * hsa_ext_brig_sampler_filter_t. + */ +typedef enum { + /** + * Filter to the image element nearest (in Manhattan distance) to the + * specified coordinate. + */ + HSA_EXT_SAMPLER_FILTER_MODE_NEAREST = 0, + + /** + * Filter to the image element calculated by combining the elements in a 2x2 + * square block or 2x2x2 cube block around the specified coordinate. The + * elements are combined using linear interpolation. + */ + HSA_EXT_SAMPLER_FILTER_MODE_LINEAR = 1 + +} hsa_ext_sampler_filter_mode_t; + +/** + * @brief A fixed-size type used to represent ::hsa_ext_sampler_filter_mode_t constants. + */ +typedef uint32_t hsa_ext_sampler_filter_mode32_t; + +/** + * @brief Implementation independent sampler descriptor. + */ +typedef struct hsa_ext_sampler_descriptor_s { + /** + * Sampler coordinate mode describes the normalization of image coordinates. + */ + hsa_ext_sampler_coordinate_mode32_t coordinate_mode; + + /** + * Sampler filter type describes the type of sampling performed. + */ + hsa_ext_sampler_filter_mode32_t filter_mode; + + /** + * Sampler address mode describes the processing of out-of-range image + * coordinates. + */ + hsa_ext_sampler_addressing_mode32_t address_mode; + +} hsa_ext_sampler_descriptor_t; + +/** + * @brief Create an agent specific sampler handle for a given agent + * independent sampler descriptor and agent. + * + * @param[in] agent Agent to be associated with the sampler handle created. + * + * @param[in] sampler_descriptor Pointer to a sampler descriptor. Must not be + * NULL. + * + * @param[out] sampler Memory location where the HSA runtime stores the newly + * created sampler handle. Must not be NULL. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + * + * @retval ::HSA_EXT_STATUS_ERROR_SAMPLER_DESCRIPTOR_UNSUPPORTED The + * @p agent does not have the capability to support the properties + * specified by @p sampler_descriptor or it is invalid. + * + * @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES The HSA runtime failed to allocate + * the required resources. + * + * @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT @p sampler_descriptor is NULL, or + * @p sampler is NULL. + */ +hsa_status_t HSA_API hsa_ext_sampler_create( + hsa_agent_t agent, + const hsa_ext_sampler_descriptor_t *sampler_descriptor, + hsa_ext_sampler_t *sampler); + +/** + * @brief Destroy a sampler handle previously created using ::hsa_ext_sampler_create. + * + * @details The sampler handle should not be destroyed while there are + * references to it queued for execution or currently being used in a + * kernel dispatch. + * + * @param[in] agent Agent associated with the sampler handle. + * + * @param[in] sampler Sampler handle to destroy. + * + * @retval ::HSA_STATUS_SUCCESS The function has been executed successfully. + * + * @retval ::HSA_STATUS_ERROR_NOT_INITIALIZED The HSA runtime has not been + * initialized. + * + * @retval ::HSA_STATUS_ERROR_INVALID_AGENT The agent is invalid. + */ +hsa_status_t HSA_API hsa_ext_sampler_destroy( + hsa_agent_t agent, + hsa_ext_sampler_t sampler); + + +#define hsa_ext_images_1_00 + +/** + * @brief The function pointer table for the images v1.00 extension. Can be returned by ::hsa_system_get_extension_table or ::hsa_system_get_major_extension_table. + */ +typedef struct hsa_ext_images_1_00_pfn_s { + + hsa_status_t (*hsa_ext_image_get_capability)( + hsa_agent_t agent, + hsa_ext_image_geometry_t geometry, + const hsa_ext_image_format_t *image_format, + uint32_t *capability_mask); + + hsa_status_t (*hsa_ext_image_data_get_info)( + hsa_agent_t agent, + const hsa_ext_image_descriptor_t *image_descriptor, + hsa_access_permission_t access_permission, + hsa_ext_image_data_info_t *image_data_info); + + hsa_status_t (*hsa_ext_image_create)( + hsa_agent_t agent, + const hsa_ext_image_descriptor_t *image_descriptor, + const void *image_data, + hsa_access_permission_t access_permission, + hsa_ext_image_t *image); + + hsa_status_t (*hsa_ext_image_destroy)( + hsa_agent_t agent, + hsa_ext_image_t image); + + hsa_status_t (*hsa_ext_image_copy)( + hsa_agent_t agent, + hsa_ext_image_t src_image, + const hsa_dim3_t* src_offset, + hsa_ext_image_t dst_image, + const hsa_dim3_t* dst_offset, + const hsa_dim3_t* range); + + hsa_status_t (*hsa_ext_image_import)( + hsa_agent_t agent, + const void *src_memory, + size_t src_row_pitch, + size_t src_slice_pitch, + hsa_ext_image_t dst_image, + const hsa_ext_image_region_t *image_region); + + hsa_status_t (*hsa_ext_image_export)( + hsa_agent_t agent, + hsa_ext_image_t src_image, + void *dst_memory, + size_t dst_row_pitch, + size_t dst_slice_pitch, + const hsa_ext_image_region_t *image_region); + + hsa_status_t (*hsa_ext_image_clear)( + hsa_agent_t agent, + hsa_ext_image_t image, + const void* data, + const hsa_ext_image_region_t *image_region); + + hsa_status_t (*hsa_ext_sampler_create)( + hsa_agent_t agent, + const hsa_ext_sampler_descriptor_t *sampler_descriptor, + hsa_ext_sampler_t *sampler); + + hsa_status_t (*hsa_ext_sampler_destroy)( + hsa_agent_t agent, + hsa_ext_sampler_t sampler); + +} hsa_ext_images_1_00_pfn_t; + +#define hsa_ext_images_1 + +/** + * @brief The function pointer table for the images v1 extension. Can be returned by ::hsa_system_get_extension_table or ::hsa_system_get_major_extension_table. + */ +typedef struct hsa_ext_images_1_pfn_s { + + hsa_status_t (*hsa_ext_image_get_capability)( + hsa_agent_t agent, + hsa_ext_image_geometry_t geometry, + const hsa_ext_image_format_t *image_format, + uint32_t *capability_mask); + + hsa_status_t (*hsa_ext_image_data_get_info)( + hsa_agent_t agent, + const hsa_ext_image_descriptor_t *image_descriptor, + hsa_access_permission_t access_permission, + hsa_ext_image_data_info_t *image_data_info); + + hsa_status_t (*hsa_ext_image_create)( + hsa_agent_t agent, + const hsa_ext_image_descriptor_t *image_descriptor, + const void *image_data, + hsa_access_permission_t access_permission, + hsa_ext_image_t *image); + + hsa_status_t (*hsa_ext_image_destroy)( + hsa_agent_t agent, + hsa_ext_image_t image); + + hsa_status_t (*hsa_ext_image_copy)( + hsa_agent_t agent, + hsa_ext_image_t src_image, + const hsa_dim3_t* src_offset, + hsa_ext_image_t dst_image, + const hsa_dim3_t* dst_offset, + const hsa_dim3_t* range); + + hsa_status_t (*hsa_ext_image_import)( + hsa_agent_t agent, + const void *src_memory, + size_t src_row_pitch, + size_t src_slice_pitch, + hsa_ext_image_t dst_image, + const hsa_ext_image_region_t *image_region); + + hsa_status_t (*hsa_ext_image_export)( + hsa_agent_t agent, + hsa_ext_image_t src_image, + void *dst_memory, + size_t dst_row_pitch, + size_t dst_slice_pitch, + const hsa_ext_image_region_t *image_region); + + hsa_status_t (*hsa_ext_image_clear)( + hsa_agent_t agent, + hsa_ext_image_t image, + const void* data, + const hsa_ext_image_region_t *image_region); + + hsa_status_t (*hsa_ext_sampler_create)( + hsa_agent_t agent, + const hsa_ext_sampler_descriptor_t *sampler_descriptor, + hsa_ext_sampler_t *sampler); + + hsa_status_t (*hsa_ext_sampler_destroy)( + hsa_agent_t agent, + hsa_ext_sampler_t sampler); + + hsa_status_t (*hsa_ext_image_get_capability_with_layout)( + hsa_agent_t agent, + hsa_ext_image_geometry_t geometry, + const hsa_ext_image_format_t *image_format, + hsa_ext_image_data_layout_t image_data_layout, + uint32_t *capability_mask); + + hsa_status_t (*hsa_ext_image_data_get_info_with_layout)( + hsa_agent_t agent, + const hsa_ext_image_descriptor_t *image_descriptor, + hsa_access_permission_t access_permission, + hsa_ext_image_data_layout_t image_data_layout, + size_t image_data_row_pitch, + size_t image_data_slice_pitch, + hsa_ext_image_data_info_t *image_data_info); + + hsa_status_t (*hsa_ext_image_create_with_layout)( + hsa_agent_t agent, + const hsa_ext_image_descriptor_t *image_descriptor, + const void *image_data, + hsa_access_permission_t access_permission, + hsa_ext_image_data_layout_t image_data_layout, + size_t image_data_row_pitch, + size_t image_data_slice_pitch, + hsa_ext_image_t *image); + +} hsa_ext_images_1_pfn_t; +/** @} */ + +#ifdef __cplusplus +} // end extern "C" block +#endif /*__cplusplus*/ + +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_ven_amd_aqlprofile.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_ven_amd_aqlprofile.h new file mode 100644 index 0000000000000000000000000000000000000000..0022c0d8b8b68db8f9971881511f2b6a73726a52 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/hsa/hsa_ven_amd_aqlprofile.h @@ -0,0 +1,488 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// The University of Illinois/NCSA +// Open Source License (NCSA) +// +// Copyright (c) 2017-2020, Advanced Micro Devices, Inc. All rights reserved. +// +// Developed by: +// +// AMD Research and AMD HSA Software Development +// +// Advanced Micro Devices, Inc. +// +// www.amd.com +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal with 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: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimers in +// the documentation and/or other materials provided with the distribution. +// - Neither the names of Advanced Micro Devices, Inc, +// nor the names of its contributors may be used to endorse or promote +// products derived from this Software without specific prior written +// permission. +// +// 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 CONTRIBUTORS 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 WITH THE SOFTWARE. +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef OPENSRC_HSA_RUNTIME_INC_HSA_VEN_AMD_AQLPROFILE_H_ +#define OPENSRC_HSA_RUNTIME_INC_HSA_VEN_AMD_AQLPROFILE_H_ + +#include +#include "hsa.h" + +#define HSA_AQLPROFILE_VERSION_MAJOR 2 +#define HSA_AQLPROFILE_VERSION_MINOR 0 + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +//////////////////////////////////////////////////////////////////////////////// +// Library version +uint32_t hsa_ven_amd_aqlprofile_version_major(); +uint32_t hsa_ven_amd_aqlprofile_version_minor(); + +/////////////////////////////////////////////////////////////////////// +// Library API: +// The library provides helper methods for instantiation of +// the profile context object and for populating of the start +// and stop AQL packets. The profile object contains a profiling +// events list and needed for profiling buffers descriptors, +// a command buffer and an output data buffer. To check if there +// was an error the library methods return a status code. Also +// the library provides methods for querying required buffers +// attributes, to validate the event attributes and to get profiling +// output data. +// +// Returned status: +// hsa_status_t – HSA status codes are used from hsa.h header +// +// Supported profiling features: +// +// Supported profiling events +typedef enum { + HSA_VEN_AMD_AQLPROFILE_EVENT_TYPE_PMC = 0, + HSA_VEN_AMD_AQLPROFILE_EVENT_TYPE_TRACE = 1, +} hsa_ven_amd_aqlprofile_event_type_t; + +// Supported performance counters (PMC) blocks +// The block ID is the same for a block instances set, for example +// each block instance from the TCC block set, TCC0, TCC1, …, TCCN +// will have the same block ID HSA_VEN_AMD_AQLPROFILE_BLOCKS_TCC. +typedef enum { + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_CPC = 0, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_CPF = 1, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_GDS = 2, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_GRBM = 3, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_GRBMSE = 4, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_SPI = 5, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_SQ = 6, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_SQCS = 7, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_SRBM = 8, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_SX = 9, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_TA = 10, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_TCA = 11, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_TCC = 12, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_TCP = 13, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_TD = 14, + // Memory related blocks + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_MCARB = 15, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_MCHUB = 16, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_MCMCBVM = 17, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_MCSEQ = 18, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_MCVML2 = 19, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_MCXBAR = 20, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_ATC = 21, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_ATCL2 = 22, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_GCEA = 23, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_RPB = 24, + // System blocks + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_SDMA = 25, + // GFX10 added blocks + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_GL1A = 26, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_GL1C = 27, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_GL2A = 28, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_GL2C = 29, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_GCR = 30, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_GUS = 31, + + // UMC & MMEA System Blocks + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_UMC = 32, + HSA_VEN_AMD_AQLPROFILE_BLOCK_NAME_MMEA = 33, + + HSA_VEN_AMD_AQLPROFILE_BLOCKS_NUMBER +} hsa_ven_amd_aqlprofile_block_name_t; + +// PMC event object structure +// ‘counter_id’ value is specified in GFXIPs perfcounter user guides +// which is the counters select value, “Performance Counters Selection” +// chapter. +typedef struct { + hsa_ven_amd_aqlprofile_block_name_t block_name; + uint32_t block_index; + uint32_t counter_id; +} hsa_ven_amd_aqlprofile_event_t; + +// Check if event is valid for the specific GPU +hsa_status_t hsa_ven_amd_aqlprofile_validate_event( + hsa_agent_t agent, // HSA handle for the profiling GPU + const hsa_ven_amd_aqlprofile_event_t* event, // [in] Pointer on validated event + bool* result); // [out] True if the event valid, False otherwise + +// Profiling parameters +// All parameters are generic and if not applicable for a specific +// profile configuration then error status will be returned. +typedef enum { + /** + * Select the target compute unit (wgp) for profiling. + */ + HSA_VEN_AMD_AQLPROFILE_PARAMETER_NAME_COMPUTE_UNIT_TARGET = 0, + /** + * VMID Mask + */ + HSA_VEN_AMD_AQLPROFILE_PARAMETER_NAME_VM_ID_MASK = 1, + /** + * Legacy. Deprecated. + */ + HSA_VEN_AMD_AQLPROFILE_PARAMETER_NAME_MASK = 2, + /** + * Legacy. Deprecated. + */ + HSA_VEN_AMD_AQLPROFILE_PARAMETER_NAME_TOKEN_MASK = 3, + /** + * Legacy. Deprecated. + */ + HSA_VEN_AMD_AQLPROFILE_PARAMETER_NAME_TOKEN_MASK2 = 4, + /** + * Shader engine mask for selection. + */ + HSA_VEN_AMD_AQLPROFILE_PARAMETER_NAME_SE_MASK = 5, + /** + * Legacy. Deprecated. + */ + HSA_VEN_AMD_AQLPROFILE_PARAMETER_NAME_SAMPLE_RATE = 6, + /** + * Legacy. Deprecated. + */ + HSA_VEN_AMD_AQLPROFILE_PARAMETER_NAME_K_CONCURRENT = 7, + /** + * Set SIMD Mask (GFX9) or SIMD ID for collection (Navi) + */ + HSA_VEN_AMD_AQLPROFILE_PARAMETER_NAME_SIMD_SELECTION = 8, + /** + * Set true for occupancy collection only. + */ + HSA_VEN_AMD_AQLPROFILE_PARAMETER_NAME_OCCUPANCY_MODE = 9, + /** + * ATT collection max data size, in MB. Shared among shader engines. + */ + HSA_VEN_AMD_AQLPROFILE_PARAMETER_NAME_ATT_BUFFER_SIZE = 10, + /** + * Mask of which compute units to generate perfcounters. GFX9 only. + */ + HSA_VEN_AMD_AQLPROFILE_PARAMETER_NAME_PERFCOUNTER_MASK = 240, + /** + * Select collection period for perfcounters. GFX9 only. + */ + HSA_VEN_AMD_AQLPROFILE_PARAMETER_NAME_PERFCOUNTER_CTRL = 241, + /** + * Select perfcounter ID (SQ block) for collection. GFX9 only. + */ + HSA_VEN_AMD_AQLPROFILE_PARAMETER_NAME_PERFCOUNTER_NAME = 242, +} hsa_ven_amd_aqlprofile_parameter_name_t; + +// Profile parameter object +typedef struct { + hsa_ven_amd_aqlprofile_parameter_name_t parameter_name; + uint32_t value; +} hsa_ven_amd_aqlprofile_parameter_t; + +typedef enum { + HSA_VEN_AMD_AQLPROFILE_ATT_CHANNEL_0 = 0, + HSA_VEN_AMD_AQLPROFILE_ATT_CHANNEL_1, + HSA_VEN_AMD_AQLPROFILE_ATT_CHANNEL_2, + HSA_VEN_AMD_AQLPROFILE_ATT_CHANNEL_3 +} hsa_ven_amd_aqlprofile_att_marker_channel_t; + +// +// Profile context object: +// The library provides a profile object structure which contains +// the events array, a buffer for the profiling start/stop commands +// and a buffer for the output data. +// The buffers are specified by the buffer descriptors and allocated +// by the application. The buffers allocation attributes, the command +// buffer size, the PMC output buffer size as well as profiling output +// data can be get using the generic get profile info helper _get_info. +// +// Buffer descriptor +typedef struct { + void* ptr; + uint32_t size; +} hsa_ven_amd_aqlprofile_descriptor_t; + +// Profile context object structure, contains profiling events list and +// needed for profiling buffers descriptors, a command buffer and +// an output data buffer +typedef struct { + hsa_agent_t agent; // GFXIP handle + hsa_ven_amd_aqlprofile_event_type_t type; // Events type + const hsa_ven_amd_aqlprofile_event_t* events; // Events array + uint32_t event_count; // Events count + const hsa_ven_amd_aqlprofile_parameter_t* parameters; // Parameters array + uint32_t parameter_count; // Parameters count + hsa_ven_amd_aqlprofile_descriptor_t output_buffer; // Output buffer + hsa_ven_amd_aqlprofile_descriptor_t command_buffer; // PM4 commands +} hsa_ven_amd_aqlprofile_profile_t; + +// +// AQL packets populating methods: +// The helper methods to populate provided by the application START and +// STOP AQL packets which the application is required to submit before and +// after profiled GPU task packets respectively. +// +// AQL Vendor Specific packet which carries a PM4 command +typedef struct { + uint16_t header; + uint16_t pm4_command[27]; + hsa_signal_t completion_signal; +} hsa_ext_amd_aql_pm4_packet_t; + +// Method to populate the provided AQL packet with profiling start commands +// Only 'pm4_command' fields of the packet are set and the application +// is responsible to set Vendor Specific header type a completion signal +hsa_status_t hsa_ven_amd_aqlprofile_start( + hsa_ven_amd_aqlprofile_profile_t* profile, // [in/out] profile contex object + hsa_ext_amd_aql_pm4_packet_t* aql_start_packet); // [out] profile start AQL packet + +// Method to populate the provided AQL packet with profiling stop commands +// Only 'pm4_command' fields of the packet are set and the application +// is responsible to set Vendor Specific header type and a completion signal +hsa_status_t hsa_ven_amd_aqlprofile_stop( + const hsa_ven_amd_aqlprofile_profile_t* profile, // [in] profile contex object + hsa_ext_amd_aql_pm4_packet_t* aql_stop_packet); // [out] profile stop AQL packet + +// Method to populate the provided AQL packet with profiling read commands +// Only 'pm4_command' fields of the packet are set and the application +// is responsible to set Vendor Specific header type and a completion signal +hsa_status_t hsa_ven_amd_aqlprofile_read( + const hsa_ven_amd_aqlprofile_profile_t* profile, // [in] profile contex object + hsa_ext_amd_aql_pm4_packet_t* aql_read_packet); // [out] profile stop AQL packet + +// Legacy devices, PM4 profiling packet size +const unsigned HSA_VEN_AMD_AQLPROFILE_LEGACY_PM4_PACKET_SIZE = 192; +// Legacy devices, converting the profiling AQL packet to PM4 packet blob +hsa_status_t hsa_ven_amd_aqlprofile_legacy_get_pm4( + const hsa_ext_amd_aql_pm4_packet_t* aql_packet, // [in] AQL packet + void* data); // [out] PM4 packet blob + +// Method to add a marker (correlation ID) into the ATT buffer. +hsa_status_t hsa_ven_amd_aqlprofile_att_marker( + hsa_ven_amd_aqlprofile_profile_t* profile, // [in/out] profile contex object + hsa_ext_amd_aql_pm4_packet_t* aql_marker_packet, // [out] profile marker AQL packet + uint32_t data, // [in] Data to be inserted + hsa_ven_amd_aqlprofile_att_marker_channel_t channel); // [in] Comm channel + +// +// Get profile info: +// Generic method for getting various profile info including profile buffers +// attributes like the command buffer size and the profiling PMC results. +// It’s implied that all counters are 64bit values. +// +// Profile generic output data: +typedef struct { + uint32_t sample_id; // PMC sample or trace buffer index + union { + struct { + hsa_ven_amd_aqlprofile_event_t event; // PMC event + uint64_t result; // PMC result + } pmc_data; + hsa_ven_amd_aqlprofile_descriptor_t trace_data; // Trace output data descriptor + }; +} hsa_ven_amd_aqlprofile_info_data_t; + +// ID query type +typedef struct { + const char* name; + uint32_t id; + uint32_t instance_count; +} hsa_ven_amd_aqlprofile_id_query_t; + +// Profile attributes +typedef enum { + HSA_VEN_AMD_AQLPROFILE_INFO_COMMAND_BUFFER_SIZE = 0, // get_info returns uint32_t value + HSA_VEN_AMD_AQLPROFILE_INFO_PMC_DATA_SIZE = 1, // get_info returns uint32_t value + HSA_VEN_AMD_AQLPROFILE_INFO_PMC_DATA = 2, // get_info returns PMC uint64_t value + // in info_data object + HSA_VEN_AMD_AQLPROFILE_INFO_TRACE_DATA = 3, // get_info returns trace buffer ptr/size + // in info_data object + HSA_VEN_AMD_AQLPROFILE_INFO_BLOCK_COUNTERS = 4, // get_info returns number of block counter + HSA_VEN_AMD_AQLPROFILE_INFO_BLOCK_ID = 5, // get_info returns block id, instances + // by name string using _id_query_t + HSA_VEN_AMD_AQLPROFILE_INFO_ENABLE_CMD = 6, // get_info returns size/pointer for + // counters enable command buffer + HSA_VEN_AMD_AQLPROFILE_INFO_DISABLE_CMD = 7, // get_info returns size/pointer for + // counters disable command buffer +} hsa_ven_amd_aqlprofile_info_type_t; + + +// Definition of output data iterator callback +typedef hsa_status_t (*hsa_ven_amd_aqlprofile_data_callback_t)( + hsa_ven_amd_aqlprofile_info_type_t info_type, // [in] data type, PMC or trace data + hsa_ven_amd_aqlprofile_info_data_t* info_data, // [in] info_data object + void* callback_data); // [in/out] data passed to the callback + +// Method for getting the profile info +hsa_status_t hsa_ven_amd_aqlprofile_get_info( + const hsa_ven_amd_aqlprofile_profile_t* profile, // [in] profile context object + hsa_ven_amd_aqlprofile_info_type_t attribute, // [in] requested profile attribute + void* value); // [in/out] returned value + +// Method for iterating the events output data +hsa_status_t hsa_ven_amd_aqlprofile_iterate_data( + const hsa_ven_amd_aqlprofile_profile_t* profile, // [in] profile context object + hsa_ven_amd_aqlprofile_data_callback_t callback, // [in] callback to iterate the output data + void* data); // [in/out] data passed to the callback + +// Return error string +hsa_status_t hsa_ven_amd_aqlprofile_error_string( + const char** str); // [out] pointer on the error string + +/** + * @brief Callback for iteration of all possible event coordinate IDs and coordinate names. + */ +typedef hsa_status_t(*hsa_ven_amd_aqlprofile_eventname_callback_t)(int id, const char* name); +/** + * @brief Iterate over all possible event coordinate IDs and their names. + */ +hsa_status_t hsa_ven_amd_aqlprofile_iterate_event_ids(hsa_ven_amd_aqlprofile_eventname_callback_t); + +/** + * @brief Iterate over all event coordinates for a given agent_t and event_t. + * @param position A counting sequence indicating callback number. + * @param id Coordinate ID as in _iterate_event_ids. + * @param extent Coordinate extent indicating maximum allowed instances. + * @param coordinate The coordinate, in the range [0,extent-1]. + * @param name Coordinate name as in _iterate_event_ids. + * @param userdata Userdata returned from _iterate_event_coord function. + */ +typedef hsa_status_t(*hsa_ven_amd_aqlprofile_coordinate_callback_t)( + int position, + int id, + int extent, + int coordinate, + const char* name, + void* userdata +); + +/** + * @brief Iterate over all event coordinates for a given agent_t and event_t. + * @param[in] agent HSA agent. + * @param[in] event The event ID and block ID to iterate for. + * @param[in] sample_id aqlprofile_info_data_t.sample_id returned from _aqlprofile_iterate_data. + * @param[in] callback Callback function to return the coordinates. + * @param[in] userdata Arbitrary data pointer to be sent back to the user via callback. + */ +hsa_status_t hsa_ven_amd_aqlprofile_iterate_event_coord( + hsa_agent_t agent, + hsa_ven_amd_aqlprofile_event_t event, + uint32_t sample_id, + hsa_ven_amd_aqlprofile_coordinate_callback_t callback, + void* userdata +); + +/** + * @brief Extension version. + */ +#define hsa_ven_amd_aqlprofile_VERSION_MAJOR 1 +#define hsa_ven_amd_aqlprofile_LIB(suff) "libhsa-amd-aqlprofile" suff ".so" + +#ifdef HSA_LARGE_MODEL +static const char kAqlProfileLib[] = hsa_ven_amd_aqlprofile_LIB("64"); +#else +static const char kAqlProfileLib[] = hsa_ven_amd_aqlprofile_LIB(""); +#endif + +/** + * @brief Extension function table. + */ +typedef struct hsa_ven_amd_aqlprofile_1_00_pfn_s { + uint32_t (*hsa_ven_amd_aqlprofile_version_major)(); + uint32_t (*hsa_ven_amd_aqlprofile_version_minor)(); + + hsa_status_t (*hsa_ven_amd_aqlprofile_error_string)( + const char** str); + + hsa_status_t (*hsa_ven_amd_aqlprofile_validate_event)( + hsa_agent_t agent, + const hsa_ven_amd_aqlprofile_event_t* event, + bool* result); + + hsa_status_t (*hsa_ven_amd_aqlprofile_start)( + hsa_ven_amd_aqlprofile_profile_t* profile, + hsa_ext_amd_aql_pm4_packet_t* aql_start_packet); + + hsa_status_t (*hsa_ven_amd_aqlprofile_stop)( + const hsa_ven_amd_aqlprofile_profile_t* profile, + hsa_ext_amd_aql_pm4_packet_t* aql_stop_packet); + + hsa_status_t (*hsa_ven_amd_aqlprofile_read)( + const hsa_ven_amd_aqlprofile_profile_t* profile, + hsa_ext_amd_aql_pm4_packet_t* aql_read_packet); + + hsa_status_t (*hsa_ven_amd_aqlprofile_legacy_get_pm4)( + const hsa_ext_amd_aql_pm4_packet_t* aql_packet, + void* data); + + hsa_status_t (*hsa_ven_amd_aqlprofile_get_info)( + const hsa_ven_amd_aqlprofile_profile_t* profile, + hsa_ven_amd_aqlprofile_info_type_t attribute, + void* value); + + hsa_status_t (*hsa_ven_amd_aqlprofile_iterate_data)( + const hsa_ven_amd_aqlprofile_profile_t* profile, + hsa_ven_amd_aqlprofile_data_callback_t callback, + void* data); + + hsa_status_t (*hsa_ven_amd_aqlprofile_iterate_event_ids)( + hsa_ven_amd_aqlprofile_eventname_callback_t + ); + + hsa_status_t (*hsa_ven_amd_aqlprofile_iterate_event_coord)( + hsa_agent_t agent, + hsa_ven_amd_aqlprofile_event_t event, + uint32_t sample_id, + hsa_ven_amd_aqlprofile_coordinate_callback_t callback, + void* userdata + ); + + hsa_status_t (*hsa_ven_amd_aqlprofile_att_marker)( + hsa_ven_amd_aqlprofile_profile_t* profile, + hsa_ext_amd_aql_pm4_packet_t* aql_packet, + uint32_t data, + hsa_ven_amd_aqlprofile_att_marker_channel_t channel + ); +} hsa_ven_amd_aqlprofile_1_00_pfn_t; + +typedef hsa_ven_amd_aqlprofile_1_00_pfn_t hsa_ven_amd_aqlprofile_pfn_t; + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif // OPENSRC_HSA_RUNTIME_INC_HSA_VEN_AMD_AQLPROFILE_H_ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/roctracer/hip_ostream_ops.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/roctracer/hip_ostream_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..eba2592fa30584cdb0a50f5badb61c81c3f9ede2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/roctracer/hip_ostream_ops.h @@ -0,0 +1,4515 @@ +// automatically generated +/* +Copyright (c) 2018 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 INC_HIP_OSTREAM_OPS_H_ +#define INC_HIP_OSTREAM_OPS_H_ + +#include +#include +#include "roctracer.h" + +#ifdef __cplusplus +#include +#include +#include +#include + +namespace roctracer { +namespace hip_support { +static int HIP_depth_max = 1; +static int HIP_depth_max_cnt = 0; +static std::string HIP_structs_regex = ""; +// begin ostream ops for HIP +// basic ostream ops +namespace detail { + inline static void print_escaped_string(std::ostream& out, const char *v, size_t len) { + out << '"'; + for (size_t i = 0; i < len && v[i]; ++i) { + switch (v[i]) { + case '\"': out << "\\\""; break; + case '\\': out << "\\\\"; break; + case '\b': out << "\\\b"; break; + case '\f': out << "\\\f"; break; + case '\n': out << "\\\n"; break; + case '\r': out << "\\\r"; break; + case '\t': out << "\\\t"; break; + default: + if (std::isprint((unsigned char)v[i])) std::operator<<(out, v[i]); + else { + std::ios_base::fmtflags flags(out.flags()); + out << "\\x" << std::setfill('0') << std::setw(2) << std::hex << (unsigned int)(unsigned char)v[i]; + out.flags(flags); + } + break; + } + } + out << '"'; + } + + template + inline static std::ostream& operator<<(std::ostream& out, const T& v) { + using std::operator<<; + static bool recursion = false; + if (recursion == false) { recursion = true; out << v; recursion = false; } + return out; + } + + inline static std::ostream &operator<<(std::ostream &out, const unsigned char &v) { + out << (unsigned int)v; + return out; + } + + inline static std::ostream &operator<<(std::ostream &out, const char &v) { + out << (unsigned char)v; + return out; + } + + template + inline static std::ostream &operator<<(std::ostream &out, const char (&v)[N]) { + print_escaped_string(out, v, N); + return out; + } + + inline static std::ostream &operator<<(std::ostream &out, const char *v) { + print_escaped_string(out, v, strlen(v)); + return out; + } +// End of basic ostream ops + +inline static std::ostream& operator<<(std::ostream& out, const __locale_struct& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("__locale_struct::__names").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "__names="); + roctracer::hip_support::detail::operator<<(out, v.__names); + std::operator<<(out, ", "); + } + if (std::string("__locale_struct::__ctype_toupper").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "__ctype_toupper="); + roctracer::hip_support::detail::operator<<(out, v.__ctype_toupper); + std::operator<<(out, ", "); + } + if (std::string("__locale_struct::__ctype_tolower").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "__ctype_tolower="); + roctracer::hip_support::detail::operator<<(out, v.__ctype_tolower); + std::operator<<(out, ", "); + } + if (std::string("__locale_struct::__ctype_b").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "__ctype_b="); + roctracer::hip_support::detail::operator<<(out, v.__ctype_b); + std::operator<<(out, ", "); + } + if (std::string("__locale_struct::__locales").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "__locales="); + roctracer::hip_support::detail::operator<<(out, v.__locales); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipDeviceArch_t& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipDeviceArch_t::hasDynamicParallelism").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasDynamicParallelism="); + roctracer::hip_support::detail::operator<<(out, v.hasDynamicParallelism); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::has3dGrid").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "has3dGrid="); + roctracer::hip_support::detail::operator<<(out, v.has3dGrid); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasSurfaceFuncs").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasSurfaceFuncs="); + roctracer::hip_support::detail::operator<<(out, v.hasSurfaceFuncs); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasSyncThreadsExt").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasSyncThreadsExt="); + roctracer::hip_support::detail::operator<<(out, v.hasSyncThreadsExt); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasThreadFenceSystem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasThreadFenceSystem="); + roctracer::hip_support::detail::operator<<(out, v.hasThreadFenceSystem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasFunnelShift").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasFunnelShift="); + roctracer::hip_support::detail::operator<<(out, v.hasFunnelShift); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasWarpShuffle").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasWarpShuffle="); + roctracer::hip_support::detail::operator<<(out, v.hasWarpShuffle); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasWarpBallot").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasWarpBallot="); + roctracer::hip_support::detail::operator<<(out, v.hasWarpBallot); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasWarpVote").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasWarpVote="); + roctracer::hip_support::detail::operator<<(out, v.hasWarpVote); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasDoubles").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasDoubles="); + roctracer::hip_support::detail::operator<<(out, v.hasDoubles); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasSharedInt64Atomics").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasSharedInt64Atomics="); + roctracer::hip_support::detail::operator<<(out, v.hasSharedInt64Atomics); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasGlobalInt64Atomics").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasGlobalInt64Atomics="); + roctracer::hip_support::detail::operator<<(out, v.hasGlobalInt64Atomics); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasFloatAtomicAdd").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasFloatAtomicAdd="); + roctracer::hip_support::detail::operator<<(out, v.hasFloatAtomicAdd); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasSharedFloatAtomicExch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasSharedFloatAtomicExch="); + roctracer::hip_support::detail::operator<<(out, v.hasSharedFloatAtomicExch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasSharedInt32Atomics").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasSharedInt32Atomics="); + roctracer::hip_support::detail::operator<<(out, v.hasSharedInt32Atomics); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasGlobalFloatAtomicExch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasGlobalFloatAtomicExch="); + roctracer::hip_support::detail::operator<<(out, v.hasGlobalFloatAtomicExch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasGlobalInt32Atomics").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasGlobalInt32Atomics="); + roctracer::hip_support::detail::operator<<(out, v.hasGlobalInt32Atomics); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipUUID& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipUUID::bytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "bytes="); + roctracer::hip_support::detail::operator<<(out, v.bytes); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipDeviceProp_tR0600& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipDeviceProp_tR0600::asicRevision").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "asicRevision="); + roctracer::hip_support::detail::operator<<(out, v.asicRevision); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::isLargeBar").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "isLargeBar="); + roctracer::hip_support::detail::operator<<(out, v.isLargeBar); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::cooperativeMultiDeviceUnmatchedSharedMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedSharedMem="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedSharedMem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::cooperativeMultiDeviceUnmatchedBlockDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedBlockDim="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedBlockDim); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::cooperativeMultiDeviceUnmatchedGridDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedGridDim="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedGridDim); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::cooperativeMultiDeviceUnmatchedFunc").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedFunc="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedFunc); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::hdpRegFlushCntl").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hdpRegFlushCntl="); + roctracer::hip_support::detail::operator<<(out, v.hdpRegFlushCntl); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::hdpMemFlushCntl").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hdpMemFlushCntl="); + roctracer::hip_support::detail::operator<<(out, v.hdpMemFlushCntl); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::arch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "arch="); + roctracer::hip_support::detail::operator<<(out, v.arch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::clockInstructionRate").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "clockInstructionRate="); + roctracer::hip_support::detail::operator<<(out, v.clockInstructionRate); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSharedMemoryPerMultiProcessor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSharedMemoryPerMultiProcessor="); + roctracer::hip_support::detail::operator<<(out, v.maxSharedMemoryPerMultiProcessor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::gcnArchName").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gcnArchName="); + roctracer::hip_support::detail::operator<<(out, v.gcnArchName); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::hipReserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hipReserved="); + roctracer::hip_support::detail::operator<<(out, v.hipReserved); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::unifiedFunctionPointers").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "unifiedFunctionPointers="); + roctracer::hip_support::detail::operator<<(out, v.unifiedFunctionPointers); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::clusterLaunch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "clusterLaunch="); + roctracer::hip_support::detail::operator<<(out, v.clusterLaunch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::ipcEventSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "ipcEventSupported="); + roctracer::hip_support::detail::operator<<(out, v.ipcEventSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::deferredMappingHipArraySupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "deferredMappingHipArraySupported="); + roctracer::hip_support::detail::operator<<(out, v.deferredMappingHipArraySupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::memoryPoolSupportedHandleTypes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memoryPoolSupportedHandleTypes="); + roctracer::hip_support::detail::operator<<(out, v.memoryPoolSupportedHandleTypes); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::gpuDirectRDMAWritesOrdering").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gpuDirectRDMAWritesOrdering="); + roctracer::hip_support::detail::operator<<(out, v.gpuDirectRDMAWritesOrdering); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::gpuDirectRDMAFlushWritesOptions").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gpuDirectRDMAFlushWritesOptions="); + roctracer::hip_support::detail::operator<<(out, v.gpuDirectRDMAFlushWritesOptions); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::gpuDirectRDMASupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gpuDirectRDMASupported="); + roctracer::hip_support::detail::operator<<(out, v.gpuDirectRDMASupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::memoryPoolsSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memoryPoolsSupported="); + roctracer::hip_support::detail::operator<<(out, v.memoryPoolsSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::timelineSemaphoreInteropSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "timelineSemaphoreInteropSupported="); + roctracer::hip_support::detail::operator<<(out, v.timelineSemaphoreInteropSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::hostRegisterReadOnlySupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hostRegisterReadOnlySupported="); + roctracer::hip_support::detail::operator<<(out, v.hostRegisterReadOnlySupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::sparseHipArraySupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sparseHipArraySupported="); + roctracer::hip_support::detail::operator<<(out, v.sparseHipArraySupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::hostRegisterSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hostRegisterSupported="); + roctracer::hip_support::detail::operator<<(out, v.hostRegisterSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::reservedSharedMemPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reservedSharedMemPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.reservedSharedMemPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::accessPolicyMaxWindowSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "accessPolicyMaxWindowSize="); + roctracer::hip_support::detail::operator<<(out, v.accessPolicyMaxWindowSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxBlocksPerMultiProcessor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxBlocksPerMultiProcessor="); + roctracer::hip_support::detail::operator<<(out, v.maxBlocksPerMultiProcessor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::directManagedMemAccessFromHost").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "directManagedMemAccessFromHost="); + roctracer::hip_support::detail::operator<<(out, v.directManagedMemAccessFromHost); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::pageableMemoryAccessUsesHostPageTables").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pageableMemoryAccessUsesHostPageTables="); + roctracer::hip_support::detail::operator<<(out, v.pageableMemoryAccessUsesHostPageTables); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::sharedMemPerBlockOptin").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedMemPerBlockOptin="); + roctracer::hip_support::detail::operator<<(out, v.sharedMemPerBlockOptin); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::cooperativeMultiDeviceLaunch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceLaunch="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceLaunch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::cooperativeLaunch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeLaunch="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeLaunch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::canUseHostPointerForRegisteredMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "canUseHostPointerForRegisteredMem="); + roctracer::hip_support::detail::operator<<(out, v.canUseHostPointerForRegisteredMem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::computePreemptionSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "computePreemptionSupported="); + roctracer::hip_support::detail::operator<<(out, v.computePreemptionSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::concurrentManagedAccess").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "concurrentManagedAccess="); + roctracer::hip_support::detail::operator<<(out, v.concurrentManagedAccess); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::pageableMemoryAccess").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pageableMemoryAccess="); + roctracer::hip_support::detail::operator<<(out, v.pageableMemoryAccess); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::singleToDoublePrecisionPerfRatio").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "singleToDoublePrecisionPerfRatio="); + roctracer::hip_support::detail::operator<<(out, v.singleToDoublePrecisionPerfRatio); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::hostNativeAtomicSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hostNativeAtomicSupported="); + roctracer::hip_support::detail::operator<<(out, v.hostNativeAtomicSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::multiGpuBoardGroupID").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "multiGpuBoardGroupID="); + roctracer::hip_support::detail::operator<<(out, v.multiGpuBoardGroupID); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::isMultiGpuBoard").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "isMultiGpuBoard="); + roctracer::hip_support::detail::operator<<(out, v.isMultiGpuBoard); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::managedMemory").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "managedMemory="); + roctracer::hip_support::detail::operator<<(out, v.managedMemory); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::regsPerMultiprocessor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "regsPerMultiprocessor="); + roctracer::hip_support::detail::operator<<(out, v.regsPerMultiprocessor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::sharedMemPerMultiprocessor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedMemPerMultiprocessor="); + roctracer::hip_support::detail::operator<<(out, v.sharedMemPerMultiprocessor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::localL1CacheSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "localL1CacheSupported="); + roctracer::hip_support::detail::operator<<(out, v.localL1CacheSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::globalL1CacheSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "globalL1CacheSupported="); + roctracer::hip_support::detail::operator<<(out, v.globalL1CacheSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::streamPrioritiesSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "streamPrioritiesSupported="); + roctracer::hip_support::detail::operator<<(out, v.streamPrioritiesSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxThreadsPerMultiProcessor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxThreadsPerMultiProcessor="); + roctracer::hip_support::detail::operator<<(out, v.maxThreadsPerMultiProcessor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::persistingL2CacheMaxSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "persistingL2CacheMaxSize="); + roctracer::hip_support::detail::operator<<(out, v.persistingL2CacheMaxSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::l2CacheSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "l2CacheSize="); + roctracer::hip_support::detail::operator<<(out, v.l2CacheSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::memoryBusWidth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memoryBusWidth="); + roctracer::hip_support::detail::operator<<(out, v.memoryBusWidth); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::memoryClockRate").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memoryClockRate="); + roctracer::hip_support::detail::operator<<(out, v.memoryClockRate); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::unifiedAddressing").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "unifiedAddressing="); + roctracer::hip_support::detail::operator<<(out, v.unifiedAddressing); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::asyncEngineCount").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "asyncEngineCount="); + roctracer::hip_support::detail::operator<<(out, v.asyncEngineCount); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::tccDriver").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "tccDriver="); + roctracer::hip_support::detail::operator<<(out, v.tccDriver); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::pciDomainID").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pciDomainID="); + roctracer::hip_support::detail::operator<<(out, v.pciDomainID); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::pciDeviceID").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pciDeviceID="); + roctracer::hip_support::detail::operator<<(out, v.pciDeviceID); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::pciBusID").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pciBusID="); + roctracer::hip_support::detail::operator<<(out, v.pciBusID); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::ECCEnabled").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "ECCEnabled="); + roctracer::hip_support::detail::operator<<(out, v.ECCEnabled); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::concurrentKernels").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "concurrentKernels="); + roctracer::hip_support::detail::operator<<(out, v.concurrentKernels); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::surfaceAlignment").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "surfaceAlignment="); + roctracer::hip_support::detail::operator<<(out, v.surfaceAlignment); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSurfaceCubemapLayered").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSurfaceCubemapLayered="); + roctracer::hip_support::detail::operator<<(out, v.maxSurfaceCubemapLayered); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSurfaceCubemap").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSurfaceCubemap="); + roctracer::hip_support::detail::operator<<(out, v.maxSurfaceCubemap); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSurface2DLayered").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSurface2DLayered="); + roctracer::hip_support::detail::operator<<(out, v.maxSurface2DLayered); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSurface1DLayered").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSurface1DLayered="); + roctracer::hip_support::detail::operator<<(out, v.maxSurface1DLayered); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSurface3D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSurface3D="); + roctracer::hip_support::detail::operator<<(out, v.maxSurface3D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSurface2D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSurface2D="); + roctracer::hip_support::detail::operator<<(out, v.maxSurface2D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSurface1D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSurface1D="); + roctracer::hip_support::detail::operator<<(out, v.maxSurface1D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTextureCubemapLayered").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTextureCubemapLayered="); + roctracer::hip_support::detail::operator<<(out, v.maxTextureCubemapLayered); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture2DLayered").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture2DLayered="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture2DLayered); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture1DLayered").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture1DLayered="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture1DLayered); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTextureCubemap").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTextureCubemap="); + roctracer::hip_support::detail::operator<<(out, v.maxTextureCubemap); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture3DAlt").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture3DAlt="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture3DAlt); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture3D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture3D="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture3D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture2DGather").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture2DGather="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture2DGather); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture2DLinear").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture2DLinear="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture2DLinear); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture2DMipmap").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture2DMipmap="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture2DMipmap); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture2D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture2D="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture2D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture1DLinear").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture1DLinear="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture1DLinear); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture1DMipmap").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture1DMipmap="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture1DMipmap); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture1D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture1D="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture1D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::computeMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "computeMode="); + roctracer::hip_support::detail::operator<<(out, v.computeMode); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::canMapHostMemory").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "canMapHostMemory="); + roctracer::hip_support::detail::operator<<(out, v.canMapHostMemory); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::integrated").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "integrated="); + roctracer::hip_support::detail::operator<<(out, v.integrated); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::kernelExecTimeoutEnabled").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "kernelExecTimeoutEnabled="); + roctracer::hip_support::detail::operator<<(out, v.kernelExecTimeoutEnabled); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::multiProcessorCount").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "multiProcessorCount="); + roctracer::hip_support::detail::operator<<(out, v.multiProcessorCount); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::deviceOverlap").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "deviceOverlap="); + roctracer::hip_support::detail::operator<<(out, v.deviceOverlap); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::texturePitchAlignment").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "texturePitchAlignment="); + roctracer::hip_support::detail::operator<<(out, v.texturePitchAlignment); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::textureAlignment").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "textureAlignment="); + roctracer::hip_support::detail::operator<<(out, v.textureAlignment); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::minor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "minor="); + roctracer::hip_support::detail::operator<<(out, v.minor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::major").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "major="); + roctracer::hip_support::detail::operator<<(out, v.major); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::totalConstMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "totalConstMem="); + roctracer::hip_support::detail::operator<<(out, v.totalConstMem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::clockRate").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "clockRate="); + roctracer::hip_support::detail::operator<<(out, v.clockRate); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxGridSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxGridSize="); + roctracer::hip_support::detail::operator<<(out, v.maxGridSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxThreadsDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxThreadsDim="); + roctracer::hip_support::detail::operator<<(out, v.maxThreadsDim); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxThreadsPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxThreadsPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.maxThreadsPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::memPitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memPitch="); + roctracer::hip_support::detail::operator<<(out, v.memPitch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::warpSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "warpSize="); + roctracer::hip_support::detail::operator<<(out, v.warpSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::regsPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "regsPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.regsPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::sharedMemPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedMemPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.sharedMemPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::totalGlobalMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "totalGlobalMem="); + roctracer::hip_support::detail::operator<<(out, v.totalGlobalMem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::luidDeviceNodeMask").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "luidDeviceNodeMask="); + roctracer::hip_support::detail::operator<<(out, v.luidDeviceNodeMask); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::luid").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "luid="); + roctracer::hip_support::detail::operator<<(out, v.luid); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::uuid").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "uuid="); + roctracer::hip_support::detail::operator<<(out, v.uuid); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::name").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "name="); + roctracer::hip_support::detail::operator<<(out, v.name); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipPointerAttribute_t& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipPointerAttribute_t::allocationFlags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "allocationFlags="); + roctracer::hip_support::detail::operator<<(out, v.allocationFlags); + std::operator<<(out, ", "); + } + if (std::string("hipPointerAttribute_t::isManaged").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "isManaged="); + roctracer::hip_support::detail::operator<<(out, v.isManaged); + std::operator<<(out, ", "); + } + if (std::string("hipPointerAttribute_t::device").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "device="); + roctracer::hip_support::detail::operator<<(out, v.device); + std::operator<<(out, ", "); + } + if (std::string("hipPointerAttribute_t::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipChannelFormatDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipChannelFormatDesc::f").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "f="); + roctracer::hip_support::detail::operator<<(out, v.f); + std::operator<<(out, ", "); + } + if (std::string("hipChannelFormatDesc::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("hipChannelFormatDesc::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("hipChannelFormatDesc::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("hipChannelFormatDesc::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const HIP_ARRAY_DESCRIPTOR& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("HIP_ARRAY_DESCRIPTOR::NumChannels").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "NumChannels="); + roctracer::hip_support::detail::operator<<(out, v.NumChannels); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY_DESCRIPTOR::Format").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Format="); + roctracer::hip_support::detail::operator<<(out, v.Format); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY_DESCRIPTOR::Height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Height="); + roctracer::hip_support::detail::operator<<(out, v.Height); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY_DESCRIPTOR::Width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Width="); + roctracer::hip_support::detail::operator<<(out, v.Width); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const HIP_ARRAY3D_DESCRIPTOR& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("HIP_ARRAY3D_DESCRIPTOR::Flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Flags="); + roctracer::hip_support::detail::operator<<(out, v.Flags); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY3D_DESCRIPTOR::NumChannels").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "NumChannels="); + roctracer::hip_support::detail::operator<<(out, v.NumChannels); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY3D_DESCRIPTOR::Format").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Format="); + roctracer::hip_support::detail::operator<<(out, v.Format); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY3D_DESCRIPTOR::Depth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Depth="); + roctracer::hip_support::detail::operator<<(out, v.Depth); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY3D_DESCRIPTOR::Height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Height="); + roctracer::hip_support::detail::operator<<(out, v.Height); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY3D_DESCRIPTOR::Width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Width="); + roctracer::hip_support::detail::operator<<(out, v.Width); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hip_Memcpy2D& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hip_Memcpy2D::Height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Height="); + roctracer::hip_support::detail::operator<<(out, v.Height); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::WidthInBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "WidthInBytes="); + roctracer::hip_support::detail::operator<<(out, v.WidthInBytes); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::dstPitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstPitch="); + roctracer::hip_support::detail::operator<<(out, v.dstPitch); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::dstArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstArray="); + roctracer::hip_support::detail::operator<<(out, v.dstArray); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::dstDevice").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstDevice="); + roctracer::hip_support::detail::operator<<(out, v.dstDevice); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::dstMemoryType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstMemoryType="); + roctracer::hip_support::detail::operator<<(out, v.dstMemoryType); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::dstY").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstY="); + roctracer::hip_support::detail::operator<<(out, v.dstY); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::dstXInBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstXInBytes="); + roctracer::hip_support::detail::operator<<(out, v.dstXInBytes); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::srcPitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcPitch="); + roctracer::hip_support::detail::operator<<(out, v.srcPitch); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::srcArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcArray="); + roctracer::hip_support::detail::operator<<(out, v.srcArray); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::srcDevice").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcDevice="); + roctracer::hip_support::detail::operator<<(out, v.srcDevice); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::srcMemoryType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcMemoryType="); + roctracer::hip_support::detail::operator<<(out, v.srcMemoryType); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::srcY").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcY="); + roctracer::hip_support::detail::operator<<(out, v.srcY); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::srcXInBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcXInBytes="); + roctracer::hip_support::detail::operator<<(out, v.srcXInBytes); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMipmappedArray& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMipmappedArray::num_channels").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "num_channels="); + roctracer::hip_support::detail::operator<<(out, v.num_channels); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::format").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "format="); + roctracer::hip_support::detail::operator<<(out, v.format); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::max_mipmap_level").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "max_mipmap_level="); + roctracer::hip_support::detail::operator<<(out, v.max_mipmap_level); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::min_mipmap_level").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "min_mipmap_level="); + roctracer::hip_support::detail::operator<<(out, v.min_mipmap_level); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::depth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "depth="); + roctracer::hip_support::detail::operator<<(out, v.depth); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "height="); + roctracer::hip_support::detail::operator<<(out, v.height); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "width="); + roctracer::hip_support::detail::operator<<(out, v.width); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::desc").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "desc="); + roctracer::hip_support::detail::operator<<(out, v.desc); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const HIP_TEXTURE_DESC& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("HIP_TEXTURE_DESC::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::borderColor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "borderColor="); + roctracer::hip_support::detail::operator<<(out, v.borderColor); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::maxMipmapLevelClamp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxMipmapLevelClamp="); + roctracer::hip_support::detail::operator<<(out, v.maxMipmapLevelClamp); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::minMipmapLevelClamp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "minMipmapLevelClamp="); + roctracer::hip_support::detail::operator<<(out, v.minMipmapLevelClamp); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::mipmapLevelBias").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "mipmapLevelBias="); + roctracer::hip_support::detail::operator<<(out, v.mipmapLevelBias); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::mipmapFilterMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "mipmapFilterMode="); + roctracer::hip_support::detail::operator<<(out, v.mipmapFilterMode); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::maxAnisotropy").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxAnisotropy="); + roctracer::hip_support::detail::operator<<(out, v.maxAnisotropy); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::filterMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "filterMode="); + roctracer::hip_support::detail::operator<<(out, v.filterMode); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::addressMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "addressMode="); + roctracer::hip_support::detail::operator<<(out, v.addressMode); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipResourceDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipResourceDesc::resType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "resType="); + roctracer::hip_support::detail::operator<<(out, v.resType); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const HIP_RESOURCE_DESC& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("HIP_RESOURCE_DESC::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_DESC::resType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "resType="); + roctracer::hip_support::detail::operator<<(out, v.resType); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipResourceViewDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipResourceViewDesc::lastLayer").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "lastLayer="); + roctracer::hip_support::detail::operator<<(out, v.lastLayer); + std::operator<<(out, ", "); + } + if (std::string("hipResourceViewDesc::firstLayer").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "firstLayer="); + roctracer::hip_support::detail::operator<<(out, v.firstLayer); + std::operator<<(out, ", "); + } + if (std::string("hipResourceViewDesc::lastMipmapLevel").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "lastMipmapLevel="); + roctracer::hip_support::detail::operator<<(out, v.lastMipmapLevel); + std::operator<<(out, ", "); + } + if (std::string("hipResourceViewDesc::firstMipmapLevel").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "firstMipmapLevel="); + roctracer::hip_support::detail::operator<<(out, v.firstMipmapLevel); + std::operator<<(out, ", "); + } + if (std::string("hipResourceViewDesc::depth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "depth="); + roctracer::hip_support::detail::operator<<(out, v.depth); + std::operator<<(out, ", "); + } + if (std::string("hipResourceViewDesc::height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "height="); + roctracer::hip_support::detail::operator<<(out, v.height); + std::operator<<(out, ", "); + } + if (std::string("hipResourceViewDesc::width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "width="); + roctracer::hip_support::detail::operator<<(out, v.width); + std::operator<<(out, ", "); + } + if (std::string("hipResourceViewDesc::format").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "format="); + roctracer::hip_support::detail::operator<<(out, v.format); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const HIP_RESOURCE_VIEW_DESC& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("HIP_RESOURCE_VIEW_DESC::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::lastLayer").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "lastLayer="); + roctracer::hip_support::detail::operator<<(out, v.lastLayer); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::firstLayer").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "firstLayer="); + roctracer::hip_support::detail::operator<<(out, v.firstLayer); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::lastMipmapLevel").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "lastMipmapLevel="); + roctracer::hip_support::detail::operator<<(out, v.lastMipmapLevel); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::firstMipmapLevel").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "firstMipmapLevel="); + roctracer::hip_support::detail::operator<<(out, v.firstMipmapLevel); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::depth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "depth="); + roctracer::hip_support::detail::operator<<(out, v.depth); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "height="); + roctracer::hip_support::detail::operator<<(out, v.height); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "width="); + roctracer::hip_support::detail::operator<<(out, v.width); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::format").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "format="); + roctracer::hip_support::detail::operator<<(out, v.format); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipPitchedPtr& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipPitchedPtr::ysize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "ysize="); + roctracer::hip_support::detail::operator<<(out, v.ysize); + std::operator<<(out, ", "); + } + if (std::string("hipPitchedPtr::xsize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "xsize="); + roctracer::hip_support::detail::operator<<(out, v.xsize); + std::operator<<(out, ", "); + } + if (std::string("hipPitchedPtr::pitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pitch="); + roctracer::hip_support::detail::operator<<(out, v.pitch); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExtent& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExtent::depth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "depth="); + roctracer::hip_support::detail::operator<<(out, v.depth); + std::operator<<(out, ", "); + } + if (std::string("hipExtent::height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "height="); + roctracer::hip_support::detail::operator<<(out, v.height); + std::operator<<(out, ", "); + } + if (std::string("hipExtent::width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "width="); + roctracer::hip_support::detail::operator<<(out, v.width); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipPos& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipPos::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("hipPos::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("hipPos::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemcpy3DParms& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemcpy3DParms::kind").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "kind="); + roctracer::hip_support::detail::operator<<(out, v.kind); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpy3DParms::extent").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "extent="); + roctracer::hip_support::detail::operator<<(out, v.extent); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpy3DParms::dstPtr").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstPtr="); + roctracer::hip_support::detail::operator<<(out, v.dstPtr); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpy3DParms::dstPos").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstPos="); + roctracer::hip_support::detail::operator<<(out, v.dstPos); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpy3DParms::dstArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstArray="); + roctracer::hip_support::detail::operator<<(out, v.dstArray); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpy3DParms::srcPtr").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcPtr="); + roctracer::hip_support::detail::operator<<(out, v.srcPtr); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpy3DParms::srcPos").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcPos="); + roctracer::hip_support::detail::operator<<(out, v.srcPos); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpy3DParms::srcArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcArray="); + roctracer::hip_support::detail::operator<<(out, v.srcArray); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const HIP_MEMCPY3D& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("HIP_MEMCPY3D::Depth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Depth="); + roctracer::hip_support::detail::operator<<(out, v.Depth); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::Height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Height="); + roctracer::hip_support::detail::operator<<(out, v.Height); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::WidthInBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "WidthInBytes="); + roctracer::hip_support::detail::operator<<(out, v.WidthInBytes); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstHeight").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstHeight="); + roctracer::hip_support::detail::operator<<(out, v.dstHeight); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstPitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstPitch="); + roctracer::hip_support::detail::operator<<(out, v.dstPitch); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstArray="); + roctracer::hip_support::detail::operator<<(out, v.dstArray); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstDevice").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstDevice="); + roctracer::hip_support::detail::operator<<(out, v.dstDevice); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstMemoryType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstMemoryType="); + roctracer::hip_support::detail::operator<<(out, v.dstMemoryType); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstLOD").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstLOD="); + roctracer::hip_support::detail::operator<<(out, v.dstLOD); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstZ").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstZ="); + roctracer::hip_support::detail::operator<<(out, v.dstZ); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstY").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstY="); + roctracer::hip_support::detail::operator<<(out, v.dstY); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstXInBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstXInBytes="); + roctracer::hip_support::detail::operator<<(out, v.dstXInBytes); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcHeight").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcHeight="); + roctracer::hip_support::detail::operator<<(out, v.srcHeight); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcPitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcPitch="); + roctracer::hip_support::detail::operator<<(out, v.srcPitch); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcArray="); + roctracer::hip_support::detail::operator<<(out, v.srcArray); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcDevice").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcDevice="); + roctracer::hip_support::detail::operator<<(out, v.srcDevice); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcMemoryType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcMemoryType="); + roctracer::hip_support::detail::operator<<(out, v.srcMemoryType); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcLOD").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcLOD="); + roctracer::hip_support::detail::operator<<(out, v.srcLOD); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcZ").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcZ="); + roctracer::hip_support::detail::operator<<(out, v.srcZ); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcY").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcY="); + roctracer::hip_support::detail::operator<<(out, v.srcY); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcXInBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcXInBytes="); + roctracer::hip_support::detail::operator<<(out, v.srcXInBytes); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uchar1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uchar1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uchar2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uchar2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("uchar2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uchar3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uchar3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("uchar3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("uchar3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uchar4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uchar4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("uchar4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("uchar4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("uchar4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const char1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("char1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const char2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("char2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("char2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const char3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("char3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("char3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("char3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const char4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("char4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("char4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("char4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("char4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ushort1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ushort1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ushort2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ushort2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ushort2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ushort3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ushort3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("ushort3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ushort3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ushort4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ushort4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("ushort4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("ushort4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ushort4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const short1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("short1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const short2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("short2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("short2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const short3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("short3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("short3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("short3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const short4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("short4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("short4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("short4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("short4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uint1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uint1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uint2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uint2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("uint2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uint3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uint3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("uint3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("uint3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uint4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uint4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("uint4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("uint4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("uint4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const int1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("int1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const int2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("int2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("int2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const int3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("int3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("int3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("int3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const int4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("int4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("int4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("int4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("int4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulong1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulong1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulong2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulong2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ulong2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulong3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulong3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("ulong3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ulong3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulong4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulong4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("ulong4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("ulong4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ulong4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const long1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("long1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const long2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("long2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("long2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const long3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("long3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("long3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("long3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const long4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("long4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("long4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("long4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("long4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulonglong1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulonglong1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulonglong2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulonglong2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ulonglong2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulonglong3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulonglong3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("ulonglong3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ulonglong3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulonglong4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulonglong4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("ulonglong4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("ulonglong4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ulonglong4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const longlong1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("longlong1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const longlong2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("longlong2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("longlong2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const longlong3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("longlong3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("longlong3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("longlong3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const longlong4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("longlong4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("longlong4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("longlong4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("longlong4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const float1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("float1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const float2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("float2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("float2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const float3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("float3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("float3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("float3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const float4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("float4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("float4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("float4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("float4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const double1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("double1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const double2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("double2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("double2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const double3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("double3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("double3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("double3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const double4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("double4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("double4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("double4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("double4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const textureReference& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("textureReference::format").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "format="); + roctracer::hip_support::detail::operator<<(out, v.format); + std::operator<<(out, ", "); + } + if (std::string("textureReference::numChannels").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "numChannels="); + roctracer::hip_support::detail::operator<<(out, v.numChannels); + std::operator<<(out, ", "); + } + if (std::string("textureReference::textureObject").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "textureObject="); + roctracer::hip_support::detail::operator<<(out, v.textureObject); + std::operator<<(out, ", "); + } + if (std::string("textureReference::maxMipmapLevelClamp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxMipmapLevelClamp="); + roctracer::hip_support::detail::operator<<(out, v.maxMipmapLevelClamp); + std::operator<<(out, ", "); + } + if (std::string("textureReference::minMipmapLevelClamp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "minMipmapLevelClamp="); + roctracer::hip_support::detail::operator<<(out, v.minMipmapLevelClamp); + std::operator<<(out, ", "); + } + if (std::string("textureReference::mipmapLevelBias").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "mipmapLevelBias="); + roctracer::hip_support::detail::operator<<(out, v.mipmapLevelBias); + std::operator<<(out, ", "); + } + if (std::string("textureReference::mipmapFilterMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "mipmapFilterMode="); + roctracer::hip_support::detail::operator<<(out, v.mipmapFilterMode); + std::operator<<(out, ", "); + } + if (std::string("textureReference::maxAnisotropy").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxAnisotropy="); + roctracer::hip_support::detail::operator<<(out, v.maxAnisotropy); + std::operator<<(out, ", "); + } + if (std::string("textureReference::sRGB").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sRGB="); + roctracer::hip_support::detail::operator<<(out, v.sRGB); + std::operator<<(out, ", "); + } + if (std::string("textureReference::channelDesc").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "channelDesc="); + roctracer::hip_support::detail::operator<<(out, v.channelDesc); + std::operator<<(out, ", "); + } + if (std::string("textureReference::filterMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "filterMode="); + roctracer::hip_support::detail::operator<<(out, v.filterMode); + std::operator<<(out, ", "); + } + if (std::string("textureReference::readMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "readMode="); + roctracer::hip_support::detail::operator<<(out, v.readMode); + std::operator<<(out, ", "); + } + if (std::string("textureReference::normalized").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "normalized="); + roctracer::hip_support::detail::operator<<(out, v.normalized); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipTextureDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipTextureDesc::maxMipmapLevelClamp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxMipmapLevelClamp="); + roctracer::hip_support::detail::operator<<(out, v.maxMipmapLevelClamp); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::minMipmapLevelClamp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "minMipmapLevelClamp="); + roctracer::hip_support::detail::operator<<(out, v.minMipmapLevelClamp); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::mipmapLevelBias").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "mipmapLevelBias="); + roctracer::hip_support::detail::operator<<(out, v.mipmapLevelBias); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::mipmapFilterMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "mipmapFilterMode="); + roctracer::hip_support::detail::operator<<(out, v.mipmapFilterMode); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::maxAnisotropy").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxAnisotropy="); + roctracer::hip_support::detail::operator<<(out, v.maxAnisotropy); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::normalizedCoords").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "normalizedCoords="); + roctracer::hip_support::detail::operator<<(out, v.normalizedCoords); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::borderColor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "borderColor="); + roctracer::hip_support::detail::operator<<(out, v.borderColor); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::sRGB").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sRGB="); + roctracer::hip_support::detail::operator<<(out, v.sRGB); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::readMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "readMode="); + roctracer::hip_support::detail::operator<<(out, v.readMode); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::filterMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "filterMode="); + roctracer::hip_support::detail::operator<<(out, v.filterMode); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const surfaceReference& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("surfaceReference::surfaceObject").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "surfaceObject="); + roctracer::hip_support::detail::operator<<(out, v.surfaceObject); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipIpcMemHandle_t& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipIpcMemHandle_t::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipIpcEventHandle_t& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipIpcEventHandle_t::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipFuncAttributes& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipFuncAttributes::sharedSizeBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedSizeBytes="); + roctracer::hip_support::detail::operator<<(out, v.sharedSizeBytes); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::ptxVersion").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "ptxVersion="); + roctracer::hip_support::detail::operator<<(out, v.ptxVersion); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::preferredShmemCarveout").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "preferredShmemCarveout="); + roctracer::hip_support::detail::operator<<(out, v.preferredShmemCarveout); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::numRegs").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "numRegs="); + roctracer::hip_support::detail::operator<<(out, v.numRegs); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::maxThreadsPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxThreadsPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.maxThreadsPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::maxDynamicSharedSizeBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxDynamicSharedSizeBytes="); + roctracer::hip_support::detail::operator<<(out, v.maxDynamicSharedSizeBytes); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::localSizeBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "localSizeBytes="); + roctracer::hip_support::detail::operator<<(out, v.localSizeBytes); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::constSizeBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "constSizeBytes="); + roctracer::hip_support::detail::operator<<(out, v.constSizeBytes); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::cacheModeCA").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cacheModeCA="); + roctracer::hip_support::detail::operator<<(out, v.cacheModeCA); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::binaryVersion").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "binaryVersion="); + roctracer::hip_support::detail::operator<<(out, v.binaryVersion); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemLocation& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemLocation::id").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "id="); + roctracer::hip_support::detail::operator<<(out, v.id); + std::operator<<(out, ", "); + } + if (std::string("hipMemLocation::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemAccessDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemAccessDesc::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipMemAccessDesc::location").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "location="); + roctracer::hip_support::detail::operator<<(out, v.location); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemPoolProps& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemPoolProps::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipMemPoolProps::maxSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSize="); + roctracer::hip_support::detail::operator<<(out, v.maxSize); + std::operator<<(out, ", "); + } + if (std::string("hipMemPoolProps::location").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "location="); + roctracer::hip_support::detail::operator<<(out, v.location); + std::operator<<(out, ", "); + } + if (std::string("hipMemPoolProps::handleTypes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "handleTypes="); + roctracer::hip_support::detail::operator<<(out, v.handleTypes); + std::operator<<(out, ", "); + } + if (std::string("hipMemPoolProps::allocType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "allocType="); + roctracer::hip_support::detail::operator<<(out, v.allocType); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemPoolPtrExportData& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemPoolPtrExportData::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const dim3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("dim3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("dim3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("dim3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipLaunchParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipLaunchParams::stream").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "stream="); + roctracer::hip_support::detail::operator<<(out, v.stream); + std::operator<<(out, ", "); + } + if (std::string("hipLaunchParams::sharedMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedMem="); + roctracer::hip_support::detail::operator<<(out, v.sharedMem); + std::operator<<(out, ", "); + } + if (std::string("hipLaunchParams::blockDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "blockDim="); + roctracer::hip_support::detail::operator<<(out, v.blockDim); + std::operator<<(out, ", "); + } + if (std::string("hipLaunchParams::gridDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gridDim="); + roctracer::hip_support::detail::operator<<(out, v.gridDim); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipFunctionLaunchParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipFunctionLaunchParams::hStream").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hStream="); + roctracer::hip_support::detail::operator<<(out, v.hStream); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::sharedMemBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedMemBytes="); + roctracer::hip_support::detail::operator<<(out, v.sharedMemBytes); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::blockDimZ").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "blockDimZ="); + roctracer::hip_support::detail::operator<<(out, v.blockDimZ); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::blockDimY").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "blockDimY="); + roctracer::hip_support::detail::operator<<(out, v.blockDimY); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::blockDimX").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "blockDimX="); + roctracer::hip_support::detail::operator<<(out, v.blockDimX); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::gridDimZ").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gridDimZ="); + roctracer::hip_support::detail::operator<<(out, v.gridDimZ); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::gridDimY").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gridDimY="); + roctracer::hip_support::detail::operator<<(out, v.gridDimY); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::gridDimX").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gridDimX="); + roctracer::hip_support::detail::operator<<(out, v.gridDimX); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::function").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "function="); + roctracer::hip_support::detail::operator<<(out, v.function); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalMemoryHandleDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalMemoryHandleDesc::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryHandleDesc::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryHandleDesc::size").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "size="); + roctracer::hip_support::detail::operator<<(out, v.size); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryHandleDesc_st::union ::handle.fd").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "handle.fd="); + roctracer::hip_support::detail::operator<<(out, v.handle.fd); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryHandleDesc::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalMemoryBufferDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalMemoryBufferDesc::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryBufferDesc::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryBufferDesc::size").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "size="); + roctracer::hip_support::detail::operator<<(out, v.size); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryBufferDesc::offset").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "offset="); + roctracer::hip_support::detail::operator<<(out, v.offset); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalMemoryMipmappedArrayDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalMemoryMipmappedArrayDesc::numLevels").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "numLevels="); + roctracer::hip_support::detail::operator<<(out, v.numLevels); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryMipmappedArrayDesc::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryMipmappedArrayDesc::extent").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "extent="); + roctracer::hip_support::detail::operator<<(out, v.extent); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryMipmappedArrayDesc::formatDesc").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "formatDesc="); + roctracer::hip_support::detail::operator<<(out, v.formatDesc); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryMipmappedArrayDesc::offset").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "offset="); + roctracer::hip_support::detail::operator<<(out, v.offset); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreHandleDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalSemaphoreHandleDesc::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreHandleDesc::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreHandleDesc_st::union ::handle.fd").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "handle.fd="); + roctracer::hip_support::detail::operator<<(out, v.handle.fd); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreHandleDesc::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreSignalParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalSemaphoreSignalParams::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreSignalParams::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreWaitParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalSemaphoreWaitParams::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreWaitParams::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipHostNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipHostNodeParams::fn").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "fn="); + roctracer::hip_support::detail::operator<<(out, v.fn); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipKernelNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipKernelNodeParams::sharedMemBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedMemBytes="); + roctracer::hip_support::detail::operator<<(out, v.sharedMemBytes); + std::operator<<(out, ", "); + } + if (std::string("hipKernelNodeParams::gridDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gridDim="); + roctracer::hip_support::detail::operator<<(out, v.gridDim); + std::operator<<(out, ", "); + } + if (std::string("hipKernelNodeParams::blockDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "blockDim="); + roctracer::hip_support::detail::operator<<(out, v.blockDim); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemsetParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemsetParams::width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "width="); + roctracer::hip_support::detail::operator<<(out, v.width); + std::operator<<(out, ", "); + } + if (std::string("hipMemsetParams::value").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "value="); + roctracer::hip_support::detail::operator<<(out, v.value); + std::operator<<(out, ", "); + } + if (std::string("hipMemsetParams::pitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pitch="); + roctracer::hip_support::detail::operator<<(out, v.pitch); + std::operator<<(out, ", "); + } + if (std::string("hipMemsetParams::height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "height="); + roctracer::hip_support::detail::operator<<(out, v.height); + std::operator<<(out, ", "); + } + if (std::string("hipMemsetParams::elementSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "elementSize="); + roctracer::hip_support::detail::operator<<(out, v.elementSize); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemAllocNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemAllocNodeParams::bytesize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "bytesize="); + roctracer::hip_support::detail::operator<<(out, v.bytesize); + std::operator<<(out, ", "); + } + if (std::string("hipMemAllocNodeParams::accessDescCount").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "accessDescCount="); + roctracer::hip_support::detail::operator<<(out, v.accessDescCount); + std::operator<<(out, ", "); + } + if (std::string("hipMemAllocNodeParams::accessDescs").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "accessDescs="); + roctracer::hip_support::detail::operator<<(out, v.accessDescs); + std::operator<<(out, ", "); + } + if (std::string("hipMemAllocNodeParams::poolProps").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "poolProps="); + roctracer::hip_support::detail::operator<<(out, v.poolProps); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipAccessPolicyWindow& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipAccessPolicyWindow::num_bytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "num_bytes="); + roctracer::hip_support::detail::operator<<(out, v.num_bytes); + std::operator<<(out, ", "); + } + if (std::string("hipAccessPolicyWindow::missProp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "missProp="); + roctracer::hip_support::detail::operator<<(out, v.missProp); + std::operator<<(out, ", "); + } + if (std::string("hipAccessPolicyWindow::hitRatio").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hitRatio="); + roctracer::hip_support::detail::operator<<(out, v.hitRatio); + std::operator<<(out, ", "); + } + if (std::string("hipAccessPolicyWindow::hitProp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hitProp="); + roctracer::hip_support::detail::operator<<(out, v.hitProp); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipLaunchAttributeValue& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipLaunchAttributeValue::priority").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "priority="); + roctracer::hip_support::detail::operator<<(out, v.priority); + std::operator<<(out, ", "); + } + if (std::string("hipLaunchAttributeValue::cooperative").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperative="); + roctracer::hip_support::detail::operator<<(out, v.cooperative); + std::operator<<(out, ", "); + } + if (std::string("hipLaunchAttributeValue::accessPolicyWindow").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "accessPolicyWindow="); + roctracer::hip_support::detail::operator<<(out, v.accessPolicyWindow); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const HIP_MEMSET_NODE_PARAMS& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("HIP_MEMSET_NODE_PARAMS::height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "height="); + roctracer::hip_support::detail::operator<<(out, v.height); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMSET_NODE_PARAMS::width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "width="); + roctracer::hip_support::detail::operator<<(out, v.width); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMSET_NODE_PARAMS::elementSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "elementSize="); + roctracer::hip_support::detail::operator<<(out, v.elementSize); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMSET_NODE_PARAMS::value").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "value="); + roctracer::hip_support::detail::operator<<(out, v.value); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMSET_NODE_PARAMS::pitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pitch="); + roctracer::hip_support::detail::operator<<(out, v.pitch); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMSET_NODE_PARAMS::dst").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dst="); + roctracer::hip_support::detail::operator<<(out, v.dst); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipGraphInstantiateParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipGraphInstantiateParams::uploadStream").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "uploadStream="); + roctracer::hip_support::detail::operator<<(out, v.uploadStream); + std::operator<<(out, ", "); + } + if (std::string("hipGraphInstantiateParams::result_out").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "result_out="); + roctracer::hip_support::detail::operator<<(out, v.result_out); + std::operator<<(out, ", "); + } + if (std::string("hipGraphInstantiateParams::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipGraphInstantiateParams::errNode_out").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "errNode_out="); + roctracer::hip_support::detail::operator<<(out, v.errNode_out); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemAllocationProp& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemAllocationProp::location").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "location="); + roctracer::hip_support::detail::operator<<(out, v.location); + std::operator<<(out, ", "); + } + if (std::string("hipMemAllocationProp::requestedHandleType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "requestedHandleType="); + roctracer::hip_support::detail::operator<<(out, v.requestedHandleType); + std::operator<<(out, ", "); + } + if (std::string("hipMemAllocationProp::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreSignalNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalSemaphoreSignalNodeParams::numExtSems").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "numExtSems="); + roctracer::hip_support::detail::operator<<(out, v.numExtSems); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreSignalNodeParams::paramsArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "paramsArray="); + roctracer::hip_support::detail::operator<<(out, v.paramsArray); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreSignalNodeParams::extSemArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "extSemArray="); + roctracer::hip_support::detail::operator<<(out, v.extSemArray); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreWaitNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalSemaphoreWaitNodeParams::numExtSems").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "numExtSems="); + roctracer::hip_support::detail::operator<<(out, v.numExtSems); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreWaitNodeParams::paramsArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "paramsArray="); + roctracer::hip_support::detail::operator<<(out, v.paramsArray); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreWaitNodeParams::extSemArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "extSemArray="); + roctracer::hip_support::detail::operator<<(out, v.extSemArray); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipArrayMapInfo& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipArrayMapInfo::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::deviceBitMask").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "deviceBitMask="); + roctracer::hip_support::detail::operator<<(out, v.deviceBitMask); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::offset").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "offset="); + roctracer::hip_support::detail::operator<<(out, v.offset); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::union ::memHandle.memHandle").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memHandle.memHandle="); + roctracer::hip_support::detail::operator<<(out, v.memHandle.memHandle); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::memHandleType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memHandleType="); + roctracer::hip_support::detail::operator<<(out, v.memHandleType); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::memOperationType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memOperationType="); + roctracer::hip_support::detail::operator<<(out, v.memOperationType); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::subresourceType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "subresourceType="); + roctracer::hip_support::detail::operator<<(out, v.subresourceType); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::resourceType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "resourceType="); + roctracer::hip_support::detail::operator<<(out, v.resourceType); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemcpyNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemcpyNodeParams::copyParams").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "copyParams="); + roctracer::hip_support::detail::operator<<(out, v.copyParams); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpyNodeParams::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpyNodeParams::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipChildGraphNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipChildGraphNodeParams::graph").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "graph="); + roctracer::hip_support::detail::operator<<(out, v.graph); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipEventWaitNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipEventWaitNodeParams::event").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "event="); + roctracer::hip_support::detail::operator<<(out, v.event); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipEventRecordNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipEventRecordNodeParams::event").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "event="); + roctracer::hip_support::detail::operator<<(out, v.event); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemFreeNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipGraphNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipGraphNodeParams::reserved2").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved2="); + roctracer::hip_support::detail::operator<<(out, v.reserved2); + std::operator<<(out, ", "); + } + if (std::string("hipGraphNodeParams::reserved0").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved0="); + roctracer::hip_support::detail::operator<<(out, v.reserved0); + std::operator<<(out, ", "); + } + if (std::string("hipGraphNodeParams::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipGraphEdgeData& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipGraphEdgeData::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + std::operator<<(out, ", "); + } + if (std::string("hipGraphEdgeData::to_port").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "to_port="); + roctracer::hip_support::detail::operator<<(out, v.to_port); + std::operator<<(out, ", "); + } + if (std::string("hipGraphEdgeData::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipGraphEdgeData::from_port").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "from_port="); + roctracer::hip_support::detail::operator<<(out, v.from_port); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipDeviceProp_tR0000& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipDeviceProp_tR0000::pageableMemoryAccessUsesHostPageTables").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pageableMemoryAccessUsesHostPageTables="); + roctracer::hip_support::detail::operator<<(out, v.pageableMemoryAccessUsesHostPageTables); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::pageableMemoryAccess").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pageableMemoryAccess="); + roctracer::hip_support::detail::operator<<(out, v.pageableMemoryAccess); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::concurrentManagedAccess").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "concurrentManagedAccess="); + roctracer::hip_support::detail::operator<<(out, v.concurrentManagedAccess); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::directManagedMemAccessFromHost").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "directManagedMemAccessFromHost="); + roctracer::hip_support::detail::operator<<(out, v.directManagedMemAccessFromHost); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::managedMemory").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "managedMemory="); + roctracer::hip_support::detail::operator<<(out, v.managedMemory); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::asicRevision").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "asicRevision="); + roctracer::hip_support::detail::operator<<(out, v.asicRevision); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::isLargeBar").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "isLargeBar="); + roctracer::hip_support::detail::operator<<(out, v.isLargeBar); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::cooperativeMultiDeviceUnmatchedSharedMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedSharedMem="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedSharedMem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::cooperativeMultiDeviceUnmatchedBlockDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedBlockDim="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedBlockDim); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::cooperativeMultiDeviceUnmatchedGridDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedGridDim="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedGridDim); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::cooperativeMultiDeviceUnmatchedFunc").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedFunc="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedFunc); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::tccDriver").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "tccDriver="); + roctracer::hip_support::detail::operator<<(out, v.tccDriver); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::ECCEnabled").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "ECCEnabled="); + roctracer::hip_support::detail::operator<<(out, v.ECCEnabled); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::kernelExecTimeoutEnabled").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "kernelExecTimeoutEnabled="); + roctracer::hip_support::detail::operator<<(out, v.kernelExecTimeoutEnabled); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::texturePitchAlignment").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "texturePitchAlignment="); + roctracer::hip_support::detail::operator<<(out, v.texturePitchAlignment); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::textureAlignment").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "textureAlignment="); + roctracer::hip_support::detail::operator<<(out, v.textureAlignment); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::memPitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memPitch="); + roctracer::hip_support::detail::operator<<(out, v.memPitch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::hdpRegFlushCntl").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hdpRegFlushCntl="); + roctracer::hip_support::detail::operator<<(out, v.hdpRegFlushCntl); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::hdpMemFlushCntl").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hdpMemFlushCntl="); + roctracer::hip_support::detail::operator<<(out, v.hdpMemFlushCntl); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxTexture3D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture3D="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture3D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxTexture2D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture2D="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture2D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxTexture1D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture1D="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture1D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxTexture1DLinear").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture1DLinear="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture1DLinear); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::cooperativeMultiDeviceLaunch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceLaunch="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceLaunch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::cooperativeLaunch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeLaunch="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeLaunch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::integrated").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "integrated="); + roctracer::hip_support::detail::operator<<(out, v.integrated); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::gcnArchName").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gcnArchName="); + roctracer::hip_support::detail::operator<<(out, v.gcnArchName); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::gcnArch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gcnArch="); + roctracer::hip_support::detail::operator<<(out, v.gcnArch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::canMapHostMemory").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "canMapHostMemory="); + roctracer::hip_support::detail::operator<<(out, v.canMapHostMemory); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::isMultiGpuBoard").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "isMultiGpuBoard="); + roctracer::hip_support::detail::operator<<(out, v.isMultiGpuBoard); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxSharedMemoryPerMultiProcessor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSharedMemoryPerMultiProcessor="); + roctracer::hip_support::detail::operator<<(out, v.maxSharedMemoryPerMultiProcessor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::pciDeviceID").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pciDeviceID="); + roctracer::hip_support::detail::operator<<(out, v.pciDeviceID); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::pciBusID").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pciBusID="); + roctracer::hip_support::detail::operator<<(out, v.pciBusID); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::pciDomainID").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pciDomainID="); + roctracer::hip_support::detail::operator<<(out, v.pciDomainID); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::concurrentKernels").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "concurrentKernels="); + roctracer::hip_support::detail::operator<<(out, v.concurrentKernels); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::arch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "arch="); + roctracer::hip_support::detail::operator<<(out, v.arch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::clockInstructionRate").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "clockInstructionRate="); + roctracer::hip_support::detail::operator<<(out, v.clockInstructionRate); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::computeMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "computeMode="); + roctracer::hip_support::detail::operator<<(out, v.computeMode); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxThreadsPerMultiProcessor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxThreadsPerMultiProcessor="); + roctracer::hip_support::detail::operator<<(out, v.maxThreadsPerMultiProcessor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::l2CacheSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "l2CacheSize="); + roctracer::hip_support::detail::operator<<(out, v.l2CacheSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::multiProcessorCount").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "multiProcessorCount="); + roctracer::hip_support::detail::operator<<(out, v.multiProcessorCount); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::minor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "minor="); + roctracer::hip_support::detail::operator<<(out, v.minor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::major").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "major="); + roctracer::hip_support::detail::operator<<(out, v.major); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::totalConstMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "totalConstMem="); + roctracer::hip_support::detail::operator<<(out, v.totalConstMem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::memoryBusWidth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memoryBusWidth="); + roctracer::hip_support::detail::operator<<(out, v.memoryBusWidth); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::memoryClockRate").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memoryClockRate="); + roctracer::hip_support::detail::operator<<(out, v.memoryClockRate); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::clockRate").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "clockRate="); + roctracer::hip_support::detail::operator<<(out, v.clockRate); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxGridSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxGridSize="); + roctracer::hip_support::detail::operator<<(out, v.maxGridSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxThreadsDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxThreadsDim="); + roctracer::hip_support::detail::operator<<(out, v.maxThreadsDim); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxThreadsPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxThreadsPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.maxThreadsPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::warpSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "warpSize="); + roctracer::hip_support::detail::operator<<(out, v.warpSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::regsPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "regsPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.regsPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::sharedMemPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedMemPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.sharedMemPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::totalGlobalMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "totalGlobalMem="); + roctracer::hip_support::detail::operator<<(out, v.totalGlobalMem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::name").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "name="); + roctracer::hip_support::detail::operator<<(out, v.name); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +// end ostream ops for HIP +};};}; + +inline static std::ostream& operator<<(std::ostream& out, const __locale_struct& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipDeviceArch_t& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipUUID& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipDeviceProp_tR0600& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipPointerAttribute_t& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipChannelFormatDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const HIP_ARRAY_DESCRIPTOR& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const HIP_ARRAY3D_DESCRIPTOR& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hip_Memcpy2D& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMipmappedArray& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const HIP_TEXTURE_DESC& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipResourceDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const HIP_RESOURCE_DESC& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipResourceViewDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const HIP_RESOURCE_VIEW_DESC& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipPitchedPtr& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExtent& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipPos& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemcpy3DParms& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const HIP_MEMCPY3D& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uchar1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uchar2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uchar3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uchar4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const char1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const char2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const char3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const char4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ushort1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ushort2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ushort3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ushort4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const short1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const short2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const short3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const short4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uint1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uint2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uint3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uint4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const int1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const int2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const int3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const int4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulong1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulong2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulong3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulong4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const long1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const long2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const long3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const long4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulonglong1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulonglong2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulonglong3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulonglong4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const longlong1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const longlong2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const longlong3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const longlong4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const float1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const float2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const float3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const float4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const double1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const double2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const double3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const double4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const textureReference& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipTextureDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const surfaceReference& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipIpcMemHandle_t& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipIpcEventHandle_t& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipFuncAttributes& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemLocation& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemAccessDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemPoolProps& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemPoolPtrExportData& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const dim3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipLaunchParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipFunctionLaunchParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalMemoryHandleDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalMemoryBufferDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalMemoryMipmappedArrayDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreHandleDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreSignalParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreWaitParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipHostNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipKernelNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemsetParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemAllocNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipAccessPolicyWindow& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipLaunchAttributeValue& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const HIP_MEMSET_NODE_PARAMS& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipGraphInstantiateParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemAllocationProp& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreSignalNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreWaitNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipArrayMapInfo& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemcpyNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipChildGraphNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipEventWaitNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipEventRecordNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemFreeNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipGraphNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipGraphEdgeData& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipDeviceProp_tR0000& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +#endif //__cplusplus +#endif // INC_HIP_OSTREAM_OPS_H_ + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/roctracer/hsa_prof_str.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/roctracer/hsa_prof_str.h new file mode 100644 index 0000000000000000000000000000000000000000..3747659f7924fb113db7f35fa19825711b6b50f0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/roctracer/hsa_prof_str.h @@ -0,0 +1,3059 @@ +/* Generated by hsaap.py */ +/* Copyright (c) 2018-2022 Advanced Micro Devices, Inc. + + 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. */ + + +/* HSA API tracing primitives + 'CoreApi', header 'hsa.h', 125 funcs + 'AmdExt', header 'hsa_ext_amd.h', 70 funcs + 'ImageExt', header 'hsa_ext_image.h', 13 funcs + 'AmdExt', header 'hsa_api_trace.h', 70 funcs + */ + +#ifndef HSA_PROF_STR_H_ +#define HSA_PROF_STR_H_ + +/* section: API ID enumeration */ + +enum hsa_api_id_t { + /* block: CoreApi API */ + HSA_API_ID_hsa_init = 0, + HSA_API_ID_hsa_shut_down = 1, + HSA_API_ID_hsa_system_get_info = 2, + HSA_API_ID_hsa_system_extension_supported = 3, + HSA_API_ID_hsa_system_get_extension_table = 4, + HSA_API_ID_hsa_iterate_agents = 5, + HSA_API_ID_hsa_agent_get_info = 6, + HSA_API_ID_hsa_queue_create = 7, + HSA_API_ID_hsa_soft_queue_create = 8, + HSA_API_ID_hsa_queue_destroy = 9, + HSA_API_ID_hsa_queue_inactivate = 10, + HSA_API_ID_hsa_queue_load_read_index_scacquire = 11, + HSA_API_ID_hsa_queue_load_read_index_relaxed = 12, + HSA_API_ID_hsa_queue_load_write_index_scacquire = 13, + HSA_API_ID_hsa_queue_load_write_index_relaxed = 14, + HSA_API_ID_hsa_queue_store_write_index_relaxed = 15, + HSA_API_ID_hsa_queue_store_write_index_screlease = 16, + HSA_API_ID_hsa_queue_cas_write_index_scacq_screl = 17, + HSA_API_ID_hsa_queue_cas_write_index_scacquire = 18, + HSA_API_ID_hsa_queue_cas_write_index_relaxed = 19, + HSA_API_ID_hsa_queue_cas_write_index_screlease = 20, + HSA_API_ID_hsa_queue_add_write_index_scacq_screl = 21, + HSA_API_ID_hsa_queue_add_write_index_scacquire = 22, + HSA_API_ID_hsa_queue_add_write_index_relaxed = 23, + HSA_API_ID_hsa_queue_add_write_index_screlease = 24, + HSA_API_ID_hsa_queue_store_read_index_relaxed = 25, + HSA_API_ID_hsa_queue_store_read_index_screlease = 26, + HSA_API_ID_hsa_agent_iterate_regions = 27, + HSA_API_ID_hsa_region_get_info = 28, + HSA_API_ID_hsa_agent_get_exception_policies = 29, + HSA_API_ID_hsa_agent_extension_supported = 30, + HSA_API_ID_hsa_memory_register = 31, + HSA_API_ID_hsa_memory_deregister = 32, + HSA_API_ID_hsa_memory_allocate = 33, + HSA_API_ID_hsa_memory_free = 34, + HSA_API_ID_hsa_memory_copy = 35, + HSA_API_ID_hsa_memory_assign_agent = 36, + HSA_API_ID_hsa_signal_create = 37, + HSA_API_ID_hsa_signal_destroy = 38, + HSA_API_ID_hsa_signal_load_relaxed = 39, + HSA_API_ID_hsa_signal_load_scacquire = 40, + HSA_API_ID_hsa_signal_store_relaxed = 41, + HSA_API_ID_hsa_signal_store_screlease = 42, + HSA_API_ID_hsa_signal_wait_relaxed = 43, + HSA_API_ID_hsa_signal_wait_scacquire = 44, + HSA_API_ID_hsa_signal_and_relaxed = 45, + HSA_API_ID_hsa_signal_and_scacquire = 46, + HSA_API_ID_hsa_signal_and_screlease = 47, + HSA_API_ID_hsa_signal_and_scacq_screl = 48, + HSA_API_ID_hsa_signal_or_relaxed = 49, + HSA_API_ID_hsa_signal_or_scacquire = 50, + HSA_API_ID_hsa_signal_or_screlease = 51, + HSA_API_ID_hsa_signal_or_scacq_screl = 52, + HSA_API_ID_hsa_signal_xor_relaxed = 53, + HSA_API_ID_hsa_signal_xor_scacquire = 54, + HSA_API_ID_hsa_signal_xor_screlease = 55, + HSA_API_ID_hsa_signal_xor_scacq_screl = 56, + HSA_API_ID_hsa_signal_exchange_relaxed = 57, + HSA_API_ID_hsa_signal_exchange_scacquire = 58, + HSA_API_ID_hsa_signal_exchange_screlease = 59, + HSA_API_ID_hsa_signal_exchange_scacq_screl = 60, + HSA_API_ID_hsa_signal_add_relaxed = 61, + HSA_API_ID_hsa_signal_add_scacquire = 62, + HSA_API_ID_hsa_signal_add_screlease = 63, + HSA_API_ID_hsa_signal_add_scacq_screl = 64, + HSA_API_ID_hsa_signal_subtract_relaxed = 65, + HSA_API_ID_hsa_signal_subtract_scacquire = 66, + HSA_API_ID_hsa_signal_subtract_screlease = 67, + HSA_API_ID_hsa_signal_subtract_scacq_screl = 68, + HSA_API_ID_hsa_signal_cas_relaxed = 69, + HSA_API_ID_hsa_signal_cas_scacquire = 70, + HSA_API_ID_hsa_signal_cas_screlease = 71, + HSA_API_ID_hsa_signal_cas_scacq_screl = 72, + HSA_API_ID_hsa_isa_from_name = 73, + HSA_API_ID_hsa_isa_get_info = 74, + HSA_API_ID_hsa_isa_compatible = 75, + HSA_API_ID_hsa_code_object_serialize = 76, + HSA_API_ID_hsa_code_object_deserialize = 77, + HSA_API_ID_hsa_code_object_destroy = 78, + HSA_API_ID_hsa_code_object_get_info = 79, + HSA_API_ID_hsa_code_object_get_symbol = 80, + HSA_API_ID_hsa_code_symbol_get_info = 81, + HSA_API_ID_hsa_code_object_iterate_symbols = 82, + HSA_API_ID_hsa_executable_create = 83, + HSA_API_ID_hsa_executable_destroy = 84, + HSA_API_ID_hsa_executable_load_code_object = 85, + HSA_API_ID_hsa_executable_freeze = 86, + HSA_API_ID_hsa_executable_get_info = 87, + HSA_API_ID_hsa_executable_global_variable_define = 88, + HSA_API_ID_hsa_executable_agent_global_variable_define = 89, + HSA_API_ID_hsa_executable_readonly_variable_define = 90, + HSA_API_ID_hsa_executable_validate = 91, + HSA_API_ID_hsa_executable_get_symbol = 92, + HSA_API_ID_hsa_executable_symbol_get_info = 93, + HSA_API_ID_hsa_executable_iterate_symbols = 94, + HSA_API_ID_hsa_status_string = 95, + HSA_API_ID_hsa_extension_get_name = 96, + HSA_API_ID_hsa_system_major_extension_supported = 97, + HSA_API_ID_hsa_system_get_major_extension_table = 98, + HSA_API_ID_hsa_agent_major_extension_supported = 99, + HSA_API_ID_hsa_cache_get_info = 100, + HSA_API_ID_hsa_agent_iterate_caches = 101, + HSA_API_ID_hsa_signal_silent_store_relaxed = 102, + HSA_API_ID_hsa_signal_silent_store_screlease = 103, + HSA_API_ID_hsa_signal_group_create = 104, + HSA_API_ID_hsa_signal_group_destroy = 105, + HSA_API_ID_hsa_signal_group_wait_any_scacquire = 106, + HSA_API_ID_hsa_signal_group_wait_any_relaxed = 107, + HSA_API_ID_hsa_agent_iterate_isas = 108, + HSA_API_ID_hsa_isa_get_info_alt = 109, + HSA_API_ID_hsa_isa_get_exception_policies = 110, + HSA_API_ID_hsa_isa_get_round_method = 111, + HSA_API_ID_hsa_wavefront_get_info = 112, + HSA_API_ID_hsa_isa_iterate_wavefronts = 113, + HSA_API_ID_hsa_code_object_get_symbol_from_name = 114, + HSA_API_ID_hsa_code_object_reader_create_from_file = 115, + HSA_API_ID_hsa_code_object_reader_create_from_memory = 116, + HSA_API_ID_hsa_code_object_reader_destroy = 117, + HSA_API_ID_hsa_executable_create_alt = 118, + HSA_API_ID_hsa_executable_load_program_code_object = 119, + HSA_API_ID_hsa_executable_load_agent_code_object = 120, + HSA_API_ID_hsa_executable_validate_alt = 121, + HSA_API_ID_hsa_executable_get_symbol_by_name = 122, + HSA_API_ID_hsa_executable_iterate_agent_symbols = 123, + HSA_API_ID_hsa_executable_iterate_program_symbols = 124, + + /* block: AmdExt API */ + HSA_API_ID_hsa_amd_coherency_get_type = 125, + HSA_API_ID_hsa_amd_coherency_set_type = 126, + HSA_API_ID_hsa_amd_profiling_set_profiler_enabled = 127, + HSA_API_ID_hsa_amd_profiling_async_copy_enable = 128, + HSA_API_ID_hsa_amd_profiling_get_dispatch_time = 129, + HSA_API_ID_hsa_amd_profiling_get_async_copy_time = 130, + HSA_API_ID_hsa_amd_profiling_convert_tick_to_system_domain = 131, + HSA_API_ID_hsa_amd_signal_async_handler = 132, + HSA_API_ID_hsa_amd_async_function = 133, + HSA_API_ID_hsa_amd_signal_wait_any = 134, + HSA_API_ID_hsa_amd_queue_cu_set_mask = 135, + HSA_API_ID_hsa_amd_memory_pool_get_info = 136, + HSA_API_ID_hsa_amd_agent_iterate_memory_pools = 137, + HSA_API_ID_hsa_amd_memory_pool_allocate = 138, + HSA_API_ID_hsa_amd_memory_pool_free = 139, + HSA_API_ID_hsa_amd_memory_async_copy = 140, + HSA_API_ID_hsa_amd_memory_async_copy_on_engine = 141, + HSA_API_ID_hsa_amd_memory_copy_engine_status = 142, + HSA_API_ID_hsa_amd_agent_memory_pool_get_info = 143, + HSA_API_ID_hsa_amd_agents_allow_access = 144, + HSA_API_ID_hsa_amd_memory_pool_can_migrate = 145, + HSA_API_ID_hsa_amd_memory_migrate = 146, + HSA_API_ID_hsa_amd_memory_lock = 147, + HSA_API_ID_hsa_amd_memory_unlock = 148, + HSA_API_ID_hsa_amd_memory_fill = 149, + HSA_API_ID_hsa_amd_interop_map_buffer = 150, + HSA_API_ID_hsa_amd_interop_unmap_buffer = 151, + HSA_API_ID_hsa_amd_image_create = 152, + HSA_API_ID_hsa_amd_pointer_info = 153, + HSA_API_ID_hsa_amd_pointer_info_set_userdata = 154, + HSA_API_ID_hsa_amd_ipc_memory_create = 155, + HSA_API_ID_hsa_amd_ipc_memory_attach = 156, + HSA_API_ID_hsa_amd_ipc_memory_detach = 157, + HSA_API_ID_hsa_amd_signal_create = 158, + HSA_API_ID_hsa_amd_ipc_signal_create = 159, + HSA_API_ID_hsa_amd_ipc_signal_attach = 160, + HSA_API_ID_hsa_amd_register_system_event_handler = 161, + HSA_API_ID_hsa_amd_queue_intercept_create = 162, + HSA_API_ID_hsa_amd_queue_intercept_register = 163, + HSA_API_ID_hsa_amd_queue_set_priority = 164, + HSA_API_ID_hsa_amd_memory_async_copy_rect = 165, + HSA_API_ID_hsa_amd_runtime_queue_create_register = 166, + HSA_API_ID_hsa_amd_memory_lock_to_pool = 167, + HSA_API_ID_hsa_amd_register_deallocation_callback = 168, + HSA_API_ID_hsa_amd_deregister_deallocation_callback = 169, + HSA_API_ID_hsa_amd_signal_value_pointer = 170, + HSA_API_ID_hsa_amd_svm_attributes_set = 171, + HSA_API_ID_hsa_amd_svm_attributes_get = 172, + HSA_API_ID_hsa_amd_svm_prefetch_async = 173, + HSA_API_ID_hsa_amd_spm_acquire = 174, + HSA_API_ID_hsa_amd_spm_release = 175, + HSA_API_ID_hsa_amd_spm_set_dest_buffer = 176, + HSA_API_ID_hsa_amd_queue_cu_get_mask = 177, + HSA_API_ID_hsa_amd_portable_export_dmabuf = 178, + HSA_API_ID_hsa_amd_portable_close_dmabuf = 179, + HSA_API_ID_hsa_amd_vmem_address_reserve = 180, + HSA_API_ID_hsa_amd_vmem_address_free = 181, + HSA_API_ID_hsa_amd_vmem_handle_create = 182, + HSA_API_ID_hsa_amd_vmem_handle_release = 183, + HSA_API_ID_hsa_amd_vmem_map = 184, + HSA_API_ID_hsa_amd_vmem_unmap = 185, + HSA_API_ID_hsa_amd_vmem_set_access = 186, + HSA_API_ID_hsa_amd_vmem_get_access = 187, + HSA_API_ID_hsa_amd_vmem_export_shareable_handle = 188, + HSA_API_ID_hsa_amd_vmem_import_shareable_handle = 189, + HSA_API_ID_hsa_amd_vmem_retain_alloc_handle = 190, + HSA_API_ID_hsa_amd_vmem_get_alloc_properties_from_handle = 191, + HSA_API_ID_hsa_amd_agent_set_async_scratch_limit = 192, + HSA_API_ID_hsa_amd_queue_get_info = 193, + HSA_API_ID_hsa_amd_vmem_address_reserve_align = 194, + + /* block: ImageExt API */ + HSA_API_ID_hsa_ext_image_get_capability = 195, + HSA_API_ID_hsa_ext_image_data_get_info = 196, + HSA_API_ID_hsa_ext_image_create = 197, + HSA_API_ID_hsa_ext_image_import = 198, + HSA_API_ID_hsa_ext_image_export = 199, + HSA_API_ID_hsa_ext_image_copy = 200, + HSA_API_ID_hsa_ext_image_clear = 201, + HSA_API_ID_hsa_ext_image_destroy = 202, + HSA_API_ID_hsa_ext_sampler_create = 203, + HSA_API_ID_hsa_ext_sampler_destroy = 204, + HSA_API_ID_hsa_ext_image_get_capability_with_layout = 205, + HSA_API_ID_hsa_ext_image_data_get_info_with_layout = 206, + HSA_API_ID_hsa_ext_image_create_with_layout = 207, + + HSA_API_ID_DISPATCH = 208, + HSA_API_ID_NUMBER = 209, +}; +/* Declarations of APIs intended for use only by tools. */ +typedef void (*hsa_amd_queue_intercept_packet_writer)(const void*, uint64_t); +typedef void (*hsa_amd_queue_intercept_handler)(const void*, uint64_t, uint64_t, void*, + hsa_amd_queue_intercept_packet_writer); +typedef void (*hsa_amd_runtime_queue_notifier)(const hsa_queue_t*, hsa_agent_t, void*); + +/* section: API arg structure */ + +struct hsa_api_data_t { + uint64_t correlation_id; + uint32_t phase; + union { + uint64_t uint64_t_retval; + hsa_status_t hsa_status_t_retval; + hsa_signal_value_t hsa_signal_value_t_retval; + uint32_t uint32_t_retval; + }; + union { + /* block: CoreApi API */ + struct { + } hsa_init; + struct { + } hsa_shut_down; + struct { + hsa_system_info_t attribute; + void* value; + } hsa_system_get_info; + struct { + uint16_t extension; + uint16_t version_major; + uint16_t version_minor; + bool* result; + } hsa_system_extension_supported; + struct { + uint16_t extension; + uint16_t version_major; + uint16_t version_minor; + void* table; + } hsa_system_get_extension_table; + struct { + hsa_status_t (* callback)(hsa_agent_t agent,void* data); + void* data; + } hsa_iterate_agents; + struct { + hsa_agent_t agent; + hsa_agent_info_t attribute; + void* value; + } hsa_agent_get_info; + struct { + hsa_agent_t agent; + uint32_t size; + hsa_queue_type32_t type; + void (* callback)(hsa_status_t status,hsa_queue_t* source,void* data); + void* data; + uint32_t private_segment_size; + uint32_t group_segment_size; + hsa_queue_t** queue; + } hsa_queue_create; + struct { + hsa_region_t region; + uint32_t size; + hsa_queue_type32_t type; + uint32_t features; + hsa_signal_t doorbell_signal; + hsa_queue_t** queue; + } hsa_soft_queue_create; + struct { + hsa_queue_t* queue; + } hsa_queue_destroy; + struct { + hsa_queue_t* queue; + } hsa_queue_inactivate; + struct { + const hsa_queue_t* queue; + } hsa_queue_load_read_index_scacquire; + struct { + const hsa_queue_t* queue; + } hsa_queue_load_read_index_relaxed; + struct { + const hsa_queue_t* queue; + } hsa_queue_load_write_index_scacquire; + struct { + const hsa_queue_t* queue; + } hsa_queue_load_write_index_relaxed; + struct { + const hsa_queue_t* queue; + uint64_t value; + } hsa_queue_store_write_index_relaxed; + struct { + const hsa_queue_t* queue; + uint64_t value; + } hsa_queue_store_write_index_screlease; + struct { + const hsa_queue_t* queue; + uint64_t expected; + uint64_t value; + } hsa_queue_cas_write_index_scacq_screl; + struct { + const hsa_queue_t* queue; + uint64_t expected; + uint64_t value; + } hsa_queue_cas_write_index_scacquire; + struct { + const hsa_queue_t* queue; + uint64_t expected; + uint64_t value; + } hsa_queue_cas_write_index_relaxed; + struct { + const hsa_queue_t* queue; + uint64_t expected; + uint64_t value; + } hsa_queue_cas_write_index_screlease; + struct { + const hsa_queue_t* queue; + uint64_t value; + } hsa_queue_add_write_index_scacq_screl; + struct { + const hsa_queue_t* queue; + uint64_t value; + } hsa_queue_add_write_index_scacquire; + struct { + const hsa_queue_t* queue; + uint64_t value; + } hsa_queue_add_write_index_relaxed; + struct { + const hsa_queue_t* queue; + uint64_t value; + } hsa_queue_add_write_index_screlease; + struct { + const hsa_queue_t* queue; + uint64_t value; + } hsa_queue_store_read_index_relaxed; + struct { + const hsa_queue_t* queue; + uint64_t value; + } hsa_queue_store_read_index_screlease; + struct { + hsa_agent_t agent; + hsa_status_t (* callback)(hsa_region_t region,void* data); + void* data; + } hsa_agent_iterate_regions; + struct { + hsa_region_t region; + hsa_region_info_t attribute; + void* value; + } hsa_region_get_info; + struct { + hsa_agent_t agent; + hsa_profile_t profile; + uint16_t* mask; + } hsa_agent_get_exception_policies; + struct { + uint16_t extension; + hsa_agent_t agent; + uint16_t version_major; + uint16_t version_minor; + bool* result; + } hsa_agent_extension_supported; + struct { + void* ptr; + size_t size; + } hsa_memory_register; + struct { + void* ptr; + size_t size; + } hsa_memory_deregister; + struct { + hsa_region_t region; + size_t size; + void** ptr; + } hsa_memory_allocate; + struct { + void* ptr; + } hsa_memory_free; + struct { + void* dst; + const void* src; + size_t size; + } hsa_memory_copy; + struct { + void* ptr; + hsa_agent_t agent; + hsa_access_permission_t access; + } hsa_memory_assign_agent; + struct { + hsa_signal_value_t initial_value; + uint32_t num_consumers; + const hsa_agent_t* consumers; + hsa_signal_t* signal; + } hsa_signal_create; + struct { + hsa_signal_t signal; + } hsa_signal_destroy; + struct { + hsa_signal_t signal; + } hsa_signal_load_relaxed; + struct { + hsa_signal_t signal; + } hsa_signal_load_scacquire; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_store_relaxed; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_store_screlease; + struct { + hsa_signal_t signal; + hsa_signal_condition_t condition; + hsa_signal_value_t compare_value; + uint64_t timeout_hint; + hsa_wait_state_t wait_state_hint; + } hsa_signal_wait_relaxed; + struct { + hsa_signal_t signal; + hsa_signal_condition_t condition; + hsa_signal_value_t compare_value; + uint64_t timeout_hint; + hsa_wait_state_t wait_state_hint; + } hsa_signal_wait_scacquire; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_and_relaxed; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_and_scacquire; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_and_screlease; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_and_scacq_screl; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_or_relaxed; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_or_scacquire; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_or_screlease; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_or_scacq_screl; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_xor_relaxed; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_xor_scacquire; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_xor_screlease; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_xor_scacq_screl; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_exchange_relaxed; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_exchange_scacquire; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_exchange_screlease; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_exchange_scacq_screl; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_add_relaxed; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_add_scacquire; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_add_screlease; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_add_scacq_screl; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_subtract_relaxed; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_subtract_scacquire; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_subtract_screlease; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_subtract_scacq_screl; + struct { + hsa_signal_t signal; + hsa_signal_value_t expected; + hsa_signal_value_t value; + } hsa_signal_cas_relaxed; + struct { + hsa_signal_t signal; + hsa_signal_value_t expected; + hsa_signal_value_t value; + } hsa_signal_cas_scacquire; + struct { + hsa_signal_t signal; + hsa_signal_value_t expected; + hsa_signal_value_t value; + } hsa_signal_cas_screlease; + struct { + hsa_signal_t signal; + hsa_signal_value_t expected; + hsa_signal_value_t value; + } hsa_signal_cas_scacq_screl; + struct { + const char* name; + hsa_isa_t* isa; + } hsa_isa_from_name; + struct { + hsa_isa_t isa; + hsa_isa_info_t attribute; + uint32_t index; + void* value; + } hsa_isa_get_info; + struct { + hsa_isa_t code_object_isa; + hsa_isa_t agent_isa; + bool* result; + } hsa_isa_compatible; + struct { + hsa_code_object_t code_object; + hsa_status_t (* alloc_callback)(size_t size,hsa_callback_data_t data,void** address); + hsa_callback_data_t callback_data; + const char* options; + void** serialized_code_object; + size_t* serialized_code_object_size; + } hsa_code_object_serialize; + struct { + void* serialized_code_object; + size_t serialized_code_object_size; + const char* options; + hsa_code_object_t* code_object; + } hsa_code_object_deserialize; + struct { + hsa_code_object_t code_object; + } hsa_code_object_destroy; + struct { + hsa_code_object_t code_object; + hsa_code_object_info_t attribute; + void* value; + } hsa_code_object_get_info; + struct { + hsa_code_object_t code_object; + const char* symbol_name; + hsa_code_symbol_t* symbol; + } hsa_code_object_get_symbol; + struct { + hsa_code_symbol_t code_symbol; + hsa_code_symbol_info_t attribute; + void* value; + } hsa_code_symbol_get_info; + struct { + hsa_code_object_t code_object; + hsa_status_t (* callback)(hsa_code_object_t code_object,hsa_code_symbol_t symbol,void* data); + void* data; + } hsa_code_object_iterate_symbols; + struct { + hsa_profile_t profile; + hsa_executable_state_t executable_state; + const char* options; + hsa_executable_t* executable; + } hsa_executable_create; + struct { + hsa_executable_t executable; + } hsa_executable_destroy; + struct { + hsa_executable_t executable; + hsa_agent_t agent; + hsa_code_object_t code_object; + const char* options; + } hsa_executable_load_code_object; + struct { + hsa_executable_t executable; + const char* options; + } hsa_executable_freeze; + struct { + hsa_executable_t executable; + hsa_executable_info_t attribute; + void* value; + } hsa_executable_get_info; + struct { + hsa_executable_t executable; + const char* variable_name; + void* address; + } hsa_executable_global_variable_define; + struct { + hsa_executable_t executable; + hsa_agent_t agent; + const char* variable_name; + void* address; + } hsa_executable_agent_global_variable_define; + struct { + hsa_executable_t executable; + hsa_agent_t agent; + const char* variable_name; + void* address; + } hsa_executable_readonly_variable_define; + struct { + hsa_executable_t executable; + uint32_t* result; + } hsa_executable_validate; + struct { + hsa_executable_t executable; + const char* module_name; + const char* symbol_name; + hsa_agent_t agent; + int32_t call_convention; + hsa_executable_symbol_t* symbol; + } hsa_executable_get_symbol; + struct { + hsa_executable_symbol_t executable_symbol; + hsa_executable_symbol_info_t attribute; + void* value; + } hsa_executable_symbol_get_info; + struct { + hsa_executable_t executable; + hsa_status_t (* callback)(hsa_executable_t exec,hsa_executable_symbol_t symbol,void* data); + void* data; + } hsa_executable_iterate_symbols; + struct { + hsa_status_t status; + const char** status_string; + } hsa_status_string; + struct { + uint16_t extension; + const char** name; + } hsa_extension_get_name; + struct { + uint16_t extension; + uint16_t version_major; + uint16_t* version_minor; + bool* result; + } hsa_system_major_extension_supported; + struct { + uint16_t extension; + uint16_t version_major; + size_t table_length; + void* table; + } hsa_system_get_major_extension_table; + struct { + uint16_t extension; + hsa_agent_t agent; + uint16_t version_major; + uint16_t* version_minor; + bool* result; + } hsa_agent_major_extension_supported; + struct { + hsa_cache_t cache; + hsa_cache_info_t attribute; + void* value; + } hsa_cache_get_info; + struct { + hsa_agent_t agent; + hsa_status_t (* callback)(hsa_cache_t cache,void* data); + void* data; + } hsa_agent_iterate_caches; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_silent_store_relaxed; + struct { + hsa_signal_t signal; + hsa_signal_value_t value; + } hsa_signal_silent_store_screlease; + struct { + uint32_t num_signals; + const hsa_signal_t* signals; + uint32_t num_consumers; + const hsa_agent_t* consumers; + hsa_signal_group_t* signal_group; + } hsa_signal_group_create; + struct { + hsa_signal_group_t signal_group; + } hsa_signal_group_destroy; + struct { + hsa_signal_group_t signal_group; + const hsa_signal_condition_t* conditions; + const hsa_signal_value_t* compare_values; + hsa_wait_state_t wait_state_hint; + hsa_signal_t* signal; + hsa_signal_value_t* value; + } hsa_signal_group_wait_any_scacquire; + struct { + hsa_signal_group_t signal_group; + const hsa_signal_condition_t* conditions; + const hsa_signal_value_t* compare_values; + hsa_wait_state_t wait_state_hint; + hsa_signal_t* signal; + hsa_signal_value_t* value; + } hsa_signal_group_wait_any_relaxed; + struct { + hsa_agent_t agent; + hsa_status_t (* callback)(hsa_isa_t isa,void* data); + void* data; + } hsa_agent_iterate_isas; + struct { + hsa_isa_t isa; + hsa_isa_info_t attribute; + void* value; + } hsa_isa_get_info_alt; + struct { + hsa_isa_t isa; + hsa_profile_t profile; + uint16_t* mask; + } hsa_isa_get_exception_policies; + struct { + hsa_isa_t isa; + hsa_fp_type_t fp_type; + hsa_flush_mode_t flush_mode; + hsa_round_method_t* round_method; + } hsa_isa_get_round_method; + struct { + hsa_wavefront_t wavefront; + hsa_wavefront_info_t attribute; + void* value; + } hsa_wavefront_get_info; + struct { + hsa_isa_t isa; + hsa_status_t (* callback)(hsa_wavefront_t wavefront,void* data); + void* data; + } hsa_isa_iterate_wavefronts; + struct { + hsa_code_object_t code_object; + const char* module_name; + const char* symbol_name; + hsa_code_symbol_t* symbol; + } hsa_code_object_get_symbol_from_name; + struct { + hsa_file_t file; + hsa_code_object_reader_t* code_object_reader; + } hsa_code_object_reader_create_from_file; + struct { + const void* code_object; + size_t size; + hsa_code_object_reader_t* code_object_reader; + } hsa_code_object_reader_create_from_memory; + struct { + hsa_code_object_reader_t code_object_reader; + } hsa_code_object_reader_destroy; + struct { + hsa_profile_t profile; + hsa_default_float_rounding_mode_t default_float_rounding_mode; + const char* options; + hsa_executable_t* executable; + } hsa_executable_create_alt; + struct { + hsa_executable_t executable; + hsa_code_object_reader_t code_object_reader; + const char* options; + hsa_loaded_code_object_t* loaded_code_object; + } hsa_executable_load_program_code_object; + struct { + hsa_executable_t executable; + hsa_agent_t agent; + hsa_code_object_reader_t code_object_reader; + const char* options; + hsa_loaded_code_object_t* loaded_code_object; + } hsa_executable_load_agent_code_object; + struct { + hsa_executable_t executable; + const char* options; + uint32_t* result; + } hsa_executable_validate_alt; + struct { + hsa_executable_t executable; + const char* symbol_name; + const hsa_agent_t* agent; + hsa_executable_symbol_t* symbol; + } hsa_executable_get_symbol_by_name; + struct { + hsa_executable_t executable; + hsa_agent_t agent; + hsa_status_t (* callback)(hsa_executable_t exec,hsa_agent_t agent,hsa_executable_symbol_t symbol,void* data); + void* data; + } hsa_executable_iterate_agent_symbols; + struct { + hsa_executable_t executable; + hsa_status_t (* callback)(hsa_executable_t exec,hsa_executable_symbol_t symbol,void* data); + void* data; + } hsa_executable_iterate_program_symbols; + + /* block: AmdExt API */ + struct { + hsa_agent_t agent; + hsa_amd_coherency_type_t* type; + } hsa_amd_coherency_get_type; + struct { + hsa_agent_t agent; + hsa_amd_coherency_type_t type; + } hsa_amd_coherency_set_type; + struct { + hsa_queue_t* queue; + int enable; + } hsa_amd_profiling_set_profiler_enabled; + struct { + bool enable; + } hsa_amd_profiling_async_copy_enable; + struct { + hsa_agent_t agent; + hsa_signal_t signal; + hsa_amd_profiling_dispatch_time_t* time; + } hsa_amd_profiling_get_dispatch_time; + struct { + hsa_signal_t signal; + hsa_amd_profiling_async_copy_time_t* time; + } hsa_amd_profiling_get_async_copy_time; + struct { + hsa_agent_t agent; + uint64_t agent_tick; + uint64_t* system_tick; + } hsa_amd_profiling_convert_tick_to_system_domain; + struct { + hsa_signal_t signal; + hsa_signal_condition_t cond; + hsa_signal_value_t value; + hsa_amd_signal_handler handler; + void* arg; + } hsa_amd_signal_async_handler; + struct { + void (* callback)(void* arg); + void* arg; + } hsa_amd_async_function; + struct { + uint32_t signal_count; + hsa_signal_t* signals; + hsa_signal_condition_t* conds; + hsa_signal_value_t* values; + uint64_t timeout_hint; + hsa_wait_state_t wait_hint; + hsa_signal_value_t* satisfying_value; + } hsa_amd_signal_wait_any; + struct { + const hsa_queue_t* queue; + uint32_t num_cu_mask_count; + const uint32_t* cu_mask; + } hsa_amd_queue_cu_set_mask; + struct { + hsa_amd_memory_pool_t memory_pool; + hsa_amd_memory_pool_info_t attribute; + void* value; + } hsa_amd_memory_pool_get_info; + struct { + hsa_agent_t agent; + hsa_status_t (* callback)(hsa_amd_memory_pool_t memory_pool,void* data); + void* data; + } hsa_amd_agent_iterate_memory_pools; + struct { + hsa_amd_memory_pool_t memory_pool; + size_t size; + uint32_t flags; + void** ptr; + } hsa_amd_memory_pool_allocate; + struct { + void* ptr; + } hsa_amd_memory_pool_free; + struct { + void* dst; + hsa_agent_t dst_agent; + const void* src; + hsa_agent_t src_agent; + size_t size; + uint32_t num_dep_signals; + const hsa_signal_t* dep_signals; + hsa_signal_t completion_signal; + } hsa_amd_memory_async_copy; + struct { + void* dst; + hsa_agent_t dst_agent; + const void* src; + hsa_agent_t src_agent; + size_t size; + uint32_t num_dep_signals; + const hsa_signal_t* dep_signals; + hsa_signal_t completion_signal; + hsa_amd_sdma_engine_id_t engine_id; + bool force_copy_on_sdma; + } hsa_amd_memory_async_copy_on_engine; + struct { + hsa_agent_t dst_agent; + hsa_agent_t src_agent; + uint32_t* engine_ids_mask; + } hsa_amd_memory_copy_engine_status; + struct { + hsa_agent_t agent; + hsa_amd_memory_pool_t memory_pool; + hsa_amd_agent_memory_pool_info_t attribute; + void* value; + } hsa_amd_agent_memory_pool_get_info; + struct { + uint32_t num_agents; + const hsa_agent_t* agents; + const uint32_t* flags; + const void* ptr; + } hsa_amd_agents_allow_access; + struct { + hsa_amd_memory_pool_t src_memory_pool; + hsa_amd_memory_pool_t dst_memory_pool; + bool* result; + } hsa_amd_memory_pool_can_migrate; + struct { + const void* ptr; + hsa_amd_memory_pool_t memory_pool; + uint32_t flags; + } hsa_amd_memory_migrate; + struct { + void* host_ptr; + size_t size; + hsa_agent_t* agents; + int num_agent; + void** agent_ptr; + } hsa_amd_memory_lock; + struct { + void* host_ptr; + } hsa_amd_memory_unlock; + struct { + void* ptr; + uint32_t value; + size_t count; + } hsa_amd_memory_fill; + struct { + uint32_t num_agents; + hsa_agent_t* agents; + int interop_handle; + uint32_t flags; + size_t* size; + void** ptr; + size_t* metadata_size; + const void** metadata; + } hsa_amd_interop_map_buffer; + struct { + void* ptr; + } hsa_amd_interop_unmap_buffer; + struct { + hsa_agent_t agent; + const hsa_ext_image_descriptor_t* image_descriptor; + const hsa_amd_image_descriptor_t* image_layout; + const void* image_data; + hsa_access_permission_t access_permission; + hsa_ext_image_t* image; + } hsa_amd_image_create; + struct { + const void* ptr; + hsa_amd_pointer_info_t* info; + void* (* alloc)(size_t); + uint32_t* num_agents_accessible; + hsa_agent_t** accessible; + } hsa_amd_pointer_info; + struct { + const void* ptr; + void* userdata; + } hsa_amd_pointer_info_set_userdata; + struct { + void* ptr; + size_t len; + hsa_amd_ipc_memory_t* handle; + } hsa_amd_ipc_memory_create; + struct { + const hsa_amd_ipc_memory_t* handle; + size_t len; + uint32_t num_agents; + const hsa_agent_t* mapping_agents; + void** mapped_ptr; + } hsa_amd_ipc_memory_attach; + struct { + void* mapped_ptr; + } hsa_amd_ipc_memory_detach; + struct { + hsa_signal_value_t initial_value; + uint32_t num_consumers; + const hsa_agent_t* consumers; + uint64_t attributes; + hsa_signal_t* signal; + } hsa_amd_signal_create; + struct { + hsa_signal_t signal; + hsa_amd_ipc_signal_t* handle; + } hsa_amd_ipc_signal_create; + struct { + const hsa_amd_ipc_signal_t* handle; + hsa_signal_t* signal; + } hsa_amd_ipc_signal_attach; + struct { + hsa_amd_system_event_callback_t callback; + void* data; + } hsa_amd_register_system_event_handler; + struct { + hsa_agent_t agent_handle; + uint32_t size; + hsa_queue_type32_t type; + void (* callback)(hsa_status_t status,hsa_queue_t* source,void* data); + void* data; + uint32_t private_segment_size; + uint32_t group_segment_size; + hsa_queue_t** queue; + } hsa_amd_queue_intercept_create; + struct { + hsa_queue_t* queue; + hsa_amd_queue_intercept_handler callback; + void* user_data; + } hsa_amd_queue_intercept_register; + struct { + hsa_queue_t* queue; + hsa_amd_queue_priority_t priority; + } hsa_amd_queue_set_priority; + struct { + const hsa_pitched_ptr_t* dst; + const hsa_dim3_t* dst_offset; + const hsa_pitched_ptr_t* src; + const hsa_dim3_t* src_offset; + const hsa_dim3_t* range; + hsa_dim3_t range__val; + hsa_agent_t copy_agent; + hsa_amd_copy_direction_t dir; + uint32_t num_dep_signals; + const hsa_signal_t* dep_signals; + hsa_signal_t completion_signal; + } hsa_amd_memory_async_copy_rect; + struct { + hsa_amd_runtime_queue_notifier callback; + void* user_data; + } hsa_amd_runtime_queue_create_register; + struct { + void* host_ptr; + size_t size; + hsa_agent_t* agents; + int num_agent; + hsa_amd_memory_pool_t pool; + uint32_t flags; + void** agent_ptr; + } hsa_amd_memory_lock_to_pool; + struct { + void* ptr; + hsa_amd_deallocation_callback_t callback; + void* user_data; + } hsa_amd_register_deallocation_callback; + struct { + void* ptr; + hsa_amd_deallocation_callback_t callback; + } hsa_amd_deregister_deallocation_callback; + struct { + hsa_signal_t signal; + volatile hsa_signal_value_t** value_ptr; + } hsa_amd_signal_value_pointer; + struct { + void* ptr; + size_t size; + hsa_amd_svm_attribute_pair_t* attribute_list; + size_t attribute_count; + } hsa_amd_svm_attributes_set; + struct { + void* ptr; + size_t size; + hsa_amd_svm_attribute_pair_t* attribute_list; + size_t attribute_count; + } hsa_amd_svm_attributes_get; + struct { + void* ptr; + size_t size; + hsa_agent_t agent; + uint32_t num_dep_signals; + const hsa_signal_t* dep_signals; + hsa_signal_t completion_signal; + } hsa_amd_svm_prefetch_async; + struct { + hsa_agent_t preferred_agent; + } hsa_amd_spm_acquire; + struct { + hsa_agent_t preferred_agent; + } hsa_amd_spm_release; + struct { + hsa_agent_t preferred_agent; + size_t size_in_bytes; + uint32_t* timeout; + uint32_t* size_copied; + void* dest; + bool* is_data_loss; + } hsa_amd_spm_set_dest_buffer; + struct { + const hsa_queue_t* queue; + uint32_t num_cu_mask_count; + uint32_t* cu_mask; + } hsa_amd_queue_cu_get_mask; + struct { + const void* ptr; + size_t size; + int* dmabuf; + uint64_t* offset; + } hsa_amd_portable_export_dmabuf; + struct { + int dmabuf; + } hsa_amd_portable_close_dmabuf; + struct { + void** va; + size_t size; + uint64_t address; + uint64_t flags; + } hsa_amd_vmem_address_reserve; + struct { + void* va; + size_t size; + } hsa_amd_vmem_address_free; + struct { + hsa_amd_memory_pool_t pool; + size_t size; + hsa_amd_memory_type_t type; + uint64_t flags; + hsa_amd_vmem_alloc_handle_t* memory_handle; + } hsa_amd_vmem_handle_create; + struct { + hsa_amd_vmem_alloc_handle_t memory_handle; + } hsa_amd_vmem_handle_release; + struct { + void* va; + size_t size; + size_t in_offset; + hsa_amd_vmem_alloc_handle_t memory_handle; + uint64_t flags; + } hsa_amd_vmem_map; + struct { + void* va; + size_t size; + } hsa_amd_vmem_unmap; + struct { + void* va; + size_t size; + const hsa_amd_memory_access_desc_t* desc; + size_t desc_cnt; + } hsa_amd_vmem_set_access; + struct { + void* va; + hsa_access_permission_t* perms; + hsa_agent_t agent_handle; + } hsa_amd_vmem_get_access; + struct { + int* dmabuf_fd; + hsa_amd_vmem_alloc_handle_t handle; + uint64_t flags; + } hsa_amd_vmem_export_shareable_handle; + struct { + int dmabuf_fd; + hsa_amd_vmem_alloc_handle_t* handle; + } hsa_amd_vmem_import_shareable_handle; + struct { + hsa_amd_vmem_alloc_handle_t* memory_handle; + void* addr; + } hsa_amd_vmem_retain_alloc_handle; + struct { + hsa_amd_vmem_alloc_handle_t memory_handle; + hsa_amd_memory_pool_t* pool; + hsa_amd_memory_type_t* type; + } hsa_amd_vmem_get_alloc_properties_from_handle; + struct { + hsa_agent_t agent; + size_t threshold; + } hsa_amd_agent_set_async_scratch_limit; + struct { + hsa_queue_t* queue; + hsa_queue_info_attribute_t attribute; + void* value; + } hsa_amd_queue_get_info; + struct { + void** va; + size_t size; + uint64_t address; + uint64_t alignment; + uint64_t flags; + } hsa_amd_vmem_address_reserve_align; + + /* block: ImageExt API */ + struct { + hsa_agent_t agent; + hsa_ext_image_geometry_t geometry; + const hsa_ext_image_format_t* image_format; + uint32_t* capability_mask; + } hsa_ext_image_get_capability; + struct { + hsa_agent_t agent; + const hsa_ext_image_descriptor_t* image_descriptor; + hsa_access_permission_t access_permission; + hsa_ext_image_data_info_t* image_data_info; + } hsa_ext_image_data_get_info; + struct { + hsa_agent_t agent; + const hsa_ext_image_descriptor_t* image_descriptor; + const void* image_data; + hsa_access_permission_t access_permission; + hsa_ext_image_t* image; + } hsa_ext_image_create; + struct { + hsa_agent_t agent; + const void* src_memory; + size_t src_row_pitch; + size_t src_slice_pitch; + hsa_ext_image_t dst_image; + const hsa_ext_image_region_t* image_region; + } hsa_ext_image_import; + struct { + hsa_agent_t agent; + hsa_ext_image_t src_image; + void* dst_memory; + size_t dst_row_pitch; + size_t dst_slice_pitch; + const hsa_ext_image_region_t* image_region; + } hsa_ext_image_export; + struct { + hsa_agent_t agent; + hsa_ext_image_t src_image; + const hsa_dim3_t* src_offset; + hsa_ext_image_t dst_image; + const hsa_dim3_t* dst_offset; + const hsa_dim3_t* range; + } hsa_ext_image_copy; + struct { + hsa_agent_t agent; + hsa_ext_image_t image; + const void* data; + const hsa_ext_image_region_t* image_region; + } hsa_ext_image_clear; + struct { + hsa_agent_t agent; + hsa_ext_image_t image; + } hsa_ext_image_destroy; + struct { + hsa_agent_t agent; + const hsa_ext_sampler_descriptor_t* sampler_descriptor; + hsa_ext_sampler_t* sampler; + } hsa_ext_sampler_create; + struct { + hsa_agent_t agent; + hsa_ext_sampler_t sampler; + } hsa_ext_sampler_destroy; + struct { + hsa_agent_t agent; + hsa_ext_image_geometry_t geometry; + const hsa_ext_image_format_t* image_format; + hsa_ext_image_data_layout_t image_data_layout; + uint32_t* capability_mask; + } hsa_ext_image_get_capability_with_layout; + struct { + hsa_agent_t agent; + const hsa_ext_image_descriptor_t* image_descriptor; + hsa_access_permission_t access_permission; + hsa_ext_image_data_layout_t image_data_layout; + size_t image_data_row_pitch; + size_t image_data_slice_pitch; + hsa_ext_image_data_info_t* image_data_info; + } hsa_ext_image_data_get_info_with_layout; + struct { + hsa_agent_t agent; + const hsa_ext_image_descriptor_t* image_descriptor; + const void* image_data; + hsa_access_permission_t access_permission; + hsa_ext_image_data_layout_t image_data_layout; + size_t image_data_row_pitch; + size_t image_data_slice_pitch; + hsa_ext_image_t* image; + } hsa_ext_image_create_with_layout; + } args; + uint64_t *phase_data; +}; + +/* section: API output stream */ + +#ifdef __cplusplus +#include "hsa_ostream_ops.h" +typedef std::pair hsa_api_data_pair_t; +inline std::ostream& operator<< (std::ostream& out, const hsa_api_data_pair_t& data_pair) { + const uint32_t cid = data_pair.first; + const hsa_api_data_t& api_data = data_pair.second; + switch(cid) { + /* block: CoreApi API */ + case HSA_API_ID_hsa_init: { + out << "hsa_init("; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_shut_down: { + out << "hsa_shut_down("; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_system_get_info: { + out << "hsa_system_get_info("; + out << api_data.args.hsa_system_get_info.attribute << ", "; + out << api_data.args.hsa_system_get_info.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_system_extension_supported: { + out << "hsa_system_extension_supported("; + out << api_data.args.hsa_system_extension_supported.extension << ", "; + out << api_data.args.hsa_system_extension_supported.version_major << ", "; + out << api_data.args.hsa_system_extension_supported.version_minor << ", "; + out << api_data.args.hsa_system_extension_supported.result; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_system_get_extension_table: { + out << "hsa_system_get_extension_table("; + out << api_data.args.hsa_system_get_extension_table.extension << ", "; + out << api_data.args.hsa_system_get_extension_table.version_major << ", "; + out << api_data.args.hsa_system_get_extension_table.version_minor << ", "; + out << api_data.args.hsa_system_get_extension_table.table; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_iterate_agents: { + out << "hsa_iterate_agents("; + out << api_data.args.hsa_iterate_agents.callback << ", "; + out << api_data.args.hsa_iterate_agents.data; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_agent_get_info: { + out << "hsa_agent_get_info("; + out << api_data.args.hsa_agent_get_info.agent << ", "; + out << api_data.args.hsa_agent_get_info.attribute << ", "; + out << api_data.args.hsa_agent_get_info.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_queue_create: { + out << "hsa_queue_create("; + out << api_data.args.hsa_queue_create.agent << ", "; + out << api_data.args.hsa_queue_create.size << ", "; + out << api_data.args.hsa_queue_create.type << ", "; + out << api_data.args.hsa_queue_create.callback << ", "; + out << api_data.args.hsa_queue_create.data << ", "; + out << api_data.args.hsa_queue_create.private_segment_size << ", "; + out << api_data.args.hsa_queue_create.group_segment_size << ", "; + out << api_data.args.hsa_queue_create.queue; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_soft_queue_create: { + out << "hsa_soft_queue_create("; + out << api_data.args.hsa_soft_queue_create.region << ", "; + out << api_data.args.hsa_soft_queue_create.size << ", "; + out << api_data.args.hsa_soft_queue_create.type << ", "; + out << api_data.args.hsa_soft_queue_create.features << ", "; + out << api_data.args.hsa_soft_queue_create.doorbell_signal << ", "; + out << api_data.args.hsa_soft_queue_create.queue; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_queue_destroy: { + out << "hsa_queue_destroy("; + out << api_data.args.hsa_queue_destroy.queue; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_queue_inactivate: { + out << "hsa_queue_inactivate("; + out << api_data.args.hsa_queue_inactivate.queue; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_queue_load_read_index_scacquire: { + out << "hsa_queue_load_read_index_scacquire("; + out << api_data.args.hsa_queue_load_read_index_scacquire.queue; + out << ") = " << api_data.uint64_t_retval; + break; + } + case HSA_API_ID_hsa_queue_load_read_index_relaxed: { + out << "hsa_queue_load_read_index_relaxed("; + out << api_data.args.hsa_queue_load_read_index_relaxed.queue; + out << ") = " << api_data.uint64_t_retval; + break; + } + case HSA_API_ID_hsa_queue_load_write_index_scacquire: { + out << "hsa_queue_load_write_index_scacquire("; + out << api_data.args.hsa_queue_load_write_index_scacquire.queue; + out << ") = " << api_data.uint64_t_retval; + break; + } + case HSA_API_ID_hsa_queue_load_write_index_relaxed: { + out << "hsa_queue_load_write_index_relaxed("; + out << api_data.args.hsa_queue_load_write_index_relaxed.queue; + out << ") = " << api_data.uint64_t_retval; + break; + } + case HSA_API_ID_hsa_queue_store_write_index_relaxed: { + out << "hsa_queue_store_write_index_relaxed("; + out << api_data.args.hsa_queue_store_write_index_relaxed.queue << ", "; + out << api_data.args.hsa_queue_store_write_index_relaxed.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_queue_store_write_index_screlease: { + out << "hsa_queue_store_write_index_screlease("; + out << api_data.args.hsa_queue_store_write_index_screlease.queue << ", "; + out << api_data.args.hsa_queue_store_write_index_screlease.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_queue_cas_write_index_scacq_screl: { + out << "hsa_queue_cas_write_index_scacq_screl("; + out << api_data.args.hsa_queue_cas_write_index_scacq_screl.queue << ", "; + out << api_data.args.hsa_queue_cas_write_index_scacq_screl.expected << ", "; + out << api_data.args.hsa_queue_cas_write_index_scacq_screl.value; + out << ") = " << api_data.uint64_t_retval; + break; + } + case HSA_API_ID_hsa_queue_cas_write_index_scacquire: { + out << "hsa_queue_cas_write_index_scacquire("; + out << api_data.args.hsa_queue_cas_write_index_scacquire.queue << ", "; + out << api_data.args.hsa_queue_cas_write_index_scacquire.expected << ", "; + out << api_data.args.hsa_queue_cas_write_index_scacquire.value; + out << ") = " << api_data.uint64_t_retval; + break; + } + case HSA_API_ID_hsa_queue_cas_write_index_relaxed: { + out << "hsa_queue_cas_write_index_relaxed("; + out << api_data.args.hsa_queue_cas_write_index_relaxed.queue << ", "; + out << api_data.args.hsa_queue_cas_write_index_relaxed.expected << ", "; + out << api_data.args.hsa_queue_cas_write_index_relaxed.value; + out << ") = " << api_data.uint64_t_retval; + break; + } + case HSA_API_ID_hsa_queue_cas_write_index_screlease: { + out << "hsa_queue_cas_write_index_screlease("; + out << api_data.args.hsa_queue_cas_write_index_screlease.queue << ", "; + out << api_data.args.hsa_queue_cas_write_index_screlease.expected << ", "; + out << api_data.args.hsa_queue_cas_write_index_screlease.value; + out << ") = " << api_data.uint64_t_retval; + break; + } + case HSA_API_ID_hsa_queue_add_write_index_scacq_screl: { + out << "hsa_queue_add_write_index_scacq_screl("; + out << api_data.args.hsa_queue_add_write_index_scacq_screl.queue << ", "; + out << api_data.args.hsa_queue_add_write_index_scacq_screl.value; + out << ") = " << api_data.uint64_t_retval; + break; + } + case HSA_API_ID_hsa_queue_add_write_index_scacquire: { + out << "hsa_queue_add_write_index_scacquire("; + out << api_data.args.hsa_queue_add_write_index_scacquire.queue << ", "; + out << api_data.args.hsa_queue_add_write_index_scacquire.value; + out << ") = " << api_data.uint64_t_retval; + break; + } + case HSA_API_ID_hsa_queue_add_write_index_relaxed: { + out << "hsa_queue_add_write_index_relaxed("; + out << api_data.args.hsa_queue_add_write_index_relaxed.queue << ", "; + out << api_data.args.hsa_queue_add_write_index_relaxed.value; + out << ") = " << api_data.uint64_t_retval; + break; + } + case HSA_API_ID_hsa_queue_add_write_index_screlease: { + out << "hsa_queue_add_write_index_screlease("; + out << api_data.args.hsa_queue_add_write_index_screlease.queue << ", "; + out << api_data.args.hsa_queue_add_write_index_screlease.value; + out << ") = " << api_data.uint64_t_retval; + break; + } + case HSA_API_ID_hsa_queue_store_read_index_relaxed: { + out << "hsa_queue_store_read_index_relaxed("; + out << api_data.args.hsa_queue_store_read_index_relaxed.queue << ", "; + out << api_data.args.hsa_queue_store_read_index_relaxed.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_queue_store_read_index_screlease: { + out << "hsa_queue_store_read_index_screlease("; + out << api_data.args.hsa_queue_store_read_index_screlease.queue << ", "; + out << api_data.args.hsa_queue_store_read_index_screlease.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_agent_iterate_regions: { + out << "hsa_agent_iterate_regions("; + out << api_data.args.hsa_agent_iterate_regions.agent << ", "; + out << api_data.args.hsa_agent_iterate_regions.callback << ", "; + out << api_data.args.hsa_agent_iterate_regions.data; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_region_get_info: { + out << "hsa_region_get_info("; + out << api_data.args.hsa_region_get_info.region << ", "; + out << api_data.args.hsa_region_get_info.attribute << ", "; + out << api_data.args.hsa_region_get_info.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_agent_get_exception_policies: { + out << "hsa_agent_get_exception_policies("; + out << api_data.args.hsa_agent_get_exception_policies.agent << ", "; + out << api_data.args.hsa_agent_get_exception_policies.profile << ", "; + out << api_data.args.hsa_agent_get_exception_policies.mask; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_agent_extension_supported: { + out << "hsa_agent_extension_supported("; + out << api_data.args.hsa_agent_extension_supported.extension << ", "; + out << api_data.args.hsa_agent_extension_supported.agent << ", "; + out << api_data.args.hsa_agent_extension_supported.version_major << ", "; + out << api_data.args.hsa_agent_extension_supported.version_minor << ", "; + out << api_data.args.hsa_agent_extension_supported.result; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_memory_register: { + out << "hsa_memory_register("; + out << api_data.args.hsa_memory_register.ptr << ", "; + out << api_data.args.hsa_memory_register.size; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_memory_deregister: { + out << "hsa_memory_deregister("; + out << api_data.args.hsa_memory_deregister.ptr << ", "; + out << api_data.args.hsa_memory_deregister.size; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_memory_allocate: { + out << "hsa_memory_allocate("; + out << api_data.args.hsa_memory_allocate.region << ", "; + out << api_data.args.hsa_memory_allocate.size << ", "; + out << api_data.args.hsa_memory_allocate.ptr; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_memory_free: { + out << "hsa_memory_free("; + out << api_data.args.hsa_memory_free.ptr; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_memory_copy: { + out << "hsa_memory_copy("; + out << api_data.args.hsa_memory_copy.dst << ", "; + out << api_data.args.hsa_memory_copy.src << ", "; + out << api_data.args.hsa_memory_copy.size; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_memory_assign_agent: { + out << "hsa_memory_assign_agent("; + out << api_data.args.hsa_memory_assign_agent.ptr << ", "; + out << api_data.args.hsa_memory_assign_agent.agent << ", "; + out << api_data.args.hsa_memory_assign_agent.access; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_signal_create: { + out << "hsa_signal_create("; + out << api_data.args.hsa_signal_create.initial_value << ", "; + out << api_data.args.hsa_signal_create.num_consumers << ", "; + out << api_data.args.hsa_signal_create.consumers << ", "; + out << api_data.args.hsa_signal_create.signal; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_signal_destroy: { + out << "hsa_signal_destroy("; + out << api_data.args.hsa_signal_destroy.signal; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_signal_load_relaxed: { + out << "hsa_signal_load_relaxed("; + out << api_data.args.hsa_signal_load_relaxed.signal; + out << ") = " << api_data.hsa_signal_value_t_retval; + break; + } + case HSA_API_ID_hsa_signal_load_scacquire: { + out << "hsa_signal_load_scacquire("; + out << api_data.args.hsa_signal_load_scacquire.signal; + out << ") = " << api_data.hsa_signal_value_t_retval; + break; + } + case HSA_API_ID_hsa_signal_store_relaxed: { + out << "hsa_signal_store_relaxed("; + out << api_data.args.hsa_signal_store_relaxed.signal << ", "; + out << api_data.args.hsa_signal_store_relaxed.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_store_screlease: { + out << "hsa_signal_store_screlease("; + out << api_data.args.hsa_signal_store_screlease.signal << ", "; + out << api_data.args.hsa_signal_store_screlease.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_wait_relaxed: { + out << "hsa_signal_wait_relaxed("; + out << api_data.args.hsa_signal_wait_relaxed.signal << ", "; + out << api_data.args.hsa_signal_wait_relaxed.condition << ", "; + out << api_data.args.hsa_signal_wait_relaxed.compare_value << ", "; + out << api_data.args.hsa_signal_wait_relaxed.timeout_hint << ", "; + out << api_data.args.hsa_signal_wait_relaxed.wait_state_hint; + out << ") = " << api_data.hsa_signal_value_t_retval; + break; + } + case HSA_API_ID_hsa_signal_wait_scacquire: { + out << "hsa_signal_wait_scacquire("; + out << api_data.args.hsa_signal_wait_scacquire.signal << ", "; + out << api_data.args.hsa_signal_wait_scacquire.condition << ", "; + out << api_data.args.hsa_signal_wait_scacquire.compare_value << ", "; + out << api_data.args.hsa_signal_wait_scacquire.timeout_hint << ", "; + out << api_data.args.hsa_signal_wait_scacquire.wait_state_hint; + out << ") = " << api_data.hsa_signal_value_t_retval; + break; + } + case HSA_API_ID_hsa_signal_and_relaxed: { + out << "hsa_signal_and_relaxed("; + out << api_data.args.hsa_signal_and_relaxed.signal << ", "; + out << api_data.args.hsa_signal_and_relaxed.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_and_scacquire: { + out << "hsa_signal_and_scacquire("; + out << api_data.args.hsa_signal_and_scacquire.signal << ", "; + out << api_data.args.hsa_signal_and_scacquire.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_and_screlease: { + out << "hsa_signal_and_screlease("; + out << api_data.args.hsa_signal_and_screlease.signal << ", "; + out << api_data.args.hsa_signal_and_screlease.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_and_scacq_screl: { + out << "hsa_signal_and_scacq_screl("; + out << api_data.args.hsa_signal_and_scacq_screl.signal << ", "; + out << api_data.args.hsa_signal_and_scacq_screl.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_or_relaxed: { + out << "hsa_signal_or_relaxed("; + out << api_data.args.hsa_signal_or_relaxed.signal << ", "; + out << api_data.args.hsa_signal_or_relaxed.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_or_scacquire: { + out << "hsa_signal_or_scacquire("; + out << api_data.args.hsa_signal_or_scacquire.signal << ", "; + out << api_data.args.hsa_signal_or_scacquire.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_or_screlease: { + out << "hsa_signal_or_screlease("; + out << api_data.args.hsa_signal_or_screlease.signal << ", "; + out << api_data.args.hsa_signal_or_screlease.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_or_scacq_screl: { + out << "hsa_signal_or_scacq_screl("; + out << api_data.args.hsa_signal_or_scacq_screl.signal << ", "; + out << api_data.args.hsa_signal_or_scacq_screl.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_xor_relaxed: { + out << "hsa_signal_xor_relaxed("; + out << api_data.args.hsa_signal_xor_relaxed.signal << ", "; + out << api_data.args.hsa_signal_xor_relaxed.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_xor_scacquire: { + out << "hsa_signal_xor_scacquire("; + out << api_data.args.hsa_signal_xor_scacquire.signal << ", "; + out << api_data.args.hsa_signal_xor_scacquire.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_xor_screlease: { + out << "hsa_signal_xor_screlease("; + out << api_data.args.hsa_signal_xor_screlease.signal << ", "; + out << api_data.args.hsa_signal_xor_screlease.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_xor_scacq_screl: { + out << "hsa_signal_xor_scacq_screl("; + out << api_data.args.hsa_signal_xor_scacq_screl.signal << ", "; + out << api_data.args.hsa_signal_xor_scacq_screl.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_exchange_relaxed: { + out << "hsa_signal_exchange_relaxed("; + out << api_data.args.hsa_signal_exchange_relaxed.signal << ", "; + out << api_data.args.hsa_signal_exchange_relaxed.value; + out << ") = " << api_data.hsa_signal_value_t_retval; + break; + } + case HSA_API_ID_hsa_signal_exchange_scacquire: { + out << "hsa_signal_exchange_scacquire("; + out << api_data.args.hsa_signal_exchange_scacquire.signal << ", "; + out << api_data.args.hsa_signal_exchange_scacquire.value; + out << ") = " << api_data.hsa_signal_value_t_retval; + break; + } + case HSA_API_ID_hsa_signal_exchange_screlease: { + out << "hsa_signal_exchange_screlease("; + out << api_data.args.hsa_signal_exchange_screlease.signal << ", "; + out << api_data.args.hsa_signal_exchange_screlease.value; + out << ") = " << api_data.hsa_signal_value_t_retval; + break; + } + case HSA_API_ID_hsa_signal_exchange_scacq_screl: { + out << "hsa_signal_exchange_scacq_screl("; + out << api_data.args.hsa_signal_exchange_scacq_screl.signal << ", "; + out << api_data.args.hsa_signal_exchange_scacq_screl.value; + out << ") = " << api_data.hsa_signal_value_t_retval; + break; + } + case HSA_API_ID_hsa_signal_add_relaxed: { + out << "hsa_signal_add_relaxed("; + out << api_data.args.hsa_signal_add_relaxed.signal << ", "; + out << api_data.args.hsa_signal_add_relaxed.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_add_scacquire: { + out << "hsa_signal_add_scacquire("; + out << api_data.args.hsa_signal_add_scacquire.signal << ", "; + out << api_data.args.hsa_signal_add_scacquire.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_add_screlease: { + out << "hsa_signal_add_screlease("; + out << api_data.args.hsa_signal_add_screlease.signal << ", "; + out << api_data.args.hsa_signal_add_screlease.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_add_scacq_screl: { + out << "hsa_signal_add_scacq_screl("; + out << api_data.args.hsa_signal_add_scacq_screl.signal << ", "; + out << api_data.args.hsa_signal_add_scacq_screl.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_subtract_relaxed: { + out << "hsa_signal_subtract_relaxed("; + out << api_data.args.hsa_signal_subtract_relaxed.signal << ", "; + out << api_data.args.hsa_signal_subtract_relaxed.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_subtract_scacquire: { + out << "hsa_signal_subtract_scacquire("; + out << api_data.args.hsa_signal_subtract_scacquire.signal << ", "; + out << api_data.args.hsa_signal_subtract_scacquire.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_subtract_screlease: { + out << "hsa_signal_subtract_screlease("; + out << api_data.args.hsa_signal_subtract_screlease.signal << ", "; + out << api_data.args.hsa_signal_subtract_screlease.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_subtract_scacq_screl: { + out << "hsa_signal_subtract_scacq_screl("; + out << api_data.args.hsa_signal_subtract_scacq_screl.signal << ", "; + out << api_data.args.hsa_signal_subtract_scacq_screl.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_cas_relaxed: { + out << "hsa_signal_cas_relaxed("; + out << api_data.args.hsa_signal_cas_relaxed.signal << ", "; + out << api_data.args.hsa_signal_cas_relaxed.expected << ", "; + out << api_data.args.hsa_signal_cas_relaxed.value; + out << ") = " << api_data.hsa_signal_value_t_retval; + break; + } + case HSA_API_ID_hsa_signal_cas_scacquire: { + out << "hsa_signal_cas_scacquire("; + out << api_data.args.hsa_signal_cas_scacquire.signal << ", "; + out << api_data.args.hsa_signal_cas_scacquire.expected << ", "; + out << api_data.args.hsa_signal_cas_scacquire.value; + out << ") = " << api_data.hsa_signal_value_t_retval; + break; + } + case HSA_API_ID_hsa_signal_cas_screlease: { + out << "hsa_signal_cas_screlease("; + out << api_data.args.hsa_signal_cas_screlease.signal << ", "; + out << api_data.args.hsa_signal_cas_screlease.expected << ", "; + out << api_data.args.hsa_signal_cas_screlease.value; + out << ") = " << api_data.hsa_signal_value_t_retval; + break; + } + case HSA_API_ID_hsa_signal_cas_scacq_screl: { + out << "hsa_signal_cas_scacq_screl("; + out << api_data.args.hsa_signal_cas_scacq_screl.signal << ", "; + out << api_data.args.hsa_signal_cas_scacq_screl.expected << ", "; + out << api_data.args.hsa_signal_cas_scacq_screl.value; + out << ") = " << api_data.hsa_signal_value_t_retval; + break; + } + case HSA_API_ID_hsa_isa_from_name: { + out << "hsa_isa_from_name("; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_isa_from_name.name << ", "; + out << api_data.args.hsa_isa_from_name.isa; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_isa_get_info: { + out << "hsa_isa_get_info("; + out << api_data.args.hsa_isa_get_info.isa << ", "; + out << api_data.args.hsa_isa_get_info.attribute << ", "; + out << api_data.args.hsa_isa_get_info.index << ", "; + out << api_data.args.hsa_isa_get_info.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_isa_compatible: { + out << "hsa_isa_compatible("; + out << api_data.args.hsa_isa_compatible.code_object_isa << ", "; + out << api_data.args.hsa_isa_compatible.agent_isa << ", "; + out << api_data.args.hsa_isa_compatible.result; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_code_object_serialize: { + out << "hsa_code_object_serialize("; + out << api_data.args.hsa_code_object_serialize.code_object << ", "; + out << api_data.args.hsa_code_object_serialize.alloc_callback << ", "; + out << api_data.args.hsa_code_object_serialize.callback_data << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_code_object_serialize.options << ", "; + out << api_data.args.hsa_code_object_serialize.serialized_code_object << ", "; + out << api_data.args.hsa_code_object_serialize.serialized_code_object_size; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_code_object_deserialize: { + out << "hsa_code_object_deserialize("; + out << api_data.args.hsa_code_object_deserialize.serialized_code_object << ", "; + out << api_data.args.hsa_code_object_deserialize.serialized_code_object_size << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_code_object_deserialize.options << ", "; + out << api_data.args.hsa_code_object_deserialize.code_object; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_code_object_destroy: { + out << "hsa_code_object_destroy("; + out << api_data.args.hsa_code_object_destroy.code_object; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_code_object_get_info: { + out << "hsa_code_object_get_info("; + out << api_data.args.hsa_code_object_get_info.code_object << ", "; + out << api_data.args.hsa_code_object_get_info.attribute << ", "; + out << api_data.args.hsa_code_object_get_info.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_code_object_get_symbol: { + out << "hsa_code_object_get_symbol("; + out << api_data.args.hsa_code_object_get_symbol.code_object << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_code_object_get_symbol.symbol_name << ", "; + out << api_data.args.hsa_code_object_get_symbol.symbol; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_code_symbol_get_info: { + out << "hsa_code_symbol_get_info("; + out << api_data.args.hsa_code_symbol_get_info.code_symbol << ", "; + out << api_data.args.hsa_code_symbol_get_info.attribute << ", "; + out << api_data.args.hsa_code_symbol_get_info.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_code_object_iterate_symbols: { + out << "hsa_code_object_iterate_symbols("; + out << api_data.args.hsa_code_object_iterate_symbols.code_object << ", "; + out << api_data.args.hsa_code_object_iterate_symbols.callback << ", "; + out << api_data.args.hsa_code_object_iterate_symbols.data; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_create: { + out << "hsa_executable_create("; + out << api_data.args.hsa_executable_create.profile << ", "; + out << api_data.args.hsa_executable_create.executable_state << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_executable_create.options << ", "; + out << api_data.args.hsa_executable_create.executable; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_destroy: { + out << "hsa_executable_destroy("; + out << api_data.args.hsa_executable_destroy.executable; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_load_code_object: { + out << "hsa_executable_load_code_object("; + out << api_data.args.hsa_executable_load_code_object.executable << ", "; + out << api_data.args.hsa_executable_load_code_object.agent << ", "; + out << api_data.args.hsa_executable_load_code_object.code_object << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_executable_load_code_object.options; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_freeze: { + out << "hsa_executable_freeze("; + out << api_data.args.hsa_executable_freeze.executable << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_executable_freeze.options; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_get_info: { + out << "hsa_executable_get_info("; + out << api_data.args.hsa_executable_get_info.executable << ", "; + out << api_data.args.hsa_executable_get_info.attribute << ", "; + out << api_data.args.hsa_executable_get_info.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_global_variable_define: { + out << "hsa_executable_global_variable_define("; + out << api_data.args.hsa_executable_global_variable_define.executable << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_executable_global_variable_define.variable_name << ", "; + out << api_data.args.hsa_executable_global_variable_define.address; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_agent_global_variable_define: { + out << "hsa_executable_agent_global_variable_define("; + out << api_data.args.hsa_executable_agent_global_variable_define.executable << ", "; + out << api_data.args.hsa_executable_agent_global_variable_define.agent << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_executable_agent_global_variable_define.variable_name << ", "; + out << api_data.args.hsa_executable_agent_global_variable_define.address; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_readonly_variable_define: { + out << "hsa_executable_readonly_variable_define("; + out << api_data.args.hsa_executable_readonly_variable_define.executable << ", "; + out << api_data.args.hsa_executable_readonly_variable_define.agent << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_executable_readonly_variable_define.variable_name << ", "; + out << api_data.args.hsa_executable_readonly_variable_define.address; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_validate: { + out << "hsa_executable_validate("; + out << api_data.args.hsa_executable_validate.executable << ", "; + out << api_data.args.hsa_executable_validate.result; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_get_symbol: { + out << "hsa_executable_get_symbol("; + out << api_data.args.hsa_executable_get_symbol.executable << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_executable_get_symbol.module_name << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_executable_get_symbol.symbol_name << ", "; + out << api_data.args.hsa_executable_get_symbol.agent << ", "; + out << api_data.args.hsa_executable_get_symbol.call_convention << ", "; + out << api_data.args.hsa_executable_get_symbol.symbol; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_symbol_get_info: { + out << "hsa_executable_symbol_get_info("; + out << api_data.args.hsa_executable_symbol_get_info.executable_symbol << ", "; + out << api_data.args.hsa_executable_symbol_get_info.attribute << ", "; + out << api_data.args.hsa_executable_symbol_get_info.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_iterate_symbols: { + out << "hsa_executable_iterate_symbols("; + out << api_data.args.hsa_executable_iterate_symbols.executable << ", "; + out << api_data.args.hsa_executable_iterate_symbols.callback << ", "; + out << api_data.args.hsa_executable_iterate_symbols.data; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_status_string: { + out << "hsa_status_string("; + out << api_data.args.hsa_status_string.status << ", "; + out << api_data.args.hsa_status_string.status_string; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_extension_get_name: { + out << "hsa_extension_get_name("; + out << api_data.args.hsa_extension_get_name.extension << ", "; + out << api_data.args.hsa_extension_get_name.name; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_system_major_extension_supported: { + out << "hsa_system_major_extension_supported("; + out << api_data.args.hsa_system_major_extension_supported.extension << ", "; + out << api_data.args.hsa_system_major_extension_supported.version_major << ", "; + out << api_data.args.hsa_system_major_extension_supported.version_minor << ", "; + out << api_data.args.hsa_system_major_extension_supported.result; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_system_get_major_extension_table: { + out << "hsa_system_get_major_extension_table("; + out << api_data.args.hsa_system_get_major_extension_table.extension << ", "; + out << api_data.args.hsa_system_get_major_extension_table.version_major << ", "; + out << api_data.args.hsa_system_get_major_extension_table.table_length << ", "; + out << api_data.args.hsa_system_get_major_extension_table.table; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_agent_major_extension_supported: { + out << "hsa_agent_major_extension_supported("; + out << api_data.args.hsa_agent_major_extension_supported.extension << ", "; + out << api_data.args.hsa_agent_major_extension_supported.agent << ", "; + out << api_data.args.hsa_agent_major_extension_supported.version_major << ", "; + out << api_data.args.hsa_agent_major_extension_supported.version_minor << ", "; + out << api_data.args.hsa_agent_major_extension_supported.result; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_cache_get_info: { + out << "hsa_cache_get_info("; + out << api_data.args.hsa_cache_get_info.cache << ", "; + out << api_data.args.hsa_cache_get_info.attribute << ", "; + out << api_data.args.hsa_cache_get_info.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_agent_iterate_caches: { + out << "hsa_agent_iterate_caches("; + out << api_data.args.hsa_agent_iterate_caches.agent << ", "; + out << api_data.args.hsa_agent_iterate_caches.callback << ", "; + out << api_data.args.hsa_agent_iterate_caches.data; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_signal_silent_store_relaxed: { + out << "hsa_signal_silent_store_relaxed("; + out << api_data.args.hsa_signal_silent_store_relaxed.signal << ", "; + out << api_data.args.hsa_signal_silent_store_relaxed.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_silent_store_screlease: { + out << "hsa_signal_silent_store_screlease("; + out << api_data.args.hsa_signal_silent_store_screlease.signal << ", "; + out << api_data.args.hsa_signal_silent_store_screlease.value; + out << ") = void"; + break; + } + case HSA_API_ID_hsa_signal_group_create: { + out << "hsa_signal_group_create("; + out << api_data.args.hsa_signal_group_create.num_signals << ", "; + out << api_data.args.hsa_signal_group_create.signals << ", "; + out << api_data.args.hsa_signal_group_create.num_consumers << ", "; + out << api_data.args.hsa_signal_group_create.consumers << ", "; + out << api_data.args.hsa_signal_group_create.signal_group; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_signal_group_destroy: { + out << "hsa_signal_group_destroy("; + out << api_data.args.hsa_signal_group_destroy.signal_group; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_signal_group_wait_any_scacquire: { + out << "hsa_signal_group_wait_any_scacquire("; + out << api_data.args.hsa_signal_group_wait_any_scacquire.signal_group << ", "; + out << api_data.args.hsa_signal_group_wait_any_scacquire.conditions << ", "; + out << api_data.args.hsa_signal_group_wait_any_scacquire.compare_values << ", "; + out << api_data.args.hsa_signal_group_wait_any_scacquire.wait_state_hint << ", "; + out << api_data.args.hsa_signal_group_wait_any_scacquire.signal << ", "; + out << api_data.args.hsa_signal_group_wait_any_scacquire.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_signal_group_wait_any_relaxed: { + out << "hsa_signal_group_wait_any_relaxed("; + out << api_data.args.hsa_signal_group_wait_any_relaxed.signal_group << ", "; + out << api_data.args.hsa_signal_group_wait_any_relaxed.conditions << ", "; + out << api_data.args.hsa_signal_group_wait_any_relaxed.compare_values << ", "; + out << api_data.args.hsa_signal_group_wait_any_relaxed.wait_state_hint << ", "; + out << api_data.args.hsa_signal_group_wait_any_relaxed.signal << ", "; + out << api_data.args.hsa_signal_group_wait_any_relaxed.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_agent_iterate_isas: { + out << "hsa_agent_iterate_isas("; + out << api_data.args.hsa_agent_iterate_isas.agent << ", "; + out << api_data.args.hsa_agent_iterate_isas.callback << ", "; + out << api_data.args.hsa_agent_iterate_isas.data; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_isa_get_info_alt: { + out << "hsa_isa_get_info_alt("; + out << api_data.args.hsa_isa_get_info_alt.isa << ", "; + out << api_data.args.hsa_isa_get_info_alt.attribute << ", "; + out << api_data.args.hsa_isa_get_info_alt.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_isa_get_exception_policies: { + out << "hsa_isa_get_exception_policies("; + out << api_data.args.hsa_isa_get_exception_policies.isa << ", "; + out << api_data.args.hsa_isa_get_exception_policies.profile << ", "; + out << api_data.args.hsa_isa_get_exception_policies.mask; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_isa_get_round_method: { + out << "hsa_isa_get_round_method("; + out << api_data.args.hsa_isa_get_round_method.isa << ", "; + out << api_data.args.hsa_isa_get_round_method.fp_type << ", "; + out << api_data.args.hsa_isa_get_round_method.flush_mode << ", "; + out << api_data.args.hsa_isa_get_round_method.round_method; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_wavefront_get_info: { + out << "hsa_wavefront_get_info("; + out << api_data.args.hsa_wavefront_get_info.wavefront << ", "; + out << api_data.args.hsa_wavefront_get_info.attribute << ", "; + out << api_data.args.hsa_wavefront_get_info.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_isa_iterate_wavefronts: { + out << "hsa_isa_iterate_wavefronts("; + out << api_data.args.hsa_isa_iterate_wavefronts.isa << ", "; + out << api_data.args.hsa_isa_iterate_wavefronts.callback << ", "; + out << api_data.args.hsa_isa_iterate_wavefronts.data; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_code_object_get_symbol_from_name: { + out << "hsa_code_object_get_symbol_from_name("; + out << api_data.args.hsa_code_object_get_symbol_from_name.code_object << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_code_object_get_symbol_from_name.module_name << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_code_object_get_symbol_from_name.symbol_name << ", "; + out << api_data.args.hsa_code_object_get_symbol_from_name.symbol; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_code_object_reader_create_from_file: { + out << "hsa_code_object_reader_create_from_file("; + out << api_data.args.hsa_code_object_reader_create_from_file.file << ", "; + out << api_data.args.hsa_code_object_reader_create_from_file.code_object_reader; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_code_object_reader_create_from_memory: { + out << "hsa_code_object_reader_create_from_memory("; + out << api_data.args.hsa_code_object_reader_create_from_memory.code_object << ", "; + out << api_data.args.hsa_code_object_reader_create_from_memory.size << ", "; + out << api_data.args.hsa_code_object_reader_create_from_memory.code_object_reader; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_code_object_reader_destroy: { + out << "hsa_code_object_reader_destroy("; + out << api_data.args.hsa_code_object_reader_destroy.code_object_reader; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_create_alt: { + out << "hsa_executable_create_alt("; + out << api_data.args.hsa_executable_create_alt.profile << ", "; + out << api_data.args.hsa_executable_create_alt.default_float_rounding_mode << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_executable_create_alt.options << ", "; + out << api_data.args.hsa_executable_create_alt.executable; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_load_program_code_object: { + out << "hsa_executable_load_program_code_object("; + out << api_data.args.hsa_executable_load_program_code_object.executable << ", "; + out << api_data.args.hsa_executable_load_program_code_object.code_object_reader << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_executable_load_program_code_object.options << ", "; + out << api_data.args.hsa_executable_load_program_code_object.loaded_code_object; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_load_agent_code_object: { + out << "hsa_executable_load_agent_code_object("; + out << api_data.args.hsa_executable_load_agent_code_object.executable << ", "; + out << api_data.args.hsa_executable_load_agent_code_object.agent << ", "; + out << api_data.args.hsa_executable_load_agent_code_object.code_object_reader << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_executable_load_agent_code_object.options << ", "; + out << api_data.args.hsa_executable_load_agent_code_object.loaded_code_object; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_validate_alt: { + out << "hsa_executable_validate_alt("; + out << api_data.args.hsa_executable_validate_alt.executable << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_executable_validate_alt.options << ", "; + out << api_data.args.hsa_executable_validate_alt.result; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_get_symbol_by_name: { + out << "hsa_executable_get_symbol_by_name("; + out << api_data.args.hsa_executable_get_symbol_by_name.executable << ", "; + out << "0x" << std::hex << (uint64_t)api_data.args.hsa_executable_get_symbol_by_name.symbol_name << ", "; + out << api_data.args.hsa_executable_get_symbol_by_name.agent << ", "; + out << api_data.args.hsa_executable_get_symbol_by_name.symbol; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_iterate_agent_symbols: { + out << "hsa_executable_iterate_agent_symbols("; + out << api_data.args.hsa_executable_iterate_agent_symbols.executable << ", "; + out << api_data.args.hsa_executable_iterate_agent_symbols.agent << ", "; + out << api_data.args.hsa_executable_iterate_agent_symbols.callback << ", "; + out << api_data.args.hsa_executable_iterate_agent_symbols.data; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_executable_iterate_program_symbols: { + out << "hsa_executable_iterate_program_symbols("; + out << api_data.args.hsa_executable_iterate_program_symbols.executable << ", "; + out << api_data.args.hsa_executable_iterate_program_symbols.callback << ", "; + out << api_data.args.hsa_executable_iterate_program_symbols.data; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + + /* block: AmdExt API */ + case HSA_API_ID_hsa_amd_coherency_get_type: { + out << "hsa_amd_coherency_get_type("; + out << api_data.args.hsa_amd_coherency_get_type.agent << ", "; + out << api_data.args.hsa_amd_coherency_get_type.type; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_coherency_set_type: { + out << "hsa_amd_coherency_set_type("; + out << api_data.args.hsa_amd_coherency_set_type.agent << ", "; + out << api_data.args.hsa_amd_coherency_set_type.type; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_profiling_set_profiler_enabled: { + out << "hsa_amd_profiling_set_profiler_enabled("; + out << api_data.args.hsa_amd_profiling_set_profiler_enabled.queue << ", "; + out << api_data.args.hsa_amd_profiling_set_profiler_enabled.enable; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_profiling_async_copy_enable: { + out << "hsa_amd_profiling_async_copy_enable("; + out << api_data.args.hsa_amd_profiling_async_copy_enable.enable; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_profiling_get_dispatch_time: { + out << "hsa_amd_profiling_get_dispatch_time("; + out << api_data.args.hsa_amd_profiling_get_dispatch_time.agent << ", "; + out << api_data.args.hsa_amd_profiling_get_dispatch_time.signal << ", "; + out << api_data.args.hsa_amd_profiling_get_dispatch_time.time; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_profiling_get_async_copy_time: { + out << "hsa_amd_profiling_get_async_copy_time("; + out << api_data.args.hsa_amd_profiling_get_async_copy_time.signal << ", "; + out << api_data.args.hsa_amd_profiling_get_async_copy_time.time; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_profiling_convert_tick_to_system_domain: { + out << "hsa_amd_profiling_convert_tick_to_system_domain("; + out << api_data.args.hsa_amd_profiling_convert_tick_to_system_domain.agent << ", "; + out << api_data.args.hsa_amd_profiling_convert_tick_to_system_domain.agent_tick << ", "; + out << api_data.args.hsa_amd_profiling_convert_tick_to_system_domain.system_tick; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_signal_async_handler: { + out << "hsa_amd_signal_async_handler("; + out << api_data.args.hsa_amd_signal_async_handler.signal << ", "; + out << api_data.args.hsa_amd_signal_async_handler.cond << ", "; + out << api_data.args.hsa_amd_signal_async_handler.value << ", "; + out << api_data.args.hsa_amd_signal_async_handler.handler << ", "; + out << api_data.args.hsa_amd_signal_async_handler.arg; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_async_function: { + out << "hsa_amd_async_function("; + out << api_data.args.hsa_amd_async_function.callback << ", "; + out << api_data.args.hsa_amd_async_function.arg; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_signal_wait_any: { + out << "hsa_amd_signal_wait_any("; + out << api_data.args.hsa_amd_signal_wait_any.signal_count << ", "; + out << api_data.args.hsa_amd_signal_wait_any.signals << ", "; + out << api_data.args.hsa_amd_signal_wait_any.conds << ", "; + out << api_data.args.hsa_amd_signal_wait_any.values << ", "; + out << api_data.args.hsa_amd_signal_wait_any.timeout_hint << ", "; + out << api_data.args.hsa_amd_signal_wait_any.wait_hint << ", "; + out << api_data.args.hsa_amd_signal_wait_any.satisfying_value; + out << ") = " << api_data.uint32_t_retval; + break; + } + case HSA_API_ID_hsa_amd_queue_cu_set_mask: { + out << "hsa_amd_queue_cu_set_mask("; + out << api_data.args.hsa_amd_queue_cu_set_mask.queue << ", "; + out << api_data.args.hsa_amd_queue_cu_set_mask.num_cu_mask_count << ", "; + out << api_data.args.hsa_amd_queue_cu_set_mask.cu_mask; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_memory_pool_get_info: { + out << "hsa_amd_memory_pool_get_info("; + out << api_data.args.hsa_amd_memory_pool_get_info.memory_pool << ", "; + out << api_data.args.hsa_amd_memory_pool_get_info.attribute << ", "; + out << api_data.args.hsa_amd_memory_pool_get_info.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_agent_iterate_memory_pools: { + out << "hsa_amd_agent_iterate_memory_pools("; + out << api_data.args.hsa_amd_agent_iterate_memory_pools.agent << ", "; + out << api_data.args.hsa_amd_agent_iterate_memory_pools.callback << ", "; + out << api_data.args.hsa_amd_agent_iterate_memory_pools.data; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_memory_pool_allocate: { + out << "hsa_amd_memory_pool_allocate("; + out << api_data.args.hsa_amd_memory_pool_allocate.memory_pool << ", "; + out << api_data.args.hsa_amd_memory_pool_allocate.size << ", "; + out << api_data.args.hsa_amd_memory_pool_allocate.flags << ", "; + out << api_data.args.hsa_amd_memory_pool_allocate.ptr; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_memory_pool_free: { + out << "hsa_amd_memory_pool_free("; + out << api_data.args.hsa_amd_memory_pool_free.ptr; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_memory_async_copy: { + out << "hsa_amd_memory_async_copy("; + out << api_data.args.hsa_amd_memory_async_copy.dst << ", "; + out << api_data.args.hsa_amd_memory_async_copy.dst_agent << ", "; + out << api_data.args.hsa_amd_memory_async_copy.src << ", "; + out << api_data.args.hsa_amd_memory_async_copy.src_agent << ", "; + out << api_data.args.hsa_amd_memory_async_copy.size << ", "; + out << api_data.args.hsa_amd_memory_async_copy.num_dep_signals << ", "; + out << api_data.args.hsa_amd_memory_async_copy.dep_signals << ", "; + out << api_data.args.hsa_amd_memory_async_copy.completion_signal; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_memory_async_copy_on_engine: { + out << "hsa_amd_memory_async_copy_on_engine("; + out << api_data.args.hsa_amd_memory_async_copy_on_engine.dst << ", "; + out << api_data.args.hsa_amd_memory_async_copy_on_engine.dst_agent << ", "; + out << api_data.args.hsa_amd_memory_async_copy_on_engine.src << ", "; + out << api_data.args.hsa_amd_memory_async_copy_on_engine.src_agent << ", "; + out << api_data.args.hsa_amd_memory_async_copy_on_engine.size << ", "; + out << api_data.args.hsa_amd_memory_async_copy_on_engine.num_dep_signals << ", "; + out << api_data.args.hsa_amd_memory_async_copy_on_engine.dep_signals << ", "; + out << api_data.args.hsa_amd_memory_async_copy_on_engine.completion_signal << ", "; + out << api_data.args.hsa_amd_memory_async_copy_on_engine.engine_id << ", "; + out << api_data.args.hsa_amd_memory_async_copy_on_engine.force_copy_on_sdma; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_memory_copy_engine_status: { + out << "hsa_amd_memory_copy_engine_status("; + out << api_data.args.hsa_amd_memory_copy_engine_status.dst_agent << ", "; + out << api_data.args.hsa_amd_memory_copy_engine_status.src_agent << ", "; + out << api_data.args.hsa_amd_memory_copy_engine_status.engine_ids_mask; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_agent_memory_pool_get_info: { + out << "hsa_amd_agent_memory_pool_get_info("; + out << api_data.args.hsa_amd_agent_memory_pool_get_info.agent << ", "; + out << api_data.args.hsa_amd_agent_memory_pool_get_info.memory_pool << ", "; + out << api_data.args.hsa_amd_agent_memory_pool_get_info.attribute << ", "; + out << api_data.args.hsa_amd_agent_memory_pool_get_info.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_agents_allow_access: { + out << "hsa_amd_agents_allow_access("; + out << api_data.args.hsa_amd_agents_allow_access.num_agents << ", "; + out << api_data.args.hsa_amd_agents_allow_access.agents << ", "; + out << api_data.args.hsa_amd_agents_allow_access.flags << ", "; + out << api_data.args.hsa_amd_agents_allow_access.ptr; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_memory_pool_can_migrate: { + out << "hsa_amd_memory_pool_can_migrate("; + out << api_data.args.hsa_amd_memory_pool_can_migrate.src_memory_pool << ", "; + out << api_data.args.hsa_amd_memory_pool_can_migrate.dst_memory_pool << ", "; + out << api_data.args.hsa_amd_memory_pool_can_migrate.result; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_memory_migrate: { + out << "hsa_amd_memory_migrate("; + out << api_data.args.hsa_amd_memory_migrate.ptr << ", "; + out << api_data.args.hsa_amd_memory_migrate.memory_pool << ", "; + out << api_data.args.hsa_amd_memory_migrate.flags; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_memory_lock: { + out << "hsa_amd_memory_lock("; + out << api_data.args.hsa_amd_memory_lock.host_ptr << ", "; + out << api_data.args.hsa_amd_memory_lock.size << ", "; + out << api_data.args.hsa_amd_memory_lock.agents << ", "; + out << api_data.args.hsa_amd_memory_lock.num_agent << ", "; + out << api_data.args.hsa_amd_memory_lock.agent_ptr; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_memory_unlock: { + out << "hsa_amd_memory_unlock("; + out << api_data.args.hsa_amd_memory_unlock.host_ptr; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_memory_fill: { + out << "hsa_amd_memory_fill("; + out << api_data.args.hsa_amd_memory_fill.ptr << ", "; + out << api_data.args.hsa_amd_memory_fill.value << ", "; + out << api_data.args.hsa_amd_memory_fill.count; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_interop_map_buffer: { + out << "hsa_amd_interop_map_buffer("; + out << api_data.args.hsa_amd_interop_map_buffer.num_agents << ", "; + out << api_data.args.hsa_amd_interop_map_buffer.agents << ", "; + out << api_data.args.hsa_amd_interop_map_buffer.interop_handle << ", "; + out << api_data.args.hsa_amd_interop_map_buffer.flags << ", "; + out << api_data.args.hsa_amd_interop_map_buffer.size << ", "; + out << api_data.args.hsa_amd_interop_map_buffer.ptr << ", "; + out << api_data.args.hsa_amd_interop_map_buffer.metadata_size << ", "; + out << api_data.args.hsa_amd_interop_map_buffer.metadata; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_interop_unmap_buffer: { + out << "hsa_amd_interop_unmap_buffer("; + out << api_data.args.hsa_amd_interop_unmap_buffer.ptr; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_image_create: { + out << "hsa_amd_image_create("; + out << api_data.args.hsa_amd_image_create.agent << ", "; + out << api_data.args.hsa_amd_image_create.image_descriptor << ", "; + out << api_data.args.hsa_amd_image_create.image_layout << ", "; + out << api_data.args.hsa_amd_image_create.image_data << ", "; + out << api_data.args.hsa_amd_image_create.access_permission << ", "; + out << api_data.args.hsa_amd_image_create.image; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_pointer_info: { + out << "hsa_amd_pointer_info("; + out << api_data.args.hsa_amd_pointer_info.ptr << ", "; + out << api_data.args.hsa_amd_pointer_info.info << ", "; + out << api_data.args.hsa_amd_pointer_info.alloc << ", "; + out << api_data.args.hsa_amd_pointer_info.num_agents_accessible << ", "; + out << api_data.args.hsa_amd_pointer_info.accessible; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_pointer_info_set_userdata: { + out << "hsa_amd_pointer_info_set_userdata("; + out << api_data.args.hsa_amd_pointer_info_set_userdata.ptr << ", "; + out << api_data.args.hsa_amd_pointer_info_set_userdata.userdata; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_ipc_memory_create: { + out << "hsa_amd_ipc_memory_create("; + out << api_data.args.hsa_amd_ipc_memory_create.ptr << ", "; + out << api_data.args.hsa_amd_ipc_memory_create.len << ", "; + out << api_data.args.hsa_amd_ipc_memory_create.handle; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_ipc_memory_attach: { + out << "hsa_amd_ipc_memory_attach("; + out << api_data.args.hsa_amd_ipc_memory_attach.handle << ", "; + out << api_data.args.hsa_amd_ipc_memory_attach.len << ", "; + out << api_data.args.hsa_amd_ipc_memory_attach.num_agents << ", "; + out << api_data.args.hsa_amd_ipc_memory_attach.mapping_agents << ", "; + out << api_data.args.hsa_amd_ipc_memory_attach.mapped_ptr; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_ipc_memory_detach: { + out << "hsa_amd_ipc_memory_detach("; + out << api_data.args.hsa_amd_ipc_memory_detach.mapped_ptr; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_signal_create: { + out << "hsa_amd_signal_create("; + out << api_data.args.hsa_amd_signal_create.initial_value << ", "; + out << api_data.args.hsa_amd_signal_create.num_consumers << ", "; + out << api_data.args.hsa_amd_signal_create.consumers << ", "; + out << api_data.args.hsa_amd_signal_create.attributes << ", "; + out << api_data.args.hsa_amd_signal_create.signal; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_ipc_signal_create: { + out << "hsa_amd_ipc_signal_create("; + out << api_data.args.hsa_amd_ipc_signal_create.signal << ", "; + out << api_data.args.hsa_amd_ipc_signal_create.handle; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_ipc_signal_attach: { + out << "hsa_amd_ipc_signal_attach("; + out << api_data.args.hsa_amd_ipc_signal_attach.handle << ", "; + out << api_data.args.hsa_amd_ipc_signal_attach.signal; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_register_system_event_handler: { + out << "hsa_amd_register_system_event_handler("; + out << api_data.args.hsa_amd_register_system_event_handler.callback << ", "; + out << api_data.args.hsa_amd_register_system_event_handler.data; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_queue_intercept_create: { + out << "hsa_amd_queue_intercept_create("; + out << api_data.args.hsa_amd_queue_intercept_create.agent_handle << ", "; + out << api_data.args.hsa_amd_queue_intercept_create.size << ", "; + out << api_data.args.hsa_amd_queue_intercept_create.type << ", "; + out << api_data.args.hsa_amd_queue_intercept_create.callback << ", "; + out << api_data.args.hsa_amd_queue_intercept_create.data << ", "; + out << api_data.args.hsa_amd_queue_intercept_create.private_segment_size << ", "; + out << api_data.args.hsa_amd_queue_intercept_create.group_segment_size << ", "; + out << api_data.args.hsa_amd_queue_intercept_create.queue; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_queue_intercept_register: { + out << "hsa_amd_queue_intercept_register("; + out << api_data.args.hsa_amd_queue_intercept_register.queue << ", "; + out << api_data.args.hsa_amd_queue_intercept_register.callback << ", "; + out << api_data.args.hsa_amd_queue_intercept_register.user_data; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_queue_set_priority: { + out << "hsa_amd_queue_set_priority("; + out << api_data.args.hsa_amd_queue_set_priority.queue << ", "; + out << api_data.args.hsa_amd_queue_set_priority.priority; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_memory_async_copy_rect: { + out << "hsa_amd_memory_async_copy_rect("; + out << api_data.args.hsa_amd_memory_async_copy_rect.dst << ", "; + out << api_data.args.hsa_amd_memory_async_copy_rect.dst_offset << ", "; + out << api_data.args.hsa_amd_memory_async_copy_rect.src << ", "; + out << api_data.args.hsa_amd_memory_async_copy_rect.src_offset << ", "; + out << api_data.args.hsa_amd_memory_async_copy_rect.range << ", "; + out << api_data.args.hsa_amd_memory_async_copy_rect.range__val << ", "; + out << api_data.args.hsa_amd_memory_async_copy_rect.copy_agent << ", "; + out << api_data.args.hsa_amd_memory_async_copy_rect.dir << ", "; + out << api_data.args.hsa_amd_memory_async_copy_rect.num_dep_signals << ", "; + out << api_data.args.hsa_amd_memory_async_copy_rect.dep_signals << ", "; + out << api_data.args.hsa_amd_memory_async_copy_rect.completion_signal; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_runtime_queue_create_register: { + out << "hsa_amd_runtime_queue_create_register("; + out << api_data.args.hsa_amd_runtime_queue_create_register.callback << ", "; + out << api_data.args.hsa_amd_runtime_queue_create_register.user_data; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_memory_lock_to_pool: { + out << "hsa_amd_memory_lock_to_pool("; + out << api_data.args.hsa_amd_memory_lock_to_pool.host_ptr << ", "; + out << api_data.args.hsa_amd_memory_lock_to_pool.size << ", "; + out << api_data.args.hsa_amd_memory_lock_to_pool.agents << ", "; + out << api_data.args.hsa_amd_memory_lock_to_pool.num_agent << ", "; + out << api_data.args.hsa_amd_memory_lock_to_pool.pool << ", "; + out << api_data.args.hsa_amd_memory_lock_to_pool.flags << ", "; + out << api_data.args.hsa_amd_memory_lock_to_pool.agent_ptr; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_register_deallocation_callback: { + out << "hsa_amd_register_deallocation_callback("; + out << api_data.args.hsa_amd_register_deallocation_callback.ptr << ", "; + out << api_data.args.hsa_amd_register_deallocation_callback.callback << ", "; + out << api_data.args.hsa_amd_register_deallocation_callback.user_data; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_deregister_deallocation_callback: { + out << "hsa_amd_deregister_deallocation_callback("; + out << api_data.args.hsa_amd_deregister_deallocation_callback.ptr << ", "; + out << api_data.args.hsa_amd_deregister_deallocation_callback.callback; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_signal_value_pointer: { + out << "hsa_amd_signal_value_pointer("; + out << api_data.args.hsa_amd_signal_value_pointer.signal << ", "; + out << api_data.args.hsa_amd_signal_value_pointer.value_ptr; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_svm_attributes_set: { + out << "hsa_amd_svm_attributes_set("; + out << api_data.args.hsa_amd_svm_attributes_set.ptr << ", "; + out << api_data.args.hsa_amd_svm_attributes_set.size << ", "; + out << api_data.args.hsa_amd_svm_attributes_set.attribute_list << ", "; + out << api_data.args.hsa_amd_svm_attributes_set.attribute_count; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_svm_attributes_get: { + out << "hsa_amd_svm_attributes_get("; + out << api_data.args.hsa_amd_svm_attributes_get.ptr << ", "; + out << api_data.args.hsa_amd_svm_attributes_get.size << ", "; + out << api_data.args.hsa_amd_svm_attributes_get.attribute_list << ", "; + out << api_data.args.hsa_amd_svm_attributes_get.attribute_count; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_svm_prefetch_async: { + out << "hsa_amd_svm_prefetch_async("; + out << api_data.args.hsa_amd_svm_prefetch_async.ptr << ", "; + out << api_data.args.hsa_amd_svm_prefetch_async.size << ", "; + out << api_data.args.hsa_amd_svm_prefetch_async.agent << ", "; + out << api_data.args.hsa_amd_svm_prefetch_async.num_dep_signals << ", "; + out << api_data.args.hsa_amd_svm_prefetch_async.dep_signals << ", "; + out << api_data.args.hsa_amd_svm_prefetch_async.completion_signal; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_spm_acquire: { + out << "hsa_amd_spm_acquire("; + out << api_data.args.hsa_amd_spm_acquire.preferred_agent; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_spm_release: { + out << "hsa_amd_spm_release("; + out << api_data.args.hsa_amd_spm_release.preferred_agent; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_spm_set_dest_buffer: { + out << "hsa_amd_spm_set_dest_buffer("; + out << api_data.args.hsa_amd_spm_set_dest_buffer.preferred_agent << ", "; + out << api_data.args.hsa_amd_spm_set_dest_buffer.size_in_bytes << ", "; + out << api_data.args.hsa_amd_spm_set_dest_buffer.timeout << ", "; + out << api_data.args.hsa_amd_spm_set_dest_buffer.size_copied << ", "; + out << api_data.args.hsa_amd_spm_set_dest_buffer.dest << ", "; + out << api_data.args.hsa_amd_spm_set_dest_buffer.is_data_loss; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_queue_cu_get_mask: { + out << "hsa_amd_queue_cu_get_mask("; + out << api_data.args.hsa_amd_queue_cu_get_mask.queue << ", "; + out << api_data.args.hsa_amd_queue_cu_get_mask.num_cu_mask_count << ", "; + out << api_data.args.hsa_amd_queue_cu_get_mask.cu_mask; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_portable_export_dmabuf: { + out << "hsa_amd_portable_export_dmabuf("; + out << api_data.args.hsa_amd_portable_export_dmabuf.ptr << ", "; + out << api_data.args.hsa_amd_portable_export_dmabuf.size << ", "; + out << api_data.args.hsa_amd_portable_export_dmabuf.dmabuf << ", "; + out << api_data.args.hsa_amd_portable_export_dmabuf.offset; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_portable_close_dmabuf: { + out << "hsa_amd_portable_close_dmabuf("; + out << api_data.args.hsa_amd_portable_close_dmabuf.dmabuf; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_vmem_address_reserve: { + out << "hsa_amd_vmem_address_reserve("; + out << api_data.args.hsa_amd_vmem_address_reserve.va << ", "; + out << api_data.args.hsa_amd_vmem_address_reserve.size << ", "; + out << api_data.args.hsa_amd_vmem_address_reserve.address << ", "; + out << api_data.args.hsa_amd_vmem_address_reserve.flags; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_vmem_address_free: { + out << "hsa_amd_vmem_address_free("; + out << api_data.args.hsa_amd_vmem_address_free.va << ", "; + out << api_data.args.hsa_amd_vmem_address_free.size; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_vmem_handle_create: { + out << "hsa_amd_vmem_handle_create("; + out << api_data.args.hsa_amd_vmem_handle_create.pool << ", "; + out << api_data.args.hsa_amd_vmem_handle_create.size << ", "; + out << api_data.args.hsa_amd_vmem_handle_create.type << ", "; + out << api_data.args.hsa_amd_vmem_handle_create.flags << ", "; + out << api_data.args.hsa_amd_vmem_handle_create.memory_handle; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_vmem_handle_release: { + out << "hsa_amd_vmem_handle_release("; + out << api_data.args.hsa_amd_vmem_handle_release.memory_handle; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_vmem_map: { + out << "hsa_amd_vmem_map("; + out << api_data.args.hsa_amd_vmem_map.va << ", "; + out << api_data.args.hsa_amd_vmem_map.size << ", "; + out << api_data.args.hsa_amd_vmem_map.in_offset << ", "; + out << api_data.args.hsa_amd_vmem_map.memory_handle << ", "; + out << api_data.args.hsa_amd_vmem_map.flags; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_vmem_unmap: { + out << "hsa_amd_vmem_unmap("; + out << api_data.args.hsa_amd_vmem_unmap.va << ", "; + out << api_data.args.hsa_amd_vmem_unmap.size; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_vmem_set_access: { + out << "hsa_amd_vmem_set_access("; + out << api_data.args.hsa_amd_vmem_set_access.va << ", "; + out << api_data.args.hsa_amd_vmem_set_access.size << ", "; + out << api_data.args.hsa_amd_vmem_set_access.desc << ", "; + out << api_data.args.hsa_amd_vmem_set_access.desc_cnt; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_vmem_get_access: { + out << "hsa_amd_vmem_get_access("; + out << api_data.args.hsa_amd_vmem_get_access.va << ", "; + out << api_data.args.hsa_amd_vmem_get_access.perms << ", "; + out << api_data.args.hsa_amd_vmem_get_access.agent_handle; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_vmem_export_shareable_handle: { + out << "hsa_amd_vmem_export_shareable_handle("; + out << api_data.args.hsa_amd_vmem_export_shareable_handle.dmabuf_fd << ", "; + out << api_data.args.hsa_amd_vmem_export_shareable_handle.handle << ", "; + out << api_data.args.hsa_amd_vmem_export_shareable_handle.flags; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_vmem_import_shareable_handle: { + out << "hsa_amd_vmem_import_shareable_handle("; + out << api_data.args.hsa_amd_vmem_import_shareable_handle.dmabuf_fd << ", "; + out << api_data.args.hsa_amd_vmem_import_shareable_handle.handle; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_vmem_retain_alloc_handle: { + out << "hsa_amd_vmem_retain_alloc_handle("; + out << api_data.args.hsa_amd_vmem_retain_alloc_handle.memory_handle << ", "; + out << api_data.args.hsa_amd_vmem_retain_alloc_handle.addr; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_vmem_get_alloc_properties_from_handle: { + out << "hsa_amd_vmem_get_alloc_properties_from_handle("; + out << api_data.args.hsa_amd_vmem_get_alloc_properties_from_handle.memory_handle << ", "; + out << api_data.args.hsa_amd_vmem_get_alloc_properties_from_handle.pool << ", "; + out << api_data.args.hsa_amd_vmem_get_alloc_properties_from_handle.type; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_agent_set_async_scratch_limit: { + out << "hsa_amd_agent_set_async_scratch_limit("; + out << api_data.args.hsa_amd_agent_set_async_scratch_limit.agent << ", "; + out << api_data.args.hsa_amd_agent_set_async_scratch_limit.threshold; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_queue_get_info: { + out << "hsa_amd_queue_get_info("; + out << api_data.args.hsa_amd_queue_get_info.queue << ", "; + out << api_data.args.hsa_amd_queue_get_info.attribute << ", "; + out << api_data.args.hsa_amd_queue_get_info.value; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_amd_vmem_address_reserve_align: { + out << "hsa_amd_vmem_address_reserve_align("; + out << api_data.args.hsa_amd_vmem_address_reserve_align.va << ", "; + out << api_data.args.hsa_amd_vmem_address_reserve_align.size << ", "; + out << api_data.args.hsa_amd_vmem_address_reserve_align.address << ", "; + out << api_data.args.hsa_amd_vmem_address_reserve_align.alignment << ", "; + out << api_data.args.hsa_amd_vmem_address_reserve_align.flags; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + + /* block: ImageExt API */ + case HSA_API_ID_hsa_ext_image_get_capability: { + out << "hsa_ext_image_get_capability("; + out << api_data.args.hsa_ext_image_get_capability.agent << ", "; + out << api_data.args.hsa_ext_image_get_capability.geometry << ", "; + out << api_data.args.hsa_ext_image_get_capability.image_format << ", "; + out << api_data.args.hsa_ext_image_get_capability.capability_mask; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_ext_image_data_get_info: { + out << "hsa_ext_image_data_get_info("; + out << api_data.args.hsa_ext_image_data_get_info.agent << ", "; + out << api_data.args.hsa_ext_image_data_get_info.image_descriptor << ", "; + out << api_data.args.hsa_ext_image_data_get_info.access_permission << ", "; + out << api_data.args.hsa_ext_image_data_get_info.image_data_info; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_ext_image_create: { + out << "hsa_ext_image_create("; + out << api_data.args.hsa_ext_image_create.agent << ", "; + out << api_data.args.hsa_ext_image_create.image_descriptor << ", "; + out << api_data.args.hsa_ext_image_create.image_data << ", "; + out << api_data.args.hsa_ext_image_create.access_permission << ", "; + out << api_data.args.hsa_ext_image_create.image; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_ext_image_import: { + out << "hsa_ext_image_import("; + out << api_data.args.hsa_ext_image_import.agent << ", "; + out << api_data.args.hsa_ext_image_import.src_memory << ", "; + out << api_data.args.hsa_ext_image_import.src_row_pitch << ", "; + out << api_data.args.hsa_ext_image_import.src_slice_pitch << ", "; + out << api_data.args.hsa_ext_image_import.dst_image << ", "; + out << api_data.args.hsa_ext_image_import.image_region; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_ext_image_export: { + out << "hsa_ext_image_export("; + out << api_data.args.hsa_ext_image_export.agent << ", "; + out << api_data.args.hsa_ext_image_export.src_image << ", "; + out << api_data.args.hsa_ext_image_export.dst_memory << ", "; + out << api_data.args.hsa_ext_image_export.dst_row_pitch << ", "; + out << api_data.args.hsa_ext_image_export.dst_slice_pitch << ", "; + out << api_data.args.hsa_ext_image_export.image_region; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_ext_image_copy: { + out << "hsa_ext_image_copy("; + out << api_data.args.hsa_ext_image_copy.agent << ", "; + out << api_data.args.hsa_ext_image_copy.src_image << ", "; + out << api_data.args.hsa_ext_image_copy.src_offset << ", "; + out << api_data.args.hsa_ext_image_copy.dst_image << ", "; + out << api_data.args.hsa_ext_image_copy.dst_offset << ", "; + out << api_data.args.hsa_ext_image_copy.range; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_ext_image_clear: { + out << "hsa_ext_image_clear("; + out << api_data.args.hsa_ext_image_clear.agent << ", "; + out << api_data.args.hsa_ext_image_clear.image << ", "; + out << api_data.args.hsa_ext_image_clear.data << ", "; + out << api_data.args.hsa_ext_image_clear.image_region; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_ext_image_destroy: { + out << "hsa_ext_image_destroy("; + out << api_data.args.hsa_ext_image_destroy.agent << ", "; + out << api_data.args.hsa_ext_image_destroy.image; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_ext_sampler_create: { + out << "hsa_ext_sampler_create("; + out << api_data.args.hsa_ext_sampler_create.agent << ", "; + out << api_data.args.hsa_ext_sampler_create.sampler_descriptor << ", "; + out << api_data.args.hsa_ext_sampler_create.sampler; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_ext_sampler_destroy: { + out << "hsa_ext_sampler_destroy("; + out << api_data.args.hsa_ext_sampler_destroy.agent << ", "; + out << api_data.args.hsa_ext_sampler_destroy.sampler; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_ext_image_get_capability_with_layout: { + out << "hsa_ext_image_get_capability_with_layout("; + out << api_data.args.hsa_ext_image_get_capability_with_layout.agent << ", "; + out << api_data.args.hsa_ext_image_get_capability_with_layout.geometry << ", "; + out << api_data.args.hsa_ext_image_get_capability_with_layout.image_format << ", "; + out << api_data.args.hsa_ext_image_get_capability_with_layout.image_data_layout << ", "; + out << api_data.args.hsa_ext_image_get_capability_with_layout.capability_mask; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_ext_image_data_get_info_with_layout: { + out << "hsa_ext_image_data_get_info_with_layout("; + out << api_data.args.hsa_ext_image_data_get_info_with_layout.agent << ", "; + out << api_data.args.hsa_ext_image_data_get_info_with_layout.image_descriptor << ", "; + out << api_data.args.hsa_ext_image_data_get_info_with_layout.access_permission << ", "; + out << api_data.args.hsa_ext_image_data_get_info_with_layout.image_data_layout << ", "; + out << api_data.args.hsa_ext_image_data_get_info_with_layout.image_data_row_pitch << ", "; + out << api_data.args.hsa_ext_image_data_get_info_with_layout.image_data_slice_pitch << ", "; + out << api_data.args.hsa_ext_image_data_get_info_with_layout.image_data_info; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + case HSA_API_ID_hsa_ext_image_create_with_layout: { + out << "hsa_ext_image_create_with_layout("; + out << api_data.args.hsa_ext_image_create_with_layout.agent << ", "; + out << api_data.args.hsa_ext_image_create_with_layout.image_descriptor << ", "; + out << api_data.args.hsa_ext_image_create_with_layout.image_data << ", "; + out << api_data.args.hsa_ext_image_create_with_layout.access_permission << ", "; + out << api_data.args.hsa_ext_image_create_with_layout.image_data_layout << ", "; + out << api_data.args.hsa_ext_image_create_with_layout.image_data_row_pitch << ", "; + out << api_data.args.hsa_ext_image_create_with_layout.image_data_slice_pitch << ", "; + out << api_data.args.hsa_ext_image_create_with_layout.image; + out << ") = " << api_data.hsa_status_t_retval; + break; + } + default: + out << "ERROR: unknown API"; + abort(); + } + return out; +} +#endif +#endif /* HSA_PROF_STR_H_ */ \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/roctracer/roctracer_hcc.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/roctracer/roctracer_hcc.h new file mode 100644 index 0000000000000000000000000000000000000000..969282b7fccf50daab50069a24a82335e237ed9c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/roctracer/roctracer_hcc.h @@ -0,0 +1,24 @@ +/* Copyright (c) 2018-2022 Advanced Micro Devices, Inc. + + 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 message( \ + "This file has been deprecated and marked for removal. Please use roctracer_hip.h instead.") + +#include "roctracer_hip.h" \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/roctracer/roctx.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/roctracer/roctx.h new file mode 100644 index 0000000000000000000000000000000000000000..ccec5a185badb7fc43d625c8987a65ecbe17a6e3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/amd/include/roctracer/roctx.h @@ -0,0 +1,229 @@ +/* Copyright (c) 2018-2022 Advanced Micro Devices, Inc. + + 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. */ + +/** \mainpage ROCTX API Specification + * + * \section introduction Introduction + * ROCTX is a library that implements the AMD code annotation API. It provides + * the support necessary to annotate events and code ranges in applications. + */ + +/** + * \file + * ROCTX API interface. + */ + +#ifndef ROCTX_H_ +#define ROCTX_H_ 1 + +/* Placeholder for calling convention and import/export macros */ +#if !defined(ROCTX_CALL) +#define ROCTX_CALL +#endif /* !defined (ROCTX_CALL) */ + +#if !defined(ROCTX_EXPORT_DECORATOR) +#if defined(__GNUC__) +#define ROCTX_EXPORT_DECORATOR __attribute__((visibility("default"))) +#elif defined(_MSC_VER) +#define ROCTX_EXPORT_DECORATOR __declspec(dllexport) +#endif /* defined (_MSC_VER) */ +#endif /* !defined (ROCTX_EXPORT_DECORATOR) */ + +#if !defined(ROCTX_IMPORT_DECORATOR) +#if defined(__GNUC__) +#define ROCTX_IMPORT_DECORATOR +#elif defined(_MSC_VER) +#define ROCTX_IMPORT_DECORATOR __declspec(dllimport) +#endif /* defined (_MSC_VER) */ +#endif /* !defined (ROCTX_IMPORT_DECORATOR) */ + +#define ROCTX_EXPORT ROCTX_EXPORT_DECORATOR ROCTX_CALL +#define ROCTX_IMPORT ROCTX_IMPORT_DECORATOR ROCTX_CALL + +#if !defined(ROCTX) +#if defined(ROCTX_EXPORTS) +#define ROCTX_API ROCTX_EXPORT +#else /* !defined (ROCTX_EXPORTS) */ +#define ROCTX_API ROCTX_IMPORT +#endif /* !defined (ROCTX_EXPORTS) */ +#endif /* !defined (ROCTX) */ + +#include + +#if defined(__cplusplus) +extern "C" { +#endif /* defined(__cplusplus) */ + +/** \defgroup symbol_versions_group Symbol Versions + * + * The names used for the shared library versioned symbols. + * + * Every function is annotated with one of the version macros defined in this + * section. Each macro specifies a corresponding symbol version string. After + * dynamically loading the shared library with \p dlopen, the address of each + * function can be obtained using \p dlvsym with the name of the function and + * its corresponding symbol version string. An error will be reported by \p + * dlvsym if the installed library does not support the version for the + * function specified in this version of the interface. + * + * @{ + */ + +/** + * The function was introduced in version 4.1 of the interface and has the + * symbol version string of ``"ROCTX_4.1"``. + */ +#define ROCTX_VERSION_4_1 + +/** @} */ + +/** \defgroup versioning_group Versioning + * + * Version information about the interface and the associated installed + * library. + * + * @{ + */ + +/** + * The semantic version of the interface following + * [semver.org][semver] rules. + * + * A client that uses this interface is only compatible with the installed + * library if the major version numbers match and the interface minor version + * number is less than or equal to the installed library minor version number. + */ + +/** + * The major version of the interface as a macro so it can be used by the + * preprocessor. + */ +#define ROCTX_VERSION_MAJOR 4 + +/** + * The minor version of the interface as a macro so it can be used by the + * preprocessor. + */ +#define ROCTX_VERSION_MINOR 1 + +/** + * Query the major version of the installed library. + * + * Return the major version of the installed library. This can be used to check + * if it is compatible with this interface version. + * + * \return Returns the major version number. + */ +ROCTX_API uint32_t roctx_version_major() ROCTX_VERSION_4_1; + +/** + * Query the minor version of the installed library. + * + * Return the minor version of the installed library. This can be used to check + * if it is compatible with this interface version. + * + * \return Returns the minor version number. + */ +ROCTX_API uint32_t roctx_version_minor() ROCTX_VERSION_4_1; + +/** @} */ + +/** \defgroup marker_group ROCTX Markers + * + * Marker annotations are used to describe events in a ROCm application. + * + * @{ + */ + +/** + * Mark an event. + * + * \param[in] message The message associated with the event. + */ +ROCTX_API void roctxMarkA(const char* message) ROCTX_VERSION_4_1; +#define roctxMark(message) roctxMarkA(message) + +/** @} */ + +/** \defgroup range_group ROCTX Ranges + * + * Range annotations are used to describe events in a ROCm application. + * + * @{ + */ + +/** + * Start a new nested range. + * + * Nested ranges are stacked and local to the current CPU thread. + * + * \param[in] message The message associated with this range. + * + * \return Returns the level this nested range is started at. Nested range + * levels are 0 based. + */ +ROCTX_API int roctxRangePushA(const char* message) ROCTX_VERSION_4_1; +#define roctxRangePush(message) roctxRangePushA(message) + +/** + * Stop the current nested range. + * + * Stop the current nested range, and pop it from the stack. If a nested range + * was active before the last one was started, it becomes again the current + * nested range. + * + * \return Returns the level the stopped nested range was started at, or a + * negative value if there was no nested range active. + */ +ROCTX_API int roctxRangePop() ROCTX_VERSION_4_1; + +/** + * ROCTX range ID. + * + * This is the range ID used to identify start/end ranges. + */ +typedef uint64_t roctx_range_id_t; + +/** + * Starts a process range. + * + * Start/stop ranges can be started and stopped in different threads. Each + * timespan is assigned a unique range ID. + * + * \param[in] message The message associated with this range. + * + * \return Returns the ID of the new range. + */ +ROCTX_API roctx_range_id_t roctxRangeStartA(const char* message) + ROCTX_VERSION_4_1; +#define roctxRangeStart(message) roctxRangeStartA(message) + +/** + * Stop a process range. + */ +ROCTX_API void roctxRangeStop(roctx_range_id_t id) ROCTX_VERSION_4_1; + +/** @} */ + +#if defined(__cplusplus) +} /* extern "C" */ +#endif /* defined (__cplusplus) */ + +#endif /* ROCTX_H_ */ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/compiler.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..9bbc5eadbde0a074d2236064a59f12c25865e523 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/compiler.py @@ -0,0 +1,90 @@ +from abc import ABCMeta, abstractmethod +from dataclasses import dataclass +from enum import Enum +from typing import Dict, Union +from types import ModuleType + + +@dataclass(frozen=True) +class GPUTarget(object): + # Target backend, e.g., cuda, hip + backend: str + # Target architecture, e.g., 90 (for cuda compute capability), gfx940 (for hip) + arch: Union[int, str] + warp_size: int + + +class Language(Enum): + """The input language being compiled by the backend.""" + TRITON = 0 + GLUON = 1 + + +class BaseBackend(metaclass=ABCMeta): + + def __init__(self, target: GPUTarget) -> None: + self.target = target + assert self.supports_target(target) + + @staticmethod + @abstractmethod + def supports_target(target: GPUTarget): + raise NotImplementedError + + @abstractmethod + def hash(self) -> str: + """Returns a unique identifier for this backend""" + raise NotImplementedError + + @abstractmethod + def parse_options(self, options: dict) -> object: + """ + Converts an `options` dictionary into an arbitrary object and returns it. + This function may contain target-specific heuristics and check the legality of the provided options + """ + raise NotImplementedError + + @abstractmethod + def add_stages(self, stages: dict, options: object) -> None: + """ + Populates `stages` dictionary with entries of the form: + ir_name [str] => Function[(src: str, metadata: dict) -> str|bytes] + The value of each entry may populate a `metadata` dictionary. + Stages will be run sequentially (in inseriton order) and can communicate using `metadata`. + All stages are expected to return a `str` object, except for the last stage which returns + a `bytes` object for execution by the launcher. + """ + raise NotImplementedError + + @abstractmethod + def load_dialects(self, context): + """ + Load additional MLIR dialects into the provided `context` + """ + raise NotImplementedError + + @abstractmethod + def get_module_map(self) -> Dict[str, ModuleType]: + """ + Return a map of interface modules to their device-specific implementations + """ + raise NotImplementedError + + @staticmethod + def parse_attr(desc): + assert isinstance(desc, str) + ret = [] + if "D" in desc: + ret += [["tt.divisibility", 16]] + return ret + + @staticmethod + def get_arg_specialization(arg, ty, **kwargs): + """ + Return a string unique to each possible specialization of the argument + """ + if ty == "int" and arg % 16 == 0 and kwargs.get("align", False): + return "D" + if ty == "tensor" and arg.data_ptr() % 16 == 0 and kwargs.get("align", False): + return "D" + return "" diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/driver.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/driver.py new file mode 100644 index 0000000000000000000000000000000000000000..13a658b47e48b00fb575d27f6b1c7d59107f6c7c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/driver.py @@ -0,0 +1,66 @@ +from abc import ABCMeta, abstractmethod +from typing import Callable, List, Protocol, Sequence + + +class Benchmarker(Protocol): + + def __call__(self, kernel_call: Callable, *, quantiles: List[float], **kwargs) -> Sequence[float]: + pass + + +class DriverBase(metaclass=ABCMeta): + + @classmethod + @abstractmethod + def is_active(self): + pass + + @abstractmethod + def map_python_to_cpp_type(self, ty: str) -> str: + """ + Converts a Triton type string to its corresponding C++ type string for this backend. + + Args: + ty (str): The Triton type string. e.g., 'i32', '*fp16', 'fp32'. + + Returns: + str: The C++ type string. + """ + pass + + @abstractmethod + def get_current_target(self): + pass + + @abstractmethod + def get_active_torch_device(self): + pass + + @abstractmethod + def get_benchmarker(self) -> Benchmarker: + """ + Return the benchmarking function that this backend should use by default. + """ + raise NotImplementedError + + def __init__(self) -> None: + pass + + +class GPUDriver(DriverBase): + + def __init__(self): + # TODO: support other frameworks than torch + import torch + self.get_device_capability = torch.cuda.get_device_capability + try: + from torch._C import _cuda_getCurrentRawStream + self.get_current_stream = _cuda_getCurrentRawStream + except ImportError: + self.get_current_stream = lambda idx: torch.cuda.current_stream(idx).cuda_stream + self.get_current_device = torch.cuda.current_device + self.set_current_device = torch.cuda.set_device + + # TODO: remove once TMA is cleaned up + def assemble_tensormap_to_arg(self, tensormaps_info, args): + return args diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..902f99021c34e916338c25c14f5461347c188b02 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/__pycache__/compiler.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/__pycache__/compiler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8b22c035088a7d4d29635929acf13dc0a14cecd Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/__pycache__/compiler.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/__pycache__/driver.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/__pycache__/driver.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05f6d40e89442723484b9613b3661243b383f25c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/__pycache__/driver.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/func_macro.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/func_macro.h new file mode 100644 index 0000000000000000000000000000000000000000..633554a01aaabd1bca5ae278c276710f323d5d7b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/func_macro.h @@ -0,0 +1,57 @@ +/* + * NVIDIA_COPYRIGHT_BEGIN + * + * Copyright (c) 2008-2018, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + * + * NVIDIA_COPYRIGHT_END + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/func_macro.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/func_macro.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_FUNC_MACRO_H__ +#endif + +#if !defined(__FUNC_MACRO_H__) +#define __FUNC_MACRO_H__ + +#if !defined(__CUDA_INTERNAL_COMPILATION__) + +#error -- incorrect inclusion of a cudart header file + +#endif /* !__CUDA_INTERNAL_COMPILATION__ */ + +#if defined(__GNUC__) + +#define __func__(decl) \ + inline decl + +#define __device_func__(decl) \ + static __attribute__((__unused__)) decl + +#elif defined(_WIN32) + +#define __func__(decl) \ + static inline decl + +#define __device_func__(decl) \ + static decl + +#endif /* __GNUC__ */ + +#endif /* __FUNC_MACRO_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_FUNC_MACRO_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_FUNC_MACRO_H__ +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/math_functions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/math_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..d8201f97efb3aed940f62360d90899a5171eeb0d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/math_functions.h @@ -0,0 +1,6257 @@ +/* + * Copyright 1993-2024 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/math_functions.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/math_functions.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_MATH_FUNCTIONS_H__ +#endif + +#if !defined(__MATH_FUNCTIONS_H__) +#define __MATH_FUNCTIONS_H__ + +#if defined(__QNX__) && (__GNUC__ >= 5) && defined(__CUDACC__) +#if __has_include(<__config>) +#include <__config> +#endif +#endif + +/** + * \defgroup CUDA_MATH Mathematical Functions + * + * CUDA mathematical functions are always available in device code. + * + * Host implementations of the common mathematical functions are mapped + * in a platform-specific way to standard math library functions, provided + * by the host compiler and respective host libm where available. + * Some functions, not available with the host compilers, are implemented + * in crt/math_functions.hpp header file. + * For example, see ::erfinv(). Other, less common functions, + * like ::rhypot(), ::cyl_bessel_i0() are only available in device code. + * + * CUDA Math device functions are no-throw for well-formed CUDA programs. + * + * Note that many floating-point and integer functions names are + * overloaded for different argument types. For example, the ::log() + * function has the following prototypes: + * \code + * double log(double x); + * float log(float x); + * float logf(float x); + * \endcode + * + * Note also that due to implementation constraints, certain math functions + * from std:: namespace may be callable in device code even via explicitly + * qualified std:: names. However, such use is discouraged, since this + * capability is unsupported, unverified, undocumented, not portable, and + * may change without notice. + */ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#if defined(__cplusplus) && defined(__CUDACC__) + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "host_defines.h" + +//NOTE: For NVRTC, these declarations have been moved into the compiler (to reduce compile time) +#define EXCLUDE_FROM_RTC + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +extern "C" +{ + +/** + * @{ + */ + +/* Define math function DOXYGEN toplevel groups, functions will + be added to these groups later. +*/ +/** + * \defgroup CUDA_MATH_SINGLE Single Precision Mathematical Functions + * This section describes single precision mathematical functions. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + +/** + * \defgroup CUDA_MATH_DOUBLE Double Precision Mathematical Functions + * This section describes double precision mathematical functions. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + +/** + * \defgroup CUDA_MATH_INT Integer Mathematical Functions + * This section describes integer mathematical functions. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + +/** + * \defgroup CUDA_MATH_INTRINSIC_SINGLE Single Precision Intrinsics + * This section describes single precision intrinsic functions that are + * only supported in device code. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + +/** + * \defgroup CUDA_MATH_INTRINSIC_DOUBLE Double Precision Intrinsics + * This section describes double precision intrinsic functions that are + * only supported in device code. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + +/** + * \defgroup CUDA_MATH_INTRINSIC_INT Integer Intrinsics + * This section describes integer intrinsic functions. All of these + * functions are supported in device code. For some of the functions, + * host-specific implementations are also provided. For example, + * see `::__nv_bswap16()`. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + +/** + * \defgroup CUDA_MATH_INTRINSIC_CAST Type Casting Intrinsics + * This section describes type casting intrinsic functions that are + * only supported in device code. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + +/** + * + * \defgroup CUDA_MATH_INTRINSIC_SIMD SIMD Intrinsics + * This section describes SIMD intrinsic functions that are + * only supported in device code. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + + +/** + * @} + */ +#define __DEVICE_FUNCTIONS_DECL__ __host__ __device__ +#if !defined(_MSC_VER) +#define __CUDA_MATH_CRTIMP +#else +#if _MSC_VER < 1900 +#define __CUDA_MATH_CRTIMP _CRTIMP +#else +#define __CUDA_MATH_CRTIMP _ACRTIMP +#endif +#endif + +#if defined(__ANDROID__) && (__ANDROID_API__ <= 20) && !defined(__aarch64__) +static __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ int abs(int); +static __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ long int labs(long int); +static __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ long long int llabs(long long int); +#else /* __ANDROID__ */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the absolute value of the input \p int argument. + * + * Calculate the absolute value of the input argument \p a. + * + * \return + * Returns the absolute value of the input argument. + * - abs(\p INT_MIN) is \p Undefined + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ int __cdecl abs(int a) __THROW; +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the absolute value of the input \p long \p int argument. + * + * Calculate the absolute value of the input argument \p a. + * + * \return + * Returns the absolute value of the input argument. + * - labs(\p LONG_MIN) is \p Undefined + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ long int __cdecl labs(long int a) __THROW; +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the absolute value of the input \p long \p long \p int argument. + * + * Calculate the absolute value of the input argument \p a. + * + * \return + * Returns the absolute value of the input argument. + * - llabs(\p LLONG_MIN) is \p Undefined + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ long long int llabs(long long int a) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} +#endif +#endif /* __ANDROID__ */ + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +/* put all math functions in std */ +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the absolute value of the input argument. + * + * Calculate the absolute value of the input argument \p x. + * + * \return + * Returns the absolute value of the input argument. + * - fabs( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - fabs( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns +0. + * - fabs(NaN) returns an unspecified NaN. + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl fabs(double x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the absolute value of its argument + * + * Calculate the absolute value of the input argument \p x. + * + * \return + * Returns the absolute value of its argument. + * - fabsf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - fabsf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns +0. + * - fabsf(NaN) returns an unspecified NaN. + * + * \note_accuracy_single + */ +#if defined(_WIN32) && defined(_M_ARM64) +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl fabsf(float x) __THROW; +#else +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float fabsf(float x) __THROW; +#endif +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int min(const int a, const int b); +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int umin(const unsigned int a, const unsigned int b); +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p long \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int llmin(const long long int a, const long long int b); +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p long \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned long long int ullmin(const unsigned long long int a, const unsigned long long int b); + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Determine the minimum numeric value of the arguments. + * + * Determines the minimum numeric value of the arguments \p x and \p y. Treats NaN + * arguments as missing data. If one argument is a NaN and the other is legitimate numeric + * value, the numeric value is chosen. + * + * \return + * Returns the minimum numeric value of the arguments \p x and \p y. + * - If both arguments are NaN, returns NaN. + * - If one argument is NaN, returns the numeric argument. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float fminf(float x, float y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl fminf(float x, float y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Determine the minimum numeric value of the arguments. + * + * Determines the minimum numeric value of the arguments \p x and \p y. Treats NaN + * arguments as missing data. If one argument is a NaN and the other is legitimate numeric + * value, the numeric value is chosen. + * + * \return + * Returns the minimum numeric value of the arguments \p x and \p y. + * - If both arguments are NaN, returns NaN. + * - If one argument is NaN, returns the numeric argument. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double fmin(double x, double y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl fmin(double x, double y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int max(const int a, const int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int umax(const unsigned int a, const unsigned int b); +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p long \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int llmax(const long long int a, const long long int b); +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p long \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned long long int ullmax(const unsigned long long int a, const unsigned long long int b); + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Determine the maximum numeric value of the arguments. + * + * Determines the maximum numeric value of the arguments \p x and \p y. Treats NaN + * arguments as missing data. If one argument is a NaN and the other is legitimate numeric + * value, the numeric value is chosen. + * + * \return + * Returns the maximum numeric values of the arguments \p x and \p y. + * - If both arguments are NaN, returns NaN. + * - If one argument is NaN, returns the numeric argument. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float fmaxf(float x, float y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl fmaxf(float x, float y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Determine the maximum numeric value of the arguments. + * + * Determines the maximum numeric value of the arguments \p x and \p y. Treats NaN + * arguments as missing data. If one argument is a NaN and the other is legitimate numeric + * value, the numeric value is chosen. + * + * \return + * Returns the maximum numeric values of the arguments \p x and \p y. + * - If both arguments are NaN, returns NaN. + * - If one argument is NaN, returns the numeric argument. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double fmax(double, double) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl fmax(double, double); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the sine of the input argument. + * + * Calculate the sine of the input argument \p x (measured in radians). + * + * \return + * - sin( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sin( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - sin(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl sin(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the cosine of the input argument. + * + * Calculate the cosine of the input argument \p x (measured in radians). + * + * \return + * - cos( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - cos( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - cos(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl cos(double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the sine and cosine of the first input argument. + * + * Calculate the sine and cosine of the first input argument \p x (measured + * in radians). The results for sine and cosine are written into the + * second argument, \p sptr, and, respectively, third argument, \p cptr. + * + * \see ::sin() and ::cos(). + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ void sincos(double x, double *sptr, double *cptr) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the sine and cosine of the first input argument. + * + * Calculate the sine and cosine of the first input argument \p x (measured + * in radians). The results for sine and cosine are written into the second + * argument, \p sptr, and, respectively, third argument, \p cptr. + * + * \see ::sinf() and ::cosf(). + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ void sincosf(float x, float *sptr, float *cptr) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the tangent of the input argument. + * + * Calculate the tangent of the input argument \p x (measured in radians). + * + * \return + * - tan( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - tan( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - tan(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl tan(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the square root of the input argument. + * + * Calculate the nonnegative square root of \p x, + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula. + * + * \return + * Returns + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula. + * - sqrt( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sqrt( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - sqrt(\p x) returns NaN if \p x is less than 0. + * - sqrt(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl sqrt(double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the reciprocal of the square root of the input argument. + * + * Calculate the reciprocal of the nonnegative square root of \p x, + * \cuda_math_formula 1/\sqrt{x} \end_cuda_math_formula. + * + * \return + * Returns + * \cuda_math_formula 1/\sqrt{x} \end_cuda_math_formula. + * - rsqrt( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - rsqrt( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - rsqrt(\p x) returns NaN if \p x is less than 0. + * - rsqrt(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double rsqrt(double x); + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the reciprocal of the square root of the input argument. + * + * Calculate the reciprocal of the nonnegative square root of \p x, + * \cuda_math_formula 1/\sqrt{x} \end_cuda_math_formula. + * + * \return + * Returns + * \cuda_math_formula 1/\sqrt{x} \end_cuda_math_formula. + * - rsqrtf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - rsqrtf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - rsqrtf(\p x) returns NaN if \p x is less than 0. + * - rsqrtf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float rsqrtf(float x); + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the base 2 logarithm of the input argument. + * + * Calculate the base 2 logarithm of the input argument \p x. + * + * \return + * - log2( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - log2(1) returns +0. + * - log2(\p x) returns NaN for \p x < 0. + * - log2( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - log2(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double log2(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl log2(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the base 2 exponential of the input argument. + * + * Calculate + * \cuda_math_formula 2^x \end_cuda_math_formula +, + * the base 2 exponential of the input argument \p x. + * + * \return + * - exp2( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - exp2( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - exp2( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - exp2(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double exp2(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl exp2(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the base 2 exponential of the input argument. + * + * Calculate + * \cuda_math_formula 2^x \end_cuda_math_formula +, + * the base 2 exponential of the input argument \p x. + * + * \return + * - exp2f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - exp2f( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - exp2f( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - exp2f(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float exp2f(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl exp2f(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the base 10 exponential of the input argument. + * + * Calculate + * \cuda_math_formula 10^x \end_cuda_math_formula +, + * the base 10 exponential of the input argument \p x. + * + * \return + * - exp10( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - exp10( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - exp10( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - exp10(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double exp10(double x) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the base 10 exponential of the input argument. + * + * Calculate + * \cuda_math_formula 10^x \end_cuda_math_formula +, + * the base 10 exponential of the input argument \p x. + * + * \return + * - exp10f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - exp10f( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - exp10f( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - exp10f(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float exp10f(float x) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument, minus 1. + * + * Calculate + * \cuda_math_formula e^x \end_cuda_math_formula + * -1, the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument \p x, minus 1. + * + * \return + * - expm1( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - expm1( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns -1. + * - expm1( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - expm1(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double expm1(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl expm1(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument, minus 1. + * + * Calculate + * \cuda_math_formula e^x \end_cuda_math_formula + * -1, the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument \p x, minus 1. + * + * \return + * - expm1f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - expm1f( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns -1. + * - expm1f( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - expm1f(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float expm1f(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl expm1f(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the base 2 logarithm of the input argument. + * + * Calculate the base 2 logarithm of the input argument \p x. + * + * \return + * - log2f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - log2f(1) returns +0. + * - log2f(\p x) returns NaN for \p x < 0. + * - log2f( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - log2f(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float log2f(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl log2f(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the base 10 logarithm of the input argument. + * + * Calculate the base 10 logarithm of the input argument \p x. + * + * \return + * - log10( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - log10(1) returns +0. + * - log10(\p x) returns NaN for \p x < 0. + * - log10( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - log10(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl log10(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the base + * \cuda_math_formula e \end_cuda_math_formula + * logarithm of the input argument. + * + * Calculate the base + * \cuda_math_formula e \end_cuda_math_formula + * logarithm of the input argument \p x. + * + * \return + * - log( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - log(1) returns +0. + * - log(\p x) returns NaN for \p x < 0. + * - log( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - log(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl log(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of + * \cuda_math_formula \log_{e}(1+x) \end_cuda_math_formula. + * + * Calculate the value of + * \cuda_math_formula \log_{e}(1+x) \end_cuda_math_formula + * of the input argument \p x. + * + * \return + * - log1p( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - log1p(-1) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - log1p(\p x) returns NaN for \p x < -1. + * - log1p( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - log1p(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double log1p(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl log1p(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of + * \cuda_math_formula \log_{e}(1+x) \end_cuda_math_formula. + * + * Calculate the value of + * \cuda_math_formula \log_{e}(1+x) \end_cuda_math_formula + * of the input argument \p x. + * + * \return + * - log1pf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - log1pf(-1) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - log1pf(\p x) returns NaN for \p x < -1. + * - log1pf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - log1pf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float log1pf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl log1pf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the largest integer less than or equal to \p x. + * + * Calculates the largest integer value which is less than or equal to \p x. + * + * \return + * Returns + * \cuda_math_formula \lfloor x \rfloor \end_cuda_math_formula + * expressed as a floating-point number. + * - floor( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - floor( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - floor(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl floor(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument. + * + * Calculate + * \cuda_math_formula e^x \end_cuda_math_formula +, + * the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument \p x. + * + * \return + * - exp( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - exp( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - exp( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - exp(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl exp(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the hyperbolic cosine of the input argument. + * + * Calculate the hyperbolic cosine of the input argument \p x. + * + * \return + * - cosh( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - cosh( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - cosh(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl cosh(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the hyperbolic sine of the input argument. + * + * Calculate the hyperbolic sine of the input argument \p x. + * + * \return + * - sinh( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sinh( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - sinh(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl sinh(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the hyperbolic tangent of the input argument. + * + * Calculate the hyperbolic tangent of the input argument \p x. + * + * \return + * - tanh( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - tanh( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 1 \end_cuda_math_formula. + * - tanh(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl tanh(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the nonnegative inverse hyperbolic cosine of the input argument. + * + * Calculate the nonnegative inverse hyperbolic cosine of the input argument \p x. + * + * \return + * Result will be in the interval [0, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ]. + * - acosh(1) returns 0. + * - acosh(\p x) returns NaN for \p x in the interval [ + * \cuda_math_formula -\infty \end_cuda_math_formula + * , 1). + * - acosh( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - acosh(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double acosh(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl acosh(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the nonnegative inverse hyperbolic cosine of the input argument. + * + * Calculate the nonnegative inverse hyperbolic cosine of the input argument \p x. + * + * \return + * Result will be in the interval [0, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ]. + * - acoshf(1) returns 0. + * - acoshf(\p x) returns NaN for \p x in the interval [ + * \cuda_math_formula -\infty \end_cuda_math_formula + * , 1). + * - acoshf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - acoshf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float acoshf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl acoshf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the inverse hyperbolic sine of the input argument. + * + * Calculate the inverse hyperbolic sine of the input argument \p x. + * + * \return + * - asinh( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - asinh( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - asinh(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double asinh(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl asinh(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the inverse hyperbolic sine of the input argument. + * + * Calculate the inverse hyperbolic sine of the input argument \p x. + * + * \return + * - asinhf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - asinhf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - asinhf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float asinhf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl asinhf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the inverse hyperbolic tangent of the input argument. + * + * Calculate the inverse hyperbolic tangent of the input argument \p x. + * + * \return + * - atanh( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - atanh( + * \cuda_math_formula \pm 1 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - atanh(\p x) returns NaN for \p x outside interval [-1, 1]. + * - atanh(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double atanh(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl atanh(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the inverse hyperbolic tangent of the input argument. + * + * Calculate the inverse hyperbolic tangent of the input argument \p x. + * + * \return + * - atanhf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - atanhf( + * \cuda_math_formula \pm 1 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - atanhf(\p x) returns NaN for \p x outside interval [-1, 1]. + * - atanhf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float atanhf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl atanhf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of + * \cuda_math_formula x\cdot 2^{exp} \end_cuda_math_formula. + * + * Calculate the value of + * \cuda_math_formula x\cdot 2^{exp} \end_cuda_math_formula + * of the input arguments \p x and \p exp. + * + * \return + * - ldexp(\p x, \p exp) is equivalent to scalbn(\p x, \p exp). + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl ldexp(double x, int exp) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of + * \cuda_math_formula x\cdot 2^{exp} \end_cuda_math_formula. + * + * Calculate the value of + * \cuda_math_formula x\cdot 2^{exp} \end_cuda_math_formula + * of the input arguments \p x and \p exp. + * + * \return + * - ldexpf(\p x, \p exp) is equivalent to scalbnf(\p x, \p exp). + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float ldexpf(float x, int exp) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the floating-point representation of the exponent of the input argument. + * + * Calculate the floating-point representation of the exponent of the input argument \p x. + * + * \return + * - logb( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - logb( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - logb(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double logb(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl logb(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the floating-point representation of the exponent of the input argument. + * + * Calculate the floating-point representation of the exponent of the input argument \p x. + * + * \return + * - logbf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - logbf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - logbf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float logbf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl logbf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Compute the unbiased integer exponent of the argument. + * + * Calculates the unbiased integer exponent of the input argument \p x. + * + * \return + * - If successful, returns the unbiased exponent of the argument. + * - ilogb( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns INT_MIN. + * - ilogb(NaN) returns INT_MIN. + * - ilogb( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns INT_MAX. + * - Note: above behavior does not take into account FP_ILOGB0 nor FP_ILOGBNAN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int ilogb(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP int __cdecl ilogb(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Compute the unbiased integer exponent of the argument. + * + * Calculates the unbiased integer exponent of the input argument \p x. + * + * \return + * - If successful, returns the unbiased exponent of the argument. + * - ilogbf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns INT_MIN. + * - ilogbf(NaN) returns INT_MIN. + * - ilogbf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns INT_MAX. + * - Note: above behavior does not take into account FP_ILOGB0 nor FP_ILOGBNAN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int ilogbf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP int __cdecl ilogbf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Scale floating-point input by integer power of two. + * + * Scale \p x by + * \cuda_math_formula 2^n \end_cuda_math_formula + * by efficient manipulation of the floating-point + * exponent. + * + * \return + * Returns \p x * + * \cuda_math_formula 2^n \end_cuda_math_formula. + * - scalbn( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - scalbn(\p x, 0) returns \p x. + * - scalbn( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - scalbn(NaN, \p n) returns NaN. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double scalbn(double x, int n) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl scalbn(double x, int n); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Scale floating-point input by integer power of two. + * + * Scale \p x by + * \cuda_math_formula 2^n \end_cuda_math_formula + * by efficient manipulation of the floating-point + * exponent. + * + * \return + * Returns \p x * + * \cuda_math_formula 2^n \end_cuda_math_formula. + * - scalbnf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - scalbnf(\p x, 0) returns \p x. + * - scalbnf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - scalbnf(NaN, \p n) returns NaN. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float scalbnf(float x, int n) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl scalbnf(float x, int n); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Scale floating-point input by integer power of two. + * + * Scale \p x by + * \cuda_math_formula 2^n \end_cuda_math_formula + * by efficient manipulation of the floating-point + * exponent. + * + * \return + * Returns \p x * + * \cuda_math_formula 2^n \end_cuda_math_formula. + * - scalbln( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - scalbln(\p x, 0) returns \p x. + * - scalbln( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - scalbln(NaN, \p n) returns NaN. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double scalbln(double x, long int n) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl scalbln(double x, long int n); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Scale floating-point input by integer power of two. + * + * Scale \p x by + * \cuda_math_formula 2^n \end_cuda_math_formula + * by efficient manipulation of the floating-point + * exponent. + * + * \return + * Returns \p x * + * \cuda_math_formula 2^n \end_cuda_math_formula. + * - scalblnf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - scalblnf(\p x, 0) returns \p x. + * - scalblnf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - scalblnf(NaN, \p n) returns NaN. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float scalblnf(float x, long int n) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl scalblnf(float x, long int n); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Extract mantissa and exponent of a floating-point value + * + * Decompose the floating-point value \p x into a component \p m for the + * normalized fraction element and another term \p n for the exponent. + * The absolute value of \p m will be greater than or equal to 0.5 and + * less than 1.0 or it will be equal to 0; + * \cuda_math_formula x = m\cdot 2^n \end_cuda_math_formula. + * The integer exponent \p n will be stored in the location to which \p nptr points. + * + * \return + * Returns the fractional component \p m. + * - frexp( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p nptr) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * and stores zero in the location pointed to by \p nptr. + * - frexp( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p nptr) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * and stores an unspecified value in the + * location to which \p nptr points. + * - frexp(NaN, \p y) returns a NaN and stores an unspecified value in the location to which \p nptr points. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl frexp(double x, int *nptr) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Extract mantissa and exponent of a floating-point value + * + * Decomposes the floating-point value \p x into a component \p m for the + * normalized fraction element and another term \p n for the exponent. + * The absolute value of \p m will be greater than or equal to 0.5 and + * less than 1.0 or it will be equal to 0; + * \cuda_math_formula x = m\cdot 2^n \end_cuda_math_formula. + * The integer exponent \p n will be stored in the location to which \p nptr points. + * + * \return + * Returns the fractional component \p m. + * - frexpf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p nptr) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * and stores zero in the location pointed to by \p nptr. + * - frexpf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p nptr) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * and stores an unspecified value in the + * location to which \p nptr points. + * - frexpf(NaN, \p y) returns a NaN and stores an unspecified value in the location to which \p nptr points. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float frexpf(float x, int *nptr) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Round to nearest integer value in floating-point. + * + * Round \p x to the nearest integer value in floating-point format, + * with halfway cases rounded away from zero. + * + * \return + * Returns rounded integer value. + * - round( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - round( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - round(NaN) returns NaN. + * + * \note_slow_round See ::rint(). + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double round(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl round(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Round to nearest integer value in floating-point. + * + * Round \p x to the nearest integer value in floating-point format, + * with halfway cases rounded away from zero. + * + * \return + * Returns rounded integer value. + * - roundf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - roundf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - roundf(NaN) returns NaN. + * + * \note_slow_round See ::rintf(). + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float roundf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl roundf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Round to nearest integer value. + * + * Round \p x to the nearest integer value, with halfway cases rounded + * away from zero. If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + * + * \note_slow_round See ::lrint(). + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long int lround(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long int __cdecl lround(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Round to nearest integer value. + * + * Round \p x to the nearest integer value, with halfway cases rounded + * away from zero. If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + * + * \note_slow_round See ::lrintf(). + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long int lroundf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long int __cdecl lroundf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Round to nearest integer value. + * + * Round \p x to the nearest integer value, with halfway cases rounded + * away from zero. If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + * + * \note_slow_round See ::llrint(). + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int llround(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long long int __cdecl llround(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Round to nearest integer value. + * + * Round \p x to the nearest integer value, with halfway cases rounded + * away from zero. If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + * + * \note_slow_round See ::llrintf(). + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int llroundf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long long int __cdecl llroundf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Round to nearest integer value in floating-point. + * + * Round \p x to the nearest integer value in floating-point format, + * with halfway cases rounded to the nearest even integer value. + * + * \return + * Returns rounded integer value. + * - rint( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - rint( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - rint(NaN) returns NaN. + */ +#if defined(__CUDA_ARCH__) || defined(__DOXYGEN_ONLY__) +/* + * We don't generate the declaration of rint for host compilation. + * This is acaully a workaround to compile the boost header file when + * Clang 3.8 is used as the host compiler. The boost header file has + * the following example code: + * namespace NS { extern "C" { double rint(double); } + * } + * + * After preprocessing, we get something like below: + * + * extern "C" { double rint(double x) throw(); } + * # 30 "/usr/include/math.h" 3 + * extern "C" { double rint(double x) throw(); } + * namespace NS { extern "C" { double rint(double); } } + * + * Although GCC accepts this output, Clang 3.8 doesn't. + * Furthermore, we cannot change the boost header file by adding "throw()" + * to rint's declaration there. So, as a workaround, we just don't generate + * our re-declaration for the host compilation. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double rint(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl rint(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#endif /* __CUDA_ARCH__ || __DOXYGEN_ONLY__ */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Round input to nearest integer value in floating-point. + * + * Round \p x to the nearest integer value in floating-point format, + * with halfway cases rounded to the nearest even integer value. + * + * \return + * Returns rounded integer value. + * - rintf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - rintf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - rintf(NaN) returns NaN. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float rintf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl rintf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Round input to nearest integer value. + * + * Round \p x to the nearest integer value, + * with halfway cases rounded to the nearest even integer value. + * If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long int lrint(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long int __cdecl lrint(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Round input to nearest integer value. + * + * Round \p x to the nearest integer value, + * with halfway cases rounded to the nearest even integer value. + * If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long int lrintf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long int __cdecl lrintf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Round input to nearest integer value. + * + * Round \p x to the nearest integer value, + * with halfway cases rounded to the nearest even integer value. + * If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int llrint(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long long int __cdecl llrint(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Round input to nearest integer value. + * + * Round \p x to the nearest integer value, + * with halfway cases rounded to the nearest even integer value. + * If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int llrintf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long long int __cdecl llrintf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Round the input argument to the nearest integer. + * + * Round argument \p x to an integer value in double precision floating-point format. Uses round to nearest rounding, with ties rounding to even. + * + * \return + * - nearbyint( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - nearbyint( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - nearbyint(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double nearbyint(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl nearbyint(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Round the input argument to the nearest integer. + * + * Round argument \p x to an integer value in single precision floating-point format. Uses round to nearest rounding, with ties rounding to even. + * + * \return + * - nearbyintf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - nearbyintf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - nearbyintf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float nearbyintf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl nearbyintf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate ceiling of the input argument. + * + * Compute the smallest integer value not less than \p x. + * + * \return + * Returns + * \cuda_math_formula \lceil x \rceil \end_cuda_math_formula + expressed as a floating-point number. + * - ceil( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - ceil( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - ceil(NaN) returns NaN. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl ceil(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Truncate input argument to the integral part. + * + * Round \p x to the nearest integer value that does not exceed \p x in + * magnitude. + * + * \return + * Returns truncated integer value. + * - trunc( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - trunc( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - trunc(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double trunc(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl trunc(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Truncate input argument to the integral part. + * + * Round \p x to the nearest integer value that does not exceed \p x in + * magnitude. + * + * \return + * Returns truncated integer value. + * - truncf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - truncf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - truncf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float truncf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl truncf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Compute the positive difference between \p x and \p y. + * + * Compute the positive difference between \p x and \p y. The positive + * difference is \p x - \p y when \p x > \p y and +0 otherwise. + * + * \return + * Returns the positive difference between \p x and \p y. + * - fdim(\p x, \p y) returns \p x - \p y if \p x > \p y. + * - fdim(\p x, \p y) returns +0 if \p x + * \cuda_math_formula \leq \end_cuda_math_formula + \p y. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double fdim(double x, double y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl fdim(double x, double y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Compute the positive difference between \p x and \p y. + * + * Compute the positive difference between \p x and \p y. The positive + * difference is \p x - \p y when \p x > \p y and +0 otherwise. + * + * \return + * Returns the positive difference between \p x and \p y. + * - fdimf(\p x, \p y) returns \p x - \p y if \p x > \p y. + * - fdimf(\p x, \p y) returns +0 if \p x + * \cuda_math_formula \leq \end_cuda_math_formula + \p y. + * - If either argument is NaN, NaN is returned. + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float fdimf(float x, float y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl fdimf(float x, float y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the arc tangent of the ratio of first and second input arguments. + * + * Calculate the principal value of the arc tangent of the ratio of first + * and second input arguments \p y / \p x. The quadrant of the result is + * determined by the signs of inputs \p y and \p x. + * + * \return + * Result will be in radians, in the interval [- + * \cuda_math_formula \pi \end_cuda_math_formula + * , + + * \cuda_math_formula \pi \end_cuda_math_formula + * ]. + * - atan2( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , -0) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula. + * - atan2( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , +0) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - atan2( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p x) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * for \p x < 0. + * - atan2( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p x) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * for \p x > 0. + * - atan2(\p y, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\pi \end_cuda_math_formula + * /2 for \p y < 0. + * - atan2(\p y, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pi \end_cuda_math_formula + * /2 for \p y > 0. + * - atan2( + * \cuda_math_formula \pm y \end_cuda_math_formula + * , + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * for finite \p y > 0. + * - atan2( + * \cuda_math_formula \pm y \end_cuda_math_formula + * , + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * for finite \p y > 0. + * - atan2( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p x) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * /2 for finite \p x. + * - atan2( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 3\pi \end_cuda_math_formula + * /4. + * - atan2( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * /4. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl atan2(double y, double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the arc tangent of the input argument. + * + * Calculate the principal value of the arc tangent of the input argument \p x. + * + * \return + * Result will be in radians, in the interval [- + * \cuda_math_formula \pi \end_cuda_math_formula + * /2, + + * \cuda_math_formula \pi \end_cuda_math_formula + * /2]. + * - atan( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - atan( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * /2. + * - atan(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl atan(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the arc cosine of the input argument. + * + * Calculate the principal value of the arc cosine of the input argument \p x. + * + * \return + * Result will be in radians, in the interval [0, + * \cuda_math_formula \pi \end_cuda_math_formula + * ] for \p x inside [-1, +1]. + * - acos(1) returns +0. + * - acos(\p x) returns NaN for \p x outside [-1, +1]. + * - acos(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl acos(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the arc sine of the input argument. + * + * Calculate the principal value of the arc sine of the input argument \p x. + * + * \return + * Result will be in radians, in the interval [- + * \cuda_math_formula \pi \end_cuda_math_formula + * /2, + + * \cuda_math_formula \pi \end_cuda_math_formula + * /2] for \p x inside [-1, +1]. + * - asin( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - asin(\p x) returns NaN for \p x outside [-1, +1]. + * - asin(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl asin(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the square root of the sum of squares of two arguments. + * + * Calculate the length of the hypotenuse of a right triangle whose two sides have lengths + * \p x and \p y without undue overflow or underflow. + * + * \return Returns the length of the hypotenuse + * \cuda_math_formula \sqrt{x^2+y^2} \end_cuda_math_formula. + * - hypot(\p x,\p y), hypot(\p y,\p x), and hypot(\p x, \p -y) are equivalent. + * - hypot(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) is equivalent to fabs(\p x). + * - hypot( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ,\p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula +, + * even if \p y is a NaN. + * - hypot(NaN, \p y) returns NaN, when \p y is not \cuda_math_formula \pm\infty \end_cuda_math_formula. + * + * \note_accuracy_double + */ +#if defined(_WIN32) +#if defined(_MSC_VER) && _MSC_VER < 1900 +static __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __CRTDECL hypot(double x, double y); +#else +extern _ACRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl hypot(double x, double y); +#endif +#else /* _WIN32 */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double hypot(double x, double y) __THROW; +#endif /* _WIN32 */ + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate one over the square root of the sum of squares of two arguments. + * + * Calculate one over the length of the hypotenuse of a right triangle whose two sides have + * lengths \p x and \p y without undue overflow or underflow. + * + * \return Returns one over the length of the hypotenuse + * \cuda_math_formula \frac{1}{\sqrt{x^2+y^2}} \end_cuda_math_formula. + * - rhypot(\p x,\p y), rhypot(\p y,\p x), and rhypot(\p x, \p -y) are equivalent. + * - rhypot( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ,\p y) returns +0, + * even if \p y is a NaN. + * - rhypot(\cuda_math_formula \pm 0, \pm 0 \end_cuda_math_formula) returns \cuda_math_formula +\infty \end_cuda_math_formula. + * - rhypot(NaN, \p y) returns NaN, when \p y is not \cuda_math_formula \pm\infty \end_cuda_math_formula. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ double rhypot(double x, double y) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the square root of the sum of squares of two arguments. + * + * Calculates the length of the hypotenuse of a right triangle whose two sides have lengths + * \p x and \p y without undue overflow or underflow. + * + * \return Returns the length of the hypotenuse + * \cuda_math_formula \sqrt{x^2+y^2} \end_cuda_math_formula. + * - hypotf(\p x,\p y), hypotf(\p y,\p x), and hypotf(\p x, \p -y) are equivalent. + * - hypotf(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) is equivalent to fabsf(\p x). + * - hypotf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ,\p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula +, + * even if \p y is a NaN. + * - hypotf(NaN, \p y) returns NaN, when \p y is not \cuda_math_formula \pm\infty \end_cuda_math_formula. + * + * \note_accuracy_single + */ +#if defined(_WIN32) +static __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __CRTDECL hypotf(float x, float y); +#else /* _WIN32 */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float hypotf(float x, float y) __THROW; +#endif /* _WIN32 */ + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate one over the square root of the sum of squares of two arguments. + * + * Calculates one over the length of the hypotenuse of a right triangle whose two sides have + * lengths \p x and \p y without undue overflow or underflow. + * + * \return Returns one over the length of the hypotenuse + * \cuda_math_formula \frac{1}{\sqrt{x^2+y^2}} \end_cuda_math_formula. + * - rhypotf(\p x,\p y), rhypotf(\p y,\p x), and rhypotf(\p x, \p -y) are equivalent. + * - rhypotf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ,\p y) returns +0, + * even if \p y is a NaN. + * - rhypotf(\cuda_math_formula \pm 0, \pm 0 \end_cuda_math_formula) returns \cuda_math_formula +\infty \end_cuda_math_formula. + * - rhypotf(NaN, \p y) returns NaN, when \p y is not \cuda_math_formula \pm\infty \end_cuda_math_formula. + * + * \note_accuracy_single + */ +extern __device__ __device_builtin__ float rhypotf(float x, float y) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the square root of the sum of squares of three coordinates of the argument. + * + * Calculate the length of three dimensional vector in Euclidean space without undue overflow or underflow. + * + * \return Returns the length of 3D vector + * \cuda_math_formula \sqrt{a^2+b^2+c^2} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +\infty \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns +0, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl norm3d(double a, double b, double c) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate one over the square root of the sum of squares of three coordinates. + * + * Calculate one over the length of three dimensional vector in Euclidean space without undue overflow or underflow. + * + * \return Returns one over the length of the 3D vector + * \cuda_math_formula \frac{1}{\sqrt{a^2+b^2+c^2}} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +0 \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns \cuda_math_formula +\infty \end_cuda_math_formula, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ double rnorm3d(double a, double b, double c) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the square root of the sum of squares of four coordinates of the argument. + * + * Calculate the length of four dimensional vector in Euclidean space without undue overflow or underflow. + * + * \return Returns the length of 4D vector + * \cuda_math_formula \sqrt{a^2+b^2+c^2+d^2} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +\infty \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns +0, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl norm4d(double a, double b, double c, double d) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate one over the square root of the sum of squares of four coordinates. + * + * Calculate one over the length of four dimensional vector in Euclidean space without undue overflow or underflow. + * + * \return Returns one over the length of the 3D vector + * \cuda_math_formula \frac{1}{\sqrt{a^2+b^2+c^2+d^2}} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +0 \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns \cuda_math_formula +\infty \end_cuda_math_formula, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ double rnorm4d(double a, double b, double c, double d) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the square root of the sum of squares of any number of coordinates. + * + * Calculate the length of a vector p, dimension of which is passed as an argument \p without undue overflow or underflow. + * + * \return Returns the length of the dim-D vector + * \cuda_math_formula \sqrt{\sum_{i=0}^{dim-1} p_i^2} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +\infty \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns +0, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_double + */ +__device__ __device_builtin__ double norm(int dim, double const * p) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the reciprocal of square root of the sum of squares of any number of coordinates. + * + * Calculates one over the length of vector \p p, dimension of which is passed as an argument, in Euclidean space without undue overflow or underflow. + * + * \return Returns one over the length of the vector + * \cuda_math_formula \frac{1}{\sqrt{\sum_{i=0}^{dim-1} p_i^2}} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +0 \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns \cuda_math_formula +\infty \end_cuda_math_formula, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ double rnorm(int dim, double const * p) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the reciprocal of square root of the sum of squares of any number of coordinates. + * + * Calculates one over the length of vector \p p, dimension of which is passed as an argument, in Euclidean space without undue overflow or underflow. + * + * \return Returns one over the length of the vector + * \cuda_math_formula \frac{1}{\sqrt{\sum_{i=0}^{dim-1} p_i^2}} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +0 \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns \cuda_math_formula +\infty \end_cuda_math_formula, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_single + */ + +extern __device__ __device_builtin__ float rnormf(int dim, float const * p) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the square root of the sum of squares of any number of coordinates. + * + * Calculates the length of a vector \p p, dimension of which is passed as an argument without undue overflow or underflow. + * + * \return Returns the length of the dim-D vector + * \cuda_math_formula \sqrt{\sum_{i=0}^{dim-1} p_i^2} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +\infty \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns +0, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_single + */ +__device__ __device_builtin__ float normf(int dim, float const * p) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the square root of the sum of squares of three coordinates of the argument. + * + * Calculates the length of three dimensional vector in Euclidean space without undue overflow or underflow. + * + * \return Returns the length of the 3D vector + * \cuda_math_formula \sqrt{a^2+b^2+c^2} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +\infty \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns +0, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_single + */ + +extern __device__ __device_builtin__ float norm3df(float a, float b, float c) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate one over the square root of the sum of squares of three coordinates. + * + * Calculates one over the length of three dimension vector in Euclidean space without undue overflow or underflow. + * + * \return Returns one over the length of the 3D vector + * \cuda_math_formula \frac{1}{\sqrt{a^2+b^2+c^2}} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +0 \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns \cuda_math_formula +\infty \end_cuda_math_formula, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_single + */ +extern __device__ __device_builtin__ float rnorm3df(float a, float b, float c) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the square root of the sum of squares of four coordinates of the argument. + * + * Calculates the length of four dimensional vector in Euclidean space without undue overflow or underflow. + * + * \return Returns the length of the 4D vector + * \cuda_math_formula \sqrt{a^2+b^2+c^2+d^2} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +\infty \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns +0, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_single + */ +extern __device__ __device_builtin__ float norm4df(float a, float b, float c, float d) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate one over the square root of the sum of squares of four coordinates. + * + * Calculates one over the length of four dimension vector in Euclidean space without undue overflow or underflow. + * + * \return Returns one over the length of the 3D vector + * \cuda_math_formula \frac{1}{\sqrt{a^2+b^2+c^2+d^2}} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +0 \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns \cuda_math_formula +\infty \end_cuda_math_formula, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_single + */ +extern __device__ __device_builtin__ float rnorm4df(float a, float b, float c, float d) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the cube root of the input argument. + * + * Calculate the cube root of \p x, + * \cuda_math_formula x^{1/3} \end_cuda_math_formula. + * + * \return + * Returns + * \cuda_math_formula x^{1/3} \end_cuda_math_formula. + * - cbrt( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - cbrt( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - cbrt(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double cbrt(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl cbrt(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the cube root of the input argument. + * + * Calculate the cube root of \p x, + * \cuda_math_formula x^{1/3} \end_cuda_math_formula. + * + * \return + * Returns + * \cuda_math_formula x^{1/3} \end_cuda_math_formula. + * - cbrtf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - cbrtf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - cbrtf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float cbrtf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl cbrtf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate reciprocal cube root function. + * + * Calculate reciprocal cube root function of \p x. + * + * \return + * - rcbrt( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - rcbrt( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - rcbrt(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double rcbrt(double x); + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate reciprocal cube root function. + * + * Calculate reciprocal cube root function of \p x. + * + * \return + * - rcbrtf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - rcbrtf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - rcbrtf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float rcbrtf(float x); +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the sine of the input argument + * \cuda_math_formula \times \pi \end_cuda_math_formula. + * + * Calculate the sine of \p x + * \cuda_math_formula \times \pi \end_cuda_math_formula + * (measured in radians), + * where \p x is the input argument. + * + * \return + * - sinpi( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sinpi( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - sinpi(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double sinpi(double x); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the sine of the input argument + * \cuda_math_formula \times \pi \end_cuda_math_formula. + * + * Calculate the sine of \p x + * \cuda_math_formula \times \pi \end_cuda_math_formula + * (measured in radians), + * where \p x is the input argument. + * + * \return + * - sinpif( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sinpif( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - sinpif(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float sinpif(float x); +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the cosine of the input argument + * \cuda_math_formula \times \pi \end_cuda_math_formula. + * + * Calculate the cosine of \p x + * \cuda_math_formula \times \pi \end_cuda_math_formula + * (measured in radians), + * where \p x is the input argument. + * + * \return + * - cospi( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - cospi( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - cospi(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double cospi(double x); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the cosine of the input argument + * \cuda_math_formula \times \pi \end_cuda_math_formula. + * + * Calculate the cosine of \p x + * \cuda_math_formula \times \pi \end_cuda_math_formula + * (measured in radians), + * where \p x is the input argument. + * + * \return + * - cospif( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - cospif( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - cospif(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float cospif(float x); +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the sine and cosine of the first input argument + * \cuda_math_formula \times \pi \end_cuda_math_formula. + * + * Calculate the sine and cosine of the first input argument, \p x (measured in radians), + * \cuda_math_formula \times \pi \end_cuda_math_formula. The results for sine and cosine are written into the + * second argument, \p sptr, and, respectively, third argument, \p cptr. + * + * \see ::sinpi() and ::cospi(). + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ void sincospi(double x, double *sptr, double *cptr); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the sine and cosine of the first input argument + * \cuda_math_formula \times \pi \end_cuda_math_formula. + * + * Calculate the sine and cosine of the first input argument, \p x (measured in radians), + * \cuda_math_formula \times \pi \end_cuda_math_formula. The results for sine and cosine are written into the + * second argument, \p sptr, and, respectively, third argument, \p cptr. + * + * \see ::sinpif() and ::cospif(). + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ void sincospif(float x, float *sptr, float *cptr); + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of first argument to the power of second argument. + * + * Calculate the value of \p x to the power of \p y. + * + * \return + * - pow( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * for \p y an odd integer less than 0. + * - pow( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for \p y less than 0 and not an odd integer. + * - pow( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * for \p y an odd integer greater than 0. + * - pow( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns +0 for \p y > 0 and not an odd integer. + * - pow(-1, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns 1. + * - pow(+1, \p y) returns 1 for any \p y, even a NaN. + * - pow(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1 for any \p x, even a NaN. + * - pow(\p x, \p y) returns a NaN for finite \p x < 0 and finite non-integer \p y. + * - pow(\p x, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for + * \cuda_math_formula | x | < 1 \end_cuda_math_formula. + * - pow(\p x, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0 for + * \cuda_math_formula | x | > 1 \end_cuda_math_formula. + * - pow(\p x, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0 for + * \cuda_math_formula | x | < 1 \end_cuda_math_formula. + * - pow(\p x, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for + * \cuda_math_formula | x | > 1 \end_cuda_math_formula. + * - pow( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns -0 for \p y an odd integer less than 0. + * - pow( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns +0 for \p y < 0 and not an odd integer. + * - pow( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula -\infty \end_cuda_math_formula + * for \p y an odd integer greater than 0. + * - pow( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for \p y > 0 and not an odd integer. + * - pow( + * \cuda_math_formula +\infty \end_cuda_math_formula + * , \p y) returns +0 for \p y < 0. + * - pow( + * \cuda_math_formula +\infty \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for \p y > 0. + * - pow(\p x, \p y) returns NaN if either \p x or \p y or both are NaN and \p x \cuda_math_formula \neq \end_cuda_math_formula +1 and \p y \cuda_math_formula \neq\pm 0 \end_cuda_math_formula. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl pow(double x, double y) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Break down the input argument into fractional and integral parts. + * + * Break down the argument \p x into fractional and integral parts. The + * integral part is stored in the argument \p iptr. + * Fractional and integral parts are given the same sign as the argument \p x. + * + * \return + * - modf( + * \cuda_math_formula \pm x \end_cuda_math_formula + * , \p iptr) returns a result with the same sign as \p x. + * - modf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p iptr) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * and stores + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * in the object pointed to by \p iptr. + * - modf(NaN, \p iptr) stores a NaN in the object pointed to by \p iptr and returns a NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl modf(double x, double *iptr) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the double-precision floating-point remainder of \p x / \p y. + * + * Calculate the double-precision floating-point remainder of \p x / \p y. + * The floating-point remainder of the division operation \p x / \p y calculated + * by this function is exactly the value x - n*y, where \p n is \p x / \p y with its fractional part truncated. + * The computed value will have the same sign as \p x, and its magnitude will be less than the magnitude of \p y. + * + * \return + * - Returns the floating-point remainder of \p x / \p y. + * - fmod( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * if \p y is not zero. + * - fmod(\p x, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns \p x if \p x is finite. + * - fmod(\p x, \p y) returns NaN if \p x is + * \cuda_math_formula \pm\infty \end_cuda_math_formula + * or \p y is zero. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl fmod(double x, double y) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Compute double-precision floating-point remainder. + * + * Compute double-precision floating-point remainder \p r of dividing + * \p x by \p y for nonzero \p y. Thus + * \cuda_math_formula r = x - n y \end_cuda_math_formula. + * The value \p n is the integer value nearest + * \cuda_math_formula \frac{x}{y} \end_cuda_math_formula. + * In the case when + * \cuda_math_formula | n -\frac{x}{y} | = \frac{1}{2} \end_cuda_math_formula + * , the + * even \p n value is chosen. + * + * \return + * - remainder(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns NaN. + * - remainder( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p y) returns NaN. + * - remainder(\p x, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns \p x for finite \p x. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double remainder(double x, double y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl remainder(double x, double y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Compute single-precision floating-point remainder. + * + * Compute single-precision floating-point remainder \p r of dividing + * \p x by \p y for nonzero \p y. Thus + * \cuda_math_formula r = x - n y \end_cuda_math_formula. + * The value \p n is the integer value nearest + * \cuda_math_formula \frac{x}{y} \end_cuda_math_formula. + * In the case when + * \cuda_math_formula | n -\frac{x}{y} | = \frac{1}{2} \end_cuda_math_formula + * , the + * even \p n value is chosen. + * + * \return + * - remainderf(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns NaN. + * - remainderf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p y) returns NaN. + * - remainderf(\p x, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns \p x for finite \p x. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float remainderf(float x, float y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl remainderf(float x, float y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Compute double-precision floating-point remainder and part of quotient. + * + * Compute a double-precision floating-point remainder in the same way as the + * ::remainder() function. Argument \p quo returns part of quotient upon + * division of \p x by \p y. Value \p quo has the same sign as + * \cuda_math_formula \frac{x}{y} \end_cuda_math_formula + * and may not be the exact quotient but agrees with the exact quotient + * in the low order 3 bits. + * + * \return + * Returns the remainder. + * - remquo(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p quo) returns NaN + * and stores an unspecified value in the + * location to which \p quo points. + * - remquo( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p y, \p quo) returns NaN + * and stores an unspecified value in the + * location to which \p quo points. + * - remquo(\p x, \p y, \p quo) returns NaN + * and stores an unspecified value in the + * location to which \p quo points if either of \p x or \p y is NaN. + * - remquo(\p x, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p quo) returns \p x and stores zero + * in the location to which \p quo points for finite \p x. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double remquo(double x, double y, int *quo) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl remquo(double x, double y, int *quo); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Compute single-precision floating-point remainder and part of quotient. + * + * Compute a single-precision floating-point remainder in the same way as the + * ::remainderf() function. Argument \p quo returns part of quotient upon + * division of \p x by \p y. Value \p quo has the same sign as + * \cuda_math_formula \frac{x}{y} \end_cuda_math_formula + * and may not be the exact quotient but agrees with the exact quotient + * in the low order 3 bits. + * + * \return + * Returns the remainder. + * - remquof(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p quo) returns NaN + * and stores an unspecified value in the + * location to which \p quo points. + * - remquof( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p y, \p quo) returns NaN + * and stores an unspecified value in the + * location to which \p quo points. + * - remquof(\p x, \p y, \p quo) returns NaN + * and stores an unspecified value in the + * location to which \p quo points if either of \p x or \p y is NaN. + * - remquof(\p x, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p quo) returns \p x and stores zero + * in the location to which \p quo points for finite \p x. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float remquof(float x, float y, int *quo) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl remquof(float x, float y, int *quo); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the Bessel function of the first kind of order 0 for the input argument. + * + * Calculate the value of the Bessel function of the first kind of order 0 for + * the input argument \p x, + * \cuda_math_formula J_0(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the first kind of order 0. + * - j0( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns +0. + * - j0(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl j0(double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the Bessel function of the first kind of order 0 for the input argument. + * + * Calculate the value of the Bessel function of the first kind of order 0 for + * the input argument \p x, + * \cuda_math_formula J_0(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the first kind of order 0. + * - j0f( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns +0. + * - j0f(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float j0f(float x) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the Bessel function of the first kind of order 1 for the input argument. + * + * Calculate the value of the Bessel function of the first kind of order 1 for + * the input argument \p x, + * \cuda_math_formula J_1(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the first kind of order 1. + * - j1( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - j1( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - j1(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl j1(double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the Bessel function of the first kind of order 1 for the input argument. + * + * Calculate the value of the Bessel function of the first kind of order 1 for + * the input argument \p x, + * \cuda_math_formula J_1(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the first kind of order 1. + * - j1f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - j1f( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - j1f(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float j1f(float x) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the Bessel function of the first kind of order n for the input argument. + * + * Calculate the value of the Bessel function of the first kind of order \p n for + * the input argument \p x, + * \cuda_math_formula J_n(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the first kind of order \p n. + * - jn(\p n, NaN) returns NaN. + * - jn(\p n, \p x) returns NaN for \p n < 0. + * - jn(\p n, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl jn(int n, double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the Bessel function of the first kind of order n for the input argument. + * + * Calculate the value of the Bessel function of the first kind of order \p n for + * the input argument \p x, + * \cuda_math_formula J_n(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the first kind of order \p n. + * - jnf(\p n, NaN) returns NaN. + * - jnf(\p n, \p x) returns NaN for \p n < 0. + * - jnf(\p n, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float jnf(int n, float x) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the Bessel function of the second kind of order 0 for the input argument. + * + * Calculate the value of the Bessel function of the second kind of order 0 for + * the input argument \p x, + * \cuda_math_formula Y_0(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the second kind of order 0. + * - y0( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - y0(\p x) returns NaN for \p x < 0. + * - y0( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - y0(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl y0(double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the Bessel function of the second kind of order 0 for the input argument. + * + * Calculate the value of the Bessel function of the second kind of order 0 for + * the input argument \p x, + * \cuda_math_formula Y_0(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the second kind of order 0. + * - y0f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - y0f(\p x) returns NaN for \p x < 0. + * - y0f( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - y0f(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float y0f(float x) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the Bessel function of the second kind of order 1 for the input argument. + * + * Calculate the value of the Bessel function of the second kind of order 1 for + * the input argument \p x, + * \cuda_math_formula Y_1(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the second kind of order 1. + * - y1( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - y1(\p x) returns NaN for \p x < 0. + * - y1( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - y1(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl y1(double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the Bessel function of the second kind of order 1 for the input argument. + * + * Calculate the value of the Bessel function of the second kind of order 1 for + * the input argument \p x, + * \cuda_math_formula Y_1(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the second kind of order 1. + * - y1f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - y1f(\p x) returns NaN for \p x < 0. + * - y1f( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - y1f(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float y1f(float x) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the Bessel function of the second kind of order n for the input argument. + * + * Calculate the value of the Bessel function of the second kind of order \p n for + * the input argument \p x, + * \cuda_math_formula Y_n(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the second kind of order \p n. + * - yn(\p n, \p x) returns NaN for \p n < 0. + * - yn(\p n, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + *) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - yn(\p n, \p x) returns NaN for \p x < 0. + * - yn(\p n, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - yn(\p n, NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl yn(int n, double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the Bessel function of the second kind of order n for the input argument. + * + * Calculate the value of the Bessel function of the second kind of order \p n for + * the input argument \p x, + * \cuda_math_formula Y_n(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the second kind of order \p n. + * - ynf(\p n, \p x) returns NaN for \p n < 0. + * - ynf(\p n, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - ynf(\p n, \p x) returns NaN for \p x < 0. + * - ynf(\p n, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - ynf(\p n, NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float ynf(int n, float x) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the regular modified cylindrical Bessel function of order 0 for the input argument. + * + * Calculate the value of the regular modified cylindrical Bessel function of order 0 for + * the input argument \p x, + * \cuda_math_formula I_0(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the regular modified cylindrical Bessel function of order 0. + * - cyl_bessel_i0(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns +1. + * - cyl_bessel_i0(\cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula +\infty \end_cuda_math_formula. + * - cyl_bessel_i0(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl cyl_bessel_i0(double x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the regular modified cylindrical Bessel function of order 0 for the input argument. + * + * Calculate the value of the regular modified cylindrical Bessel function of order 0 for + * the input argument \p x, + * \cuda_math_formula I_0(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the regular modified cylindrical Bessel function of order 0. + * - cyl_bessel_i0f(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns +1. + * - cyl_bessel_i0f(\cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula +\infty \end_cuda_math_formula. + * - cyl_bessel_i0f(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __device__ __device_builtin__ float cyl_bessel_i0f(float x) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the regular modified cylindrical Bessel function of order 1 for the input argument. + * + * Calculate the value of the regular modified cylindrical Bessel function of order 1 for + * the input argument \p x, + * \cuda_math_formula I_1(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the regular modified cylindrical Bessel function of order 1. + * - cyl_bessel_i1(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - cyl_bessel_i1(\cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - cyl_bessel_i1(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl cyl_bessel_i1(double x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the regular modified cylindrical Bessel function of order 1 for the input argument. + * + * Calculate the value of the regular modified cylindrical Bessel function of order 1 for + * the input argument \p x, + * \cuda_math_formula I_1(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the regular modified cylindrical Bessel function of order 1. + * - cyl_bessel_i1f(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - cyl_bessel_i1f(\cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - cyl_bessel_i1f(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __device__ __device_builtin__ float cyl_bessel_i1f(float x) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the error function of the input argument. + * + * Calculate the value of the error function for the input argument \p x, + * \cuda_math_formula \frac{2}{\sqrt \pi} \int_0^x e^{-t^2} dt \end_cuda_math_formula. + * + * \return + * - erf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - erf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 1 \end_cuda_math_formula. + * - erf(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double erf(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl erf(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the error function of the input argument. + * + * Calculate the value of the error function for the input argument \p x, + * \cuda_math_formula \frac{2}{\sqrt \pi} \int_0^x e^{-t^2} dt \end_cuda_math_formula. + * + * \return + * - erff( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - erff( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 1 \end_cuda_math_formula. + * - erff(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float erff(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl erff(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the inverse error function of the input argument. + * + * Calculate the inverse error function + * \cuda_math_formula \operatorname{erf}^{-1} \end_cuda_math_formula + * (\p x), of the input argument \p x in the interval [-1, 1]. + * + * \return + * - erfinv( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - erfinv(1) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - erfinv(-1) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - erfinv(\p x) returns NaN for \p x outside [-1, +1]. + * - erfinv(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double erfinv(double x); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the inverse error function of the input argument. + * + * Calculate the inverse error function + * \cuda_math_formula \operatorname{erf}^{-1} \end_cuda_math_formula + * (\p x), of the input argument \p x in the interval [-1, 1]. + * + * \return + * - erfinvf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - erfinvf(1) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - erfinvf(-1) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - erfinvf(\p x) returns NaN for \p x outside [-1, +1]. + * - erfinvf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float erfinvf(float x); + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the complementary error function of the input argument. + * + * Calculate the complementary error function of the input argument \p x, + * 1 - erf(\p x). + * + * \return + * - erfc( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns 2. + * - erfc( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - erfc(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double erfc(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl erfc(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the complementary error function of the input argument. + * + * Calculate the complementary error function of the input argument \p x, + * 1 - erf(\p x). + * + * \return + * - erfcf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns 2. + * - erfcf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - erfcf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float erfcf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl erfcf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the natural logarithm of the absolute value of the gamma function of the input argument. + * + * Calculate the natural logarithm of the absolute value of the gamma function of the input argument \p x, namely the value of + * \cuda_math_formula \log_{e}\left|\Gamma(x)\right| \end_cuda_math_formula + * + * \return + * - lgamma(1) returns +0. + * - lgamma(2) returns +0. + * - lgamma(\p x) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * if \p x + * \cuda_math_formula \leq \end_cuda_math_formula + 0 and \p x is an integer. + * - lgamma( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - lgamma( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - lgamma(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double lgamma(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl lgamma(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the inverse complementary error function of the input argument. + * + * Calculate the inverse complementary error function + * \cuda_math_formula \operatorname{erfc}^{-1} \end_cuda_math_formula + * (\p x), of the input argument \p x in the interval [0, 2]. + * + * \return + * - erfcinv( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - erfcinv(2) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - erfcinv(\p x) returns NaN for \p x outside [0, 2]. + * - erfcinv(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double erfcinv(double x); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the inverse complementary error function of the input argument. + * + * Calculate the inverse complementary error function + * \cuda_math_formula \operatorname{erfc}^{-1} \end_cuda_math_formula + * (\p x), of the input argument \p x in the interval [0, 2]. + * + * \return + * - erfcinvf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - erfcinvf(2) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - erfcinvf(\p x) returns NaN for \p x outside [0, 2]. + * - erfcinvf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float erfcinvf(float x); +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the inverse of the standard normal cumulative distribution function. + * + * Calculate the inverse of the standard normal cumulative distribution function for input argument \p x, + * \cuda_math_formula \Phi^{-1}(x) \end_cuda_math_formula. The function is defined for input values in the interval + * \cuda_math_formula (0, 1) \end_cuda_math_formula. + * + * \return + * - normcdfinv( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - normcdfinv(1) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - normcdfinv(\p x) returns NaN + * if \p x is not in the interval [0,1]. + * - normcdfinv(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double normcdfinv(double x); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the inverse of the standard normal cumulative distribution function. + * + * Calculate the inverse of the standard normal cumulative distribution function for input argument \p x, + * \cuda_math_formula \Phi^{-1}(x) \end_cuda_math_formula. The function is defined for input values in the interval + * \cuda_math_formula (0, 1) \end_cuda_math_formula. + * + * \return + * - normcdfinvf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - normcdfinvf(1) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - normcdfinvf(\p x) returns NaN + * if \p x is not in the interval [0,1]. + * - normcdfinvf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float normcdfinvf(float x); +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the standard normal cumulative distribution function. + * + * Calculate the cumulative distribution function of the standard normal distribution for input argument \p x, + * \cuda_math_formula \Phi(x) \end_cuda_math_formula. + * + * \return + * - normcdf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns 1. + * - normcdf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - normcdf(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double normcdf(double x); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the standard normal cumulative distribution function. + * + * Calculate the cumulative distribution function of the standard normal distribution for input argument \p x, + * \cuda_math_formula \Phi(x) \end_cuda_math_formula. + * + * \return + * - normcdff( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns 1. + * - normcdff( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0 + * - normcdff(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float normcdff(float x); +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the scaled complementary error function of the input argument. + * + * Calculate the scaled complementary error function of the input argument \p x, + * \cuda_math_formula e^{x^2}\cdot \operatorname{erfc}(x) \end_cuda_math_formula. + * + * \return + * - erfcx( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - erfcx( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - erfcx(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double erfcx(double x); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the scaled complementary error function of the input argument. + * + * Calculate the scaled complementary error function of the input argument \p x, + * \cuda_math_formula e^{x^2}\cdot \operatorname{erfc}(x) \end_cuda_math_formula. + * + * \return + * - erfcxf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - erfcxf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - erfcxf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float erfcxf(float x); + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the natural logarithm of the absolute value of the gamma function of the input argument. + * + * Calculate the natural logarithm of the absolute value of the gamma function of the input argument \p x, namely the value of + * \cuda_math_formula \log_{e}\left|\Gamma(x)\right| \end_cuda_math_formula + * + * \return + * - lgammaf(1) returns +0. + * - lgammaf(2) returns +0. + * - lgammaf(\p x) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * if \p x + * \cuda_math_formula \leq \end_cuda_math_formula + * 0 and \p x is an integer. + * - lgammaf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - lgammaf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - lgammaf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float lgammaf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl lgammaf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the gamma function of the input argument. + * + * Calculate the gamma function of the input argument \p x, namely the value of + * \cuda_math_formula \Gamma(x) \end_cuda_math_formula. + * + * \return + * - tgamma( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - tgamma(\p x) returns NaN if \p x < 0 and \p x is an integer. + * - tgamma( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns NaN. + * - tgamma( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - tgamma(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double tgamma(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl tgamma(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the gamma function of the input argument. + * + * Calculate the gamma function of the input argument \p x, namely the value of + * \cuda_math_formula \Gamma(x) \end_cuda_math_formula. + * + * \return + * - tgammaf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - tgammaf(\p x) returns NaN if \p x < 0 and \p x is an integer. + * - tgammaf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns NaN. + * - tgammaf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - tgammaf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float tgammaf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl tgammaf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** \ingroup CUDA_MATH_DOUBLE + * \brief Create value with given magnitude, copying sign of second value. + * + * Create a floating-point value with the magnitude \p x and the sign of \p y. + * + * \return + * - a value with the magnitude of \p x and the sign of \p y. + * - copysign(\p NaN, \p y) returns a \p NaN with the sign of \p y. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double copysign(double x, double y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl copysign(double x, double y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** \ingroup CUDA_MATH_SINGLE + * \brief Create value with given magnitude, copying sign of second value. + * + * Create a floating-point value with the magnitude \p x and the sign of \p y. + * + * \return + * - a value with the magnitude of \p x and the sign of \p y. + * - copysignf(\p NaN, \p y) returns a \p NaN with the sign of \p y. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float copysignf(float x, float y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl copysignf(float x, float y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Return next representable double-precision floating-point value after argument \p x in the direction of \p y. + * + * Calculate the next representable double-precision floating-point value + * following \p x in the direction of \p y. For example, if \p y is greater than \p x, ::nextafter() + * returns the smallest representable number greater than \p x + * + * \return + * - nextafter(\p x, \p y) = \p y if \p x equals \p y. + * - nextafter(\p x, \p y) = \p NaN if either \p x or \p y are \p NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double nextafter(double x, double y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl nextafter(double x, double y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Return next representable single-precision floating-point value after argument \p x in the direction of \p y. + * + * Calculate the next representable single-precision floating-point value + * following \p x in the direction of \p y. For example, if \p y is greater than \p x, ::nextafterf() + * returns the smallest representable number greater than \p x + * + * \return + * - nextafterf(\p x, \p y) = \p y if \p x equals \p y. + * - nextafterf(\p x, \p y) = \p NaN if either \p x or \p y are \p NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float nextafterf(float x, float y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl nextafterf(float x, float y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Returns "Not a Number" value. + * + * Return a representation of a quiet NaN. Argument \p tagp selects one of the possible representations. + * + * \return + * - nan(\p tagp) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double nan(const char *tagp) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl nan(const char *tagp); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Returns "Not a Number" value + * + * Return a representation of a quiet NaN. Argument \p tagp selects one of the possible representations. + * + * \return + * - nanf(\p tagp) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float nanf(const char *tagp) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl nanf(const char *tagp); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* namespace std */ +#endif +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isinff(float) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isnanf(float) __THROW; + + +#if defined(__APPLE__) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isfinited(double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isfinitef(float) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __signbitd(double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isnand(double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isinfd(double) __THROW; +#else /* __APPLE__ */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __finite(double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __finitef(float) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __signbit(double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isnan(double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isinf(double) __THROW; +#endif /* __APPLE__ */ + +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __signbitf(float) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Compute + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation. + * + * Compute the value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single ternary operation. After computing the value + * to infinite precision, the value is rounded once using round-to-nearest, + * ties-to-even rounding mode. + * + * \return + * Returns the rounded value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation. + * - fma( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p z) returns NaN. + * - fma( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p z) returns NaN. + * - fma(\p x, \p y, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - fma(\p x, \p y, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - fma(\p x, \p y, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - fma(\p x, \p y, \cuda_math_formula \mp 0 \end_cuda_math_formula) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - fma(\p x, \p y, \p z) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y + z \end_cuda_math_formula is exactly zero and \cuda_math_formula z \neq 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double fma(double x, double y, double z) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl fma(double x, double y, double z); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Compute + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation. + * + * Compute the value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single ternary operation. After computing the value + * to infinite precision, the value is rounded once using round-to-nearest, + * ties-to-even rounding mode. + * + * \return + * Returns the rounded value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation. + * - fmaf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p z) returns NaN. + * - fmaf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p z) returns NaN. + * - fmaf(\p x, \p y, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - fmaf(\p x, \p y, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - fmaf(\p x, \p y, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - fmaf(\p x, \p y, \cuda_math_formula \mp 0 \end_cuda_math_formula) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - fmaf(\p x, \p y, \p z) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y + z \end_cuda_math_formula is exactly zero and \cuda_math_formula z \neq 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float fmaf(float x, float y, float z) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl fmaf(float x, float y, float z); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + + +/* these are here to avoid warnings on the call graph. + long double is not supported on the device */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __signbitl(long double) __THROW; +#if defined(__APPLE__) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isfinite(long double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isinf(long double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isnan(long double) __THROW; +#else /* __APPLE__ */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __finitel(long double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isinfl(long double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isnanl(long double) __THROW; +#endif /* __APPLE__ */ + +#if defined(_WIN32) && ( defined(_M_AMD64) || defined(_M_ARM64) ) +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl acosf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl asinf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl atanf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl atan2f(float, float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl cosf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl sinf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl tanf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl coshf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl sinhf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl tanhf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl expf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl logf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl log10f(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl modff(float, float*) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl powf(float, float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl sqrtf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl ceilf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl floorf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl fmodf(float, float) __THROW; +#else /* _WIN32 && (_M_AMD64 || _M_ARM64) */ + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the arc cosine of the input argument. + * + * Calculate the principal value of the arc cosine of the input argument \p x. + * + * \return + * Result will be in radians, in the interval [0, + * \cuda_math_formula \pi \end_cuda_math_formula + * ] for \p x inside [-1, +1]. + * - acosf(1) returns +0. + * - acosf(\p x) returns NaN for \p x outside [-1, +1]. + * - acosf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float acosf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the arc sine of the input argument. + * + * Calculate the principal value of the arc sine of the input argument \p x. + * + * \return + * Result will be in radians, in the interval [- + * \cuda_math_formula \pi/2 \end_cuda_math_formula + * , + + * \cuda_math_formula \pi/2 \end_cuda_math_formula + * ] for \p x inside [-1, +1]. + * - asinf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - asinf(\p x) returns NaN for \p x outside [-1, +1]. + * - asinf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float asinf(float x) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the arc tangent of the input argument. + * + * Calculate the principal value of the arc tangent of the input argument \p x. + * + * \return + * Result will be in radians, in the interval [- + * \cuda_math_formula \pi/2 \end_cuda_math_formula + * , + + * \cuda_math_formula \pi/2 \end_cuda_math_formula + * ]. + * - atanf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - atanf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * /2. + * - atanf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float atanf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the arc tangent of the ratio of first and second input arguments. + * + * Calculate the principal value of the arc tangent of the ratio of first + * and second input arguments \p y / \p x. The quadrant of the result is + * determined by the signs of inputs \p y and \p x. + * + * \return + * Result will be in radians, in the interval [- + * \cuda_math_formula \pi \end_cuda_math_formula + * , + + * \cuda_math_formula \pi \end_cuda_math_formula + * ]. + * - atan2f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , -0) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula. + * - atan2f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , +0) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - atan2f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p x) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * for \p x < 0. + * - atan2f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p x) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * for \p x > 0. + * - atan2f(\p y, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\pi \end_cuda_math_formula + * /2 for \p y < 0. + * - atan2f(\p y, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pi \end_cuda_math_formula + * /2 for \p y > 0. + * - atan2f( + * \cuda_math_formula \pm y \end_cuda_math_formula + * , + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * for finite \p y > 0. + * - atan2f( + * \cuda_math_formula \pm y \end_cuda_math_formula + * , + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * for finite \p y > 0. + * - atan2f( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p x) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * /2 for finite \p x. + * - atan2f( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 3\pi \end_cuda_math_formula + * /4. + * - atan2f( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * /4. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float atan2f(float y, float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the cosine of the input argument. + * + * Calculate the cosine of the input argument \p x (measured in radians). + * + * \return + * - cosf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - cosf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - cosf(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float cosf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the sine of the input argument. + * + * Calculate the sine of the input argument \p x (measured in radians). + * + * \return + * - sinf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sinf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - sinf(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float sinf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the tangent of the input argument. + * + * Calculate the tangent of the input argument \p x (measured in radians). + * + * \return + * - tanf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - tanf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - tanf(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float tanf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the hyperbolic cosine of the input argument. + * + * Calculate the hyperbolic cosine of the input argument \p x. + * + * \return + * - coshf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - coshf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - coshf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float coshf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the hyperbolic sine of the input argument. + * + * Calculate the hyperbolic sine of the input argument \p x. + * + * \return + * - sinhf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sinhf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - sinhf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float sinhf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the hyperbolic tangent of the input argument. + * + * Calculate the hyperbolic tangent of the input argument \p x. + * + * \return + * - tanhf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - tanhf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 1 \end_cuda_math_formula. + * - tanhf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float tanhf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the natural logarithm of the input argument. + * + * Calculate the natural logarithm of the input argument \p x. + * + * \return + * - logf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - logf(1) returns +0. + * - logf(\p x) returns NaN for \p x < 0. + * - logf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - logf(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float logf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument. + * + * Calculate + * \cuda_math_formula e^x \end_cuda_math_formula +, + * the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument \p x. + * + * \return + * - expf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - expf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - expf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - expf(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float expf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the base 10 logarithm of the input argument. + * + * Calculate the base 10 logarithm of the input argument \p x. + * + * \return + * - log10f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - log10f(1) returns +0. + * - log10f(\p x) returns NaN for \p x < 0. + * - log10f( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - log10f(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float log10f(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Break down the input argument into fractional and integral parts. + * + * Break down the argument \p x into fractional and integral parts. The integral part is stored in the argument \p iptr. + * Fractional and integral parts are given the same sign as the argument \p x. + * + * \return + * - modff( + * \cuda_math_formula \pm x \end_cuda_math_formula + * , \p iptr) returns a result with the same sign as \p x. + * - modff( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p iptr) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * and stores + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * in the object pointed to by \p iptr. + * - modff(NaN, \p iptr) stores a NaN in the object pointed to by \p iptr and returns a NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float modff(float x, float *iptr) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of first argument to the power of second argument. + * + * Calculate the value of \p x to the power of \p y. + * + * \return + * - powf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * for \p y an odd integer less than 0. + * - powf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for \p y less than 0 and not an odd integer. + * - powf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * for \p y an odd integer greater than 0. + * - powf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns +0 for \p y > 0 and not an odd integer. + * - powf(-1, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns 1. + * - powf(+1, \p y) returns 1 for any \p y, even a NaN. + * - powf(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1 for any \p x, even a NaN. + * - powf(\p x, \p y) returns a NaN for finite \p x < 0 and finite non-integer \p y. + * - powf(\p x, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for + * \cuda_math_formula | x | < 1 \end_cuda_math_formula. + * - powf(\p x, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0 for + * \cuda_math_formula | x | > 1 \end_cuda_math_formula. + * - powf(\p x, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0 for + * \cuda_math_formula | x | < 1 \end_cuda_math_formula. + * - powf(\p x, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for + * \cuda_math_formula | x | > 1 \end_cuda_math_formula. + * - powf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns -0 for \p y an odd integer less than 0. + * - powf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns +0 for \p y < 0 and not an odd integer. + * - powf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula -\infty \end_cuda_math_formula + * for \p y an odd integer greater than 0. + * - powf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for \p y > 0 and not an odd integer. + * - powf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * , \p y) returns +0 for \p y < 0. + * - powf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for \p y > 0. + * - powf(\p x, \p y) returns NaN if either \p x or \p y or both are NaN and \p x \cuda_math_formula \neq \end_cuda_math_formula +1 and \p y \cuda_math_formula \neq\pm 0 \end_cuda_math_formula. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float powf(float x, float y) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the square root of the input argument. + * + * Calculate the nonnegative square root of \p x, + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula. + * + * \return + * Returns + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula. + * - sqrtf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sqrtf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - sqrtf(\p x) returns NaN if \p x is less than 0. + * - sqrtf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float sqrtf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate ceiling of the input argument. + * + * Compute the smallest integer value not less than \p x. + * + * \return + * Returns + * \cuda_math_formula \lceil x \rceil \end_cuda_math_formula + * expressed as a floating-point number. + * - ceilf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - ceilf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - ceilf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float ceilf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the largest integer less than or equal to \p x. + * + * Calculate the largest integer value which is less than or equal to \p x. + * + * \return + * Returns + * \cuda_math_formula \lfloor x \rfloor \end_cuda_math_formula + * expressed as a floating-point number. + * - floorf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - floorf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - floorf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float floorf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the floating-point remainder of \p x / \p y. + * + * Calculate the floating-point remainder of \p x / \p y. + * The floating-point remainder of the division operation \p x / \p y calculated + * by this function is exactly the value x - n*y, where \p n is \p x / \p y with its fractional part truncated. + * The computed value will have the same sign as \p x, and its magnitude will be less than the magnitude of \p y. + * \return + * - Returns the floating-point remainder of \p x / \p y. + * - fmodf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * if \p y is not zero. + * - fmodf(\p x, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns \p x if \p x is finite. + * - fmodf(\p x, \p y) returns NaN if \p x is + * \cuda_math_formula \pm\infty \end_cuda_math_formula + * or \p y is zero. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float fmodf(float x, float y) __THROW; +#if defined(__QNX__) +/* redeclare some builtins that QNX uses */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float _FLog(float, int); +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float _FCosh(float, float); +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float _FSinh(float, float); +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float _FSinx(float, unsigned int, int); +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int _FDsign(float); +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int _Dsign(double); +#endif +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif +#endif /* _WIN32 && (_M_AMD64 || _M_ARM64) */ + +} + +#if !defined(__CUDACC_RTC__) +#include +#include + +#ifndef __CUDA_INTERNAL_SKIP_CPP_HEADERS__ +#include +#include +#endif /* __CUDA_INTERNAL_SKIP_CPP_HEADERS__ */ +#endif /* __CUDACC_RTC__ */ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#if defined(__CUDACC_RTC__) + +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(float x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(long double x); + +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(float x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(long double x); + +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(float x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(long double x); + +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(float x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(long double x); + +#elif defined(__GNUC__) + +#undef signbit +#undef isfinite +#undef isnan +#undef isinf + +#if defined(__APPLE__) + +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(float x); +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(double x); +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(long double x); + +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(float x); +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(double x); +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(long double x); + +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(double x) throw(); +#if !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 7000 +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(float x); +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(long double x); +#else /* !(!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 7000) */ +template +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool __libcpp_isnan(T) _NOEXCEPT; +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isnan(float x) _NOEXCEPT; +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isnan(long double x) _NOEXCEPT; +#endif /* !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 7000 */ + +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(double x) throw(); +#if !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 7000 +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(float x); +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(long double x); +#else /* !(!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 7000) */ +template +__cudart_builtin__ __DEVICE_FUNCTIONS_DECL__ bool __libcpp_isinf(T) _NOEXCEPT; +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isinf(float x) _NOEXCEPT; +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isinf(long double x) _NOEXCEPT; +#endif /* !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 7000 */ + +#else /* __APPLE__ */ + +#if ((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L) +#if !defined(_NVHPC_CUDA) +namespace std { +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool signbit(float x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool signbit(double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool signbit(long double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isfinite(float x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isfinite(double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isfinite(long double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isnan(float x); +/* GCC 6.1 uses ::isnan(double x) for isnan(double x) if the condition is true */ +#if _GLIBCXX_HAVE_OBSOLETE_ISNAN && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(double x) throw(); +#else /* !(_GLIBCXX_HAVE_OBSOLETE_ISNAN && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC) */ +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isnan(double x); +#endif /* _GLIBCXX_HAVE_OBSOLETE_ISNAN && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC */ +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isnan(long double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isinf(float x); +/* GCC 6.1 uses ::isinf(double x) for isinf(double x) if the condition is true. */ +#if _GLIBCXX_HAVE_OBSOLETE_ISINF && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(double x) throw(); +#else /* !(_GLIBCXX_HAVE_OBSOLETE_ISINF && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC) */ +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isinf(double x); +#endif /* _GLIBCXX_HAVE_OBSOLETE_ISINF && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC */ +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isinf(long double x); +} +#endif + +#else /* !(((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L)) */ + +#if defined(__QNX__) +#if (__QNX__) && !defined(_LIBCPP_VERSION) +/* QNX defines functions in std, need to declare them here */ +namespace std { +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool signbit(float x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool signbit(double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool signbit(long double x); +} +#else +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool signbit(const float x); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool signbit(const double x); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool signbit(const long double x); +#endif +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isfinite(const float a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isfinite(const double a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isfinite(const long double a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isnan(const float a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isnan(const double a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isnan(const long double a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isinf(const float a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isinf(const double a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isinf(const long double a); +#else /* ! __QNX__ */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(const float x); +#if defined(__ICC) +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(const double x) throw(); +#else /* !__ICC */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(const double x); +#endif /* __ICC */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(const long double x); + +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(const float x); +#if defined(__ICC) +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(const double x) throw(); +#else /* !__ICC */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(const double x); +#endif /* __ICC */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(const long double x); + +#if (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 +template +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool __libcpp_isnan(T) _NOEXCEPT; +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isnan(float x) _NOEXCEPT; +#else /* !((defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000) */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(float x); +#endif /* (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 */ +#if defined(__ANDROID__) || defined(__HORIZON__) +#if !defined(_LIBCPP_VERSION) +__forceinline__ +#endif /* !defined(_LIBCPP_VERSION) */ +#if _LIBCPP_VERSION >= 7000 +#ifdef _LIBCPP_PREFERRED_OVERLOAD +_LIBCPP_INLINE_VISIBILITY _LIBCPP_PREFERRED_OVERLOAD __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isnan(double x) _NOEXCEPT; +#endif /* _LIBCPP_PREFERRED_OVERLOAD */ +#else /* _LIBCPP_VERSION < 7000 */ +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(double x); +#endif /* _LIBCPP_VERSION >= 7000 */ +#else /* !(__ANDROID__ || __HORIZON__) */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(double x) throw(); +#endif /* __ANDROID__ */ +#if (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isnan(long double x) _NOEXCEPT; +#else /* !( (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000) */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(long double x); +#endif /* (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 */ + +#if (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 +static __inline__ __cudart_builtin__ __DEVICE_FUNCTIONS_DECL__ unsigned __FLOAT_BITS(float __f); +static __inline__ __cudart_builtin__ __DEVICE_FUNCTIONS_DECL__ unsigned long long __DOUBLE_BITS(double __f); +template +__cudart_builtin__ __DEVICE_FUNCTIONS_DECL__ bool __libcpp_isinf(T) _NOEXCEPT; +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isinf(float x) _NOEXCEPT; +#else /* !( (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000) */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(float x); +#endif /* (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 */ + +#if defined(__ANDROID__) || defined(__HORIZON__) +#if !defined(_LIBCPP_VERSION) +__forceinline__ +#endif /* !defined(_LIBCPP_VERSION) */ +#if _LIBCPP_VERSION >= 7000 +#ifdef _LIBCPP_PREFERRED_OVERLOAD +_LIBCPP_INLINE_VISIBILITY _LIBCPP_PREFERRED_OVERLOAD __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isinf(double x) _NOEXCEPT; +#endif /* _LIBCPP_PREFERRED_OVERLOAD */ +#else /* _LIBCPP_VERSION < 7000 */ +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(double x); +#endif /* _LIBCPP_VERSION >= 7000 */ +#else /* ! (__ANDROID__ || __HORIZON__) */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(double x) throw(); +#endif /* __ANDROID__ || __HORIZON__ */ +#if (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isinf(long double x) _NOEXCEPT; +#else /* !( (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000) */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(long double x); +#endif /* (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 */ +#endif /* __QNX__ */ + +#endif /* ((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L) */ +#endif /* __APPLE__ */ + +#if !defined(_LIBCPP_VERSION) +#if defined(__clang__) +#if __has_include() +#define __NV_GLIBCXX_VERSION 40800 +#endif /* __has_include() */ +#endif /* __clang__ */ + +#if !defined(__NV_GLIBCXX_VERSION) +#define __NV_GLIBCXX_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) +#endif /* !__NV_GLIBCXX_VERSION */ +#endif /* !defined(_LIBCPP_VERSION) */ + +#if !defined(__HORIZON__) || !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 3800 +#if defined(__arm__) && !defined(_STLPORT_VERSION) && !_GLIBCXX_USE_C99 +#if !defined(__ANDROID__) || (defined(__NV_GLIBCXX_VERSION) && __NV_GLIBCXX_VERSION < 40800) + +#if defined(__QNX__) +/* QNX defines functions in std, need to declare them here */ +namespace std { +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int abs (long long int a); +} +#elif defined(__HORIZON__) +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +#pragma GCC system_header +#endif +_LIBCPP_BEGIN_NAMESPACE_STD +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int abs (long long int a) throw(); +_LIBCPP_END_NAMESPACE_STD +#else +static __inline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int abs(long long int a); +#endif /* __QNX__ || __HORIZON__*/ + +#endif /* !__ANDROID__ || (defined(__NV_GLIBCXX_VERSION) && __NV_GLIBCXX_VERSION < 40800) */ +#endif /* __arm__ && !_STLPORT_VERSION && !_GLIBCXX_USE_C99 */ +#endif /* !defined(__HORIZON__) || !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 3800 */ + +#if defined(__NV_GLIBCXX_VERSION) && __NV_GLIBCXX_VERSION < 40800 && !defined(__ibmxl__) + +#if !defined(_STLPORT_VERSION) +namespace __gnu_cxx +{ +#endif /* !_STLPORT_VERSION */ + +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int abs(long long int a); + +#if !defined(_STLPORT_VERSION) +} +#endif /* !_STLPORT_VERSION */ + +#endif /* defined(__NV_GLIBCXX_VERSION) && __NV_GLIBCXX_VERSION < 40800 && !__ibmxl__ */ + +namespace std +{ + template extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ T __pow_helper(T, int); + template extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ T __cmath_power(T, unsigned int); +} + +using std::abs; +using std::fabs; +using std::ceil; +using std::floor; +using std::sqrt; +#if !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 3800 +using std::pow; +#endif /* !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 3800 */ +using std::log; +using std::log10; +using std::fmod; +using std::modf; +using std::exp; +using std::frexp; +using std::ldexp; +using std::asin; +using std::sin; +using std::sinh; +using std::acos; +using std::cos; +using std::cosh; +using std::atan; +using std::atan2; +using std::tan; +using std::tanh; + +#elif defined(_WIN32) + +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ __CUDA_MATH_CRTIMP double __cdecl _hypot(double x, double y); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ __CUDA_MATH_CRTIMP float __cdecl _hypotf(float x, float y); + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __DEVICE_FUNCTIONS_DECL__ int signbit(long double a); +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if _MSC_VER >= 1900 +#define __SIGNBIT_THROW throw() +#else +#define __SIGNBIT_THROW +#endif +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool signbit(long double) __SIGNBIT_THROW; +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ __device_builtin__ __CUDA_MATH_CRTIMP int _ldsign(long double); +#undef __SIGNBIT_THROW +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Return the sign bit of the input. + * + * Determine whether the floating-point value \p a is negative. + * + * \return + * Reports the sign bit of all values including infinities, zeros, and NaNs. + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is negative. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a + * nonzero value if and only if \p a is negative. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE signbit(double a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +#if _MSC_VER >= 1900 +#define __SIGNBIT_THROW throw() +#else +#define __SIGNBIT_THROW +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Return the sign bit of the input. + * + * Determine whether the floating-point value \p a is negative. + * + * \return + * Reports the sign bit of all values including infinities, zeros, and NaNs. + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is negative. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a + * nonzero value if and only if \p a is negative. + */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ __RETURN_TYPE signbit(double) __SIGNBIT_THROW; +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ __device_builtin__ __CUDA_MATH_CRTIMP int _dsign(double); +#undef __RETURN_TYPE +#undef __SIGNBIT_THROW +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_SINGLE + * + * \brief Return the sign bit of the input. + * + * Determine whether the floating-point value \p a is negative. + * + * \return + * Reports the sign bit of all values including infinities, zeros, and NaNs. + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is negative. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a nonzero value + * if and only if \p a is negative. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE signbit(float a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +#if _MSC_VER >= 1900 +#define __SIGNBIT_THROW throw() +#else +#define __SIGNBIT_THROW +#endif +/** + * \ingroup CUDA_MATH_SINGLE + * + * \brief Return the sign bit of the input. + * + * Determine whether the floating-point value \p a is negative. + * + * \return + * Reports the sign bit of all values including infinities, zeros, and NaNs. + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is negative. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a nonzero value + * if and only if \p a is negative. + */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ __RETURN_TYPE signbit(float) __SIGNBIT_THROW; +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ __device_builtin__ __CUDA_MATH_CRTIMP int _fdsign(float); +#undef __RETURN_TYPE +#undef __SIGNBIT_THROW +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __DEVICE_FUNCTIONS_DECL__ int isinf(long double a); +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isinf(long double a); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Determine whether argument is infinite. + * + * Determine whether the floating-point value \p a is an infinite value + * (positive or negative). + * \return + * - With Visual Studio 2013 host compiler: Returns true if and only + * if \p a is an infinite value. + * - With other host compilers: Returns a nonzero value if and only + * if \p a is an infinite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isinf(double a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Determine whether argument is infinite. + * + * Determine whether the floating-point value \p a is an infinite value + * (positive or negative). + * \return + * - With Visual Studio 2013 host compiler: Returns true if and only + * if \p a is an infinite value. + * - With other host compilers: Returns a nonzero value if and only + * if \p a is an infinite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isinf(double a); +#undef __RETURN_TYPE +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_SINGLE + * + * \brief Determine whether argument is infinite. + * + * Determine whether the floating-point value \p a is an infinite value + * (positive or negative). + * + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is an infinite value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a nonzero + * value if and only if \p a is an infinite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isinf(float a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +/** + * \ingroup CUDA_MATH_SINGLE + * + * \brief Determine whether argument is infinite. + * + * Determine whether the floating-point value \p a is an infinite value + * (positive or negative). + * + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is an infinite value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a nonzero + * value if and only if \p a is an infinite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isinf(float a); +#undef __RETURN_TYPE +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __DEVICE_FUNCTIONS_DECL__ int isnan(long double a); +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isnan(long double a); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Determine whether argument is a NaN. + * + * Determine whether the floating-point value \p a is a NaN. + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. + * Returns true if and only if \p a is a NaN value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a + * nonzero value if and only if \p a is a NaN value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isnan(double a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Determine whether argument is a NaN. + * + * Determine whether the floating-point value \p a is a NaN. + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. + * Returns true if and only if \p a is a NaN value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a + * nonzero value if and only if \p a is a NaN value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isnan(double a); +#undef __RETURN_TYPE +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_SINGLE + * + * + * \brief Determine whether argument is a NaN. + * + * Determine whether the floating-point value \p a is a NaN. + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. + * Returns true if and only if \p a is a NaN value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a + * nonzero value if and only if \p a is a NaN value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isnan(float a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +/** + * \ingroup CUDA_MATH_SINGLE + * + * + * \brief Determine whether argument is a NaN. + * + * Determine whether the floating-point value \p a is a NaN. + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. + * Returns true if and only if \p a is a NaN value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a + * nonzero value if and only if \p a is a NaN value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isnan(float a); +#undef __RETURN_TYPE +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __DEVICE_FUNCTIONS_DECL__ int isfinite(long double a); +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isfinite(long double a); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Determine whether argument is finite. + * + * Determine whether the floating-point value \p a is a finite value + * (zero, subnormal, or normal and not infinity or NaN). + * + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is a finite value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns + * a nonzero value if and only if \p a is a finite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isfinite(double a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Determine whether argument is finite. + * + * Determine whether the floating-point value \p a is a finite value + * (zero, subnormal, or normal and not infinity or NaN). + * + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is a finite value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns + * a nonzero value if and only if \p a is a finite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isfinite(double a); +#undef __RETURN_TYPE +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Determine whether argument is finite. + * + * Determine whether the floating-point value \p a is a finite value + * (zero, subnormal, or normal and not infinity or NaN). + * + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is a finite value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns + * a nonzero value if and only if \p a is a finite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isfinite(float a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Determine whether argument is finite. + * + * Determine whether the floating-point value \p a is a finite value + * (zero, subnormal, or normal and not infinity or NaN). + * + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is a finite value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns + * a nonzero value if and only if \p a is a finite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isfinite(float a); +#undef __RETURN_TYPE +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +template extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ T _Pow_int(T, int); +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the absolute value of the input \p long \p long \p int argument. + * + * Calculate the absolute value of the input argument \p a. + * + * \return + * Returns the absolute value of the input argument. + * - abs(\p LLONG_MIN) is \p Undefined + */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int abs(long long int a); +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +template extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ T _Pow_int(T, int) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int abs(long long int) throw(); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#endif /* __CUDACC_RTC__ */ + +#if __cplusplus >= 201103L +#define __NV_NOEXCEPT noexcept +#else /* !__cplusplus >= 201103L */ +#define __NV_NOEXCEPT throw() +#endif /* __cplusplus >= 201103L */ + +#if defined(_LIBCPP_VERSION) && defined(_LIBCPP_BEGIN_NAMESPACE_STD) && !defined(_STLPORT_VERSION) +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wc++11-extensions" +#endif /* __clang__ */ +#if _LIBCPP_VERSION < 3800 +_LIBCPP_BEGIN_NAMESPACE_STD +#endif /* _LIBCPP_VERSION < 3800 */ +#elif defined(__GNUC__) && !defined(_STLPORT_VERSION) +namespace std { +#endif /* defined(_LIBCPP_VERSION) && defined(_LIBCPP_BEGIN_NAMESPACE_STD) && !defined(_STLPORT_VERSION) || + __GNUC__ && !_STLPORT_VERSION */ + +#if defined(__CUDACC_RTC__) || defined(__GNUC__) + +#if defined(__CUDACC_RTC__) || \ + (defined(__NV_GLIBCXX_VERSION) && __NV_GLIBCXX_VERSION >= 40800) || \ + defined(__ibmxl__) +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int abs(long long int); +#endif /* __CUDACC__RTC__ || + (defined(__NV_GLIBCXX_VERSION) && __NV_GLIBCXX_VERSION >= 40800) || + __ibmxl__ */ + +#endif /* __CUDACC_RTC__ || __GNUC__ */ + +#if defined(__CUDACC_RTC__) || \ + (!defined(_MSC_VER) || _MSC_VER < 1800) && \ + (!defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)) +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the absolute value of the input \p long \p int argument. + * + * Calculate the absolute value of the input argument \p a. + * + * \return + * Returns the absolute value of the input argument. + * - abs(\p LONG_MIN) is \p Undefined + */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long int __cdecl abs(long int a); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl abs(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ double __cdecl abs(double); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl fabs(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl ceil(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl floor(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl sqrt(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl pow(float, float); + +#if !defined(__QNX__) + +#if defined(__GNUC__) && __cplusplus >= 201103L && !defined(_LIBCPP_VERSION) +template +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ +typename __gnu_cxx::__promote_2<_Tp, _Up>::__type pow(_Tp, _Up); +#else /* !(defined(__GNUC__) && __cplusplus >= 201103L && !defined(_LIBCPP_VERSION)) */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl pow(float, int); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ double __cdecl pow(double, int); +#endif /* defined(__GNUC__) && __cplusplus >= 201103L && !defined(_LIBCPP_VERSION) */ + +#endif /* !defined(__QNX__) */ + +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl log(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl log10(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl fmod(float, float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl modf(float, float*); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl exp(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl frexp(float, int*); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl ldexp(float, int); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl asin(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl sin(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl sinh(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl acos(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl cos(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl cosh(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl atan(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl atan2(float, float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl tan(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl tanh(float); +#else /* __CUDACC_RTC__ || + (!defined(_MSC_VER) || _MSC_VER < 1800) && + (!defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)) */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long int __cdecl abs(long int) throw(); +#if defined(_LIBCPP_VERSION) +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int __cdecl abs(long long int) throw(); +#endif /* defined(_LIBCPP_VERSION) */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl abs(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ double __cdecl abs(double) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl fabs(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl ceil(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl floor(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl sqrt(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl pow(float, float) throw(); +#if defined(_LIBCPP_VERSION) +#if (defined (__ANDROID__) || defined(__HORIZON__)) && (_LIBCPP_VERSION >= 9000) +template +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ +#if _LIBCPP_VERSION >= 14000 +typename std::__enable_if_t +#else /* _LIBCPP_VERSION < 14000 */ +typename std::_EnableIf +#endif /* _LIBCPP_VERSION >= 14000 */ +< + std::is_arithmetic<_A1>::value && + std::is_arithmetic<_A2>::value, + std::__promote<_A1, _A2> +>::type pow(_A1 __lcpp_x, _A2 __lcpp_y) __NV_NOEXCEPT; +#elif (defined(__APPLE__) && __clang_major__ >= 7) || _LIBCPP_VERSION >= 3800 || defined(__QNX__) +template +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ +#if defined(__QNX__) && (_LIBCPP_VERSION >= 160000) +typename std::__enable_if_t < +#elif _LIBCPP_VERSION >= 13000 +typename std::enable_if < +#else /* #defined(__QNX__) && (_LIBCPP_VERSION >= 160000) */ +typename std::__lazy_enable_if < +#endif /* _LIBCPP_VERSION >= 160000 */ + std::is_arithmetic<_Tp>::value && std::is_arithmetic<_Up>::value, + std::__promote<_Tp, _Up> +>::type pow(_Tp __x, _Up __y) __NV_NOEXCEPT; +#else /* !((__APPLE__ && __clang_major__ >= 7) || _LIBCPP_VERSION >= 3800) */ +template +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ +typename enable_if < + std::is_arithmetic<_Tp>::value && std::is_arithmetic<_Up>::value, + typename std::__promote<_Tp, _Up>::type +>::type pow(_Tp __x, _Up __y) __NV_NOEXCEPT; +#endif /* (__APPLE__ && __clang_major__ >= 7) || _LIBCPP_VERSION >= 3800 */ +#else /* !defined(_LIBCPP_VERSION) */ +#if !(defined(__GNUC__) && __cplusplus >= 201103L) +#if (defined(_MSC_VER) && (_MSC_VER >= 1928)) && !(defined __CUDA_INTERNAL_SKIP_CPP_HEADERS__) +template && ::std:: is_arithmetic_v<_Ty2>, int> > [[nodiscard]] __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ ::std:: _Common_float_type_t<_Ty1, _Ty2> __cdecl pow(_Ty1 _Left, _Ty2 _Right) noexcept; +#else +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl pow(float, int) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ double __cdecl pow(double, int) throw(); +#endif /* (defined(_MSC_VER) && (_MSC_VER >= 1928)) && !(defined __CUDA_INTERNAL_SKIP_CPP_HEADERS__) */ +#endif /* !(defined(__GNUC__) && __cplusplus >= 201103L) */ +#endif /* defined(_LIBCPP_VERSION) */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl log(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl log10(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl fmod(float, float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl modf(float, float*) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl exp(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl frexp(float, int*) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl ldexp(float, int) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl asin(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl sin(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl sinh(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl acos(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl cos(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl cosh(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl atan(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl atan2(float, float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl tan(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl tanh(float) throw(); +#endif /* __CUDACC_RTC__ || + (!defined(_MSC_VER) || _MSC_VER < 1800) && + (!defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)) */ + +#if defined(_LIBCPP_VERSION) && defined(_LIBCPP_END_NAMESPACE_STD) && !defined(_STLPORT_VERSION) +#if _LIBCPP_VERSION < 3800 +_LIBCPP_END_NAMESPACE_STD +#endif /* _LIBCPP_VERSION < 3800 */ +#if defined(__clang__) +#pragma clang diagnostic pop +#endif /* __clang__ */ +#elif defined(__GNUC__) && !defined(_STLPORT_VERSION) +} +#endif /* defined(_LIBCPP_VERSION) && defined(_LIBCPP_BEGIN_NAMESPACE_STD) && !defined(_STLPORT_VERSION) || + __GNUC__ && !_STLPORT_VERSION */ + +#undef __DEVICE_FUNCTIONS_DECL__ +#undef __NV_NOEXCEPT + +#if defined(__CUDACC_RTC__) +#define __MATH_FUNCTIONS_DECL__ __host__ __device__ +#define __MATH_FUNCTIONS_DEVICE_DECL__ __device__ +#else /* __CUDACC_RTC__ */ +#define __MATH_FUNCTIONS_DECL__ static inline __host__ __device__ __cudart_builtin__ +#define __MATH_FUNCTIONS_DEVICE_DECL__ static inline __device__ __cudart_builtin__ +#endif /* __CUDACC_RTC__ */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#if defined(__QNX__) || (defined(_LIBCPP_VERSION) && _LIBCPP_VERSION >= 3800) +#if defined(__QNX__) && (!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 8000) +#if defined(_LIBCPP_VERSION) +#define __NV_NOEXCEPT _NOEXCEPT +_LIBCPP_BEGIN_NAMESPACE_STD +#else +#define __NV_NOEXCEPT +namespace std { +__host__ __device__ __cudart_builtin__ int ilogbf(float a); +#endif +#else /* !(defined(__QNX__) && (!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 8000)) */ +#define __NV_NOEXCEPT _NOEXCEPT +#endif /* defined(__QNX__) && (!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 8000) */ +__host__ __device__ __cudart_builtin__ float logb(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ int ilogb(float a) __NV_NOEXCEPT; + +__host__ __device__ __cudart_builtin__ float scalbn(float a, int b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float scalbln(float a, long int b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float exp2(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float expm1(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float log2(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float log1p(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float acosh(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float asinh(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float atanh(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float hypot(float a, float b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float cbrt(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float erf(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float erfc(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float lgamma(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float tgamma(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float copysign(float a, float b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float nextafter(float a, float b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float remainder(float a, float b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float remquo(float a, float b, int *quo) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float round(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ long int lround(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ long long int llround(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float trunc(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float rint(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ long int lrint(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ long long int llrint(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float nearbyint(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float fdim(float a, float b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float fma(float a, float b, float c) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float fmax(float a, float b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float fmin(float a, float b) __NV_NOEXCEPT; +#if defined(__QNX__) && (!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 8000) +#if defined(_LIBCPP_VERSION) +_LIBCPP_END_NAMESPACE_STD +using _VSTD::logb; +using _VSTD::ilogb; +using _VSTD::scalbn; +using _VSTD::scalbln; +using _VSTD::exp2; +using _VSTD::expm1; +using _VSTD::log2; +using _VSTD::log1p; +using _VSTD::acosh; +using _VSTD::asinh; +using _VSTD::atanh; +using _VSTD::hypot; +using _VSTD::cbrt; +using _VSTD::erf; +using _VSTD::erfc; +using _VSTD::lgamma; +using _VSTD::tgamma; +using _VSTD::copysign; +using _VSTD::nextafter; +using _VSTD::remainder; +using _VSTD::remquo; +using _VSTD::round; +using _VSTD::lround; +using _VSTD::llround; +using _VSTD::trunc; +using _VSTD::rint; +using _VSTD::lrint; +using _VSTD::llrint; +using _VSTD::nearbyint; +using _VSTD::fdim; +using _VSTD::fma; +using _VSTD::fmax; +using _VSTD::fmin; +#else +} +#endif +#endif /* defined(__QNX__) && (!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 8000) */ +#undef __NV_NOEXCEPT +#else /* !(defined(__QNX__ ) || (defined(_LIBCPP_VERSION) && _LIBCPP_VERSION >= 3800)) */ +#if ((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L) +namespace std { +__host__ __device__ __cudart_builtin__ constexpr float logb(float a); +__host__ __device__ __cudart_builtin__ constexpr int ilogb(float a); +__host__ __device__ __cudart_builtin__ constexpr float scalbn(float a, int b); +__host__ __device__ __cudart_builtin__ constexpr float scalbln(float a, long int b); +__host__ __device__ __cudart_builtin__ constexpr float exp2(float a); +__host__ __device__ __cudart_builtin__ constexpr float expm1(float a); +__host__ __device__ __cudart_builtin__ constexpr float log2(float a); +__host__ __device__ __cudart_builtin__ constexpr float log1p(float a); +__host__ __device__ __cudart_builtin__ constexpr float acosh(float a); +__host__ __device__ __cudart_builtin__ constexpr float asinh(float a); +__host__ __device__ __cudart_builtin__ constexpr float atanh(float a); +__host__ __device__ __cudart_builtin__ constexpr float hypot(float a, float b); +__host__ __device__ __cudart_builtin__ constexpr float cbrt(float a); +__host__ __device__ __cudart_builtin__ constexpr float erf(float a); +__host__ __device__ __cudart_builtin__ constexpr float erfc(float a); +__host__ __device__ __cudart_builtin__ constexpr float lgamma(float a); +__host__ __device__ __cudart_builtin__ constexpr float tgamma(float a); +__host__ __device__ __cudart_builtin__ constexpr float copysign(float a, float b); +__host__ __device__ __cudart_builtin__ constexpr float nextafter(float a, float b); +__host__ __device__ __cudart_builtin__ constexpr float remainder(float a, float b); +__host__ __device__ __cudart_builtin__ float remquo(float a, float b, int *quo); +__host__ __device__ __cudart_builtin__ constexpr float round(float a); +__host__ __device__ __cudart_builtin__ constexpr long int lround(float a); +__host__ __device__ __cudart_builtin__ constexpr long long int llround(float a); +__host__ __device__ __cudart_builtin__ constexpr float trunc(float a); +__host__ __device__ __cudart_builtin__ constexpr float rint(float a); +__host__ __device__ __cudart_builtin__ constexpr long int lrint(float a); +__host__ __device__ __cudart_builtin__ constexpr long long int llrint(float a); +__host__ __device__ __cudart_builtin__ constexpr float nearbyint(float a); +__host__ __device__ __cudart_builtin__ constexpr float fdim(float a, float b); +__host__ __device__ __cudart_builtin__ constexpr float fma(float a, float b, float c); +__host__ __device__ __cudart_builtin__ constexpr float fmax(float a, float b); +__host__ __device__ __cudart_builtin__ constexpr float fmin(float a, float b); +} +#else /* !(((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L)) */ +__MATH_FUNCTIONS_DECL__ float logb(float a); + +__MATH_FUNCTIONS_DECL__ int ilogb(float a); + +__MATH_FUNCTIONS_DECL__ float scalbn(float a, int b); + +__MATH_FUNCTIONS_DECL__ float scalbln(float a, long int b); + +__MATH_FUNCTIONS_DECL__ float exp2(float a); + +__MATH_FUNCTIONS_DECL__ float expm1(float a); + +__MATH_FUNCTIONS_DECL__ float log2(float a); + +__MATH_FUNCTIONS_DECL__ float log1p(float a); + +__MATH_FUNCTIONS_DECL__ float acosh(float a); + +__MATH_FUNCTIONS_DECL__ float asinh(float a); + +__MATH_FUNCTIONS_DECL__ float atanh(float a); + +__MATH_FUNCTIONS_DECL__ float hypot(float a, float b); + +__MATH_FUNCTIONS_DECL__ float cbrt(float a); + +__MATH_FUNCTIONS_DECL__ float erf(float a); + +__MATH_FUNCTIONS_DECL__ float erfc(float a); + +__MATH_FUNCTIONS_DECL__ float lgamma(float a); + +__MATH_FUNCTIONS_DECL__ float tgamma(float a); + +__MATH_FUNCTIONS_DECL__ float copysign(float a, float b); + +__MATH_FUNCTIONS_DECL__ float nextafter(float a, float b); + +__MATH_FUNCTIONS_DECL__ float remainder(float a, float b); + +__MATH_FUNCTIONS_DECL__ float remquo(float a, float b, int *quo); + +__MATH_FUNCTIONS_DECL__ float round(float a); + +__MATH_FUNCTIONS_DECL__ long int lround(float a); + +__MATH_FUNCTIONS_DECL__ long long int llround(float a); + +__MATH_FUNCTIONS_DECL__ float trunc(float a); + +__MATH_FUNCTIONS_DECL__ float rint(float a); + +__MATH_FUNCTIONS_DECL__ long int lrint(float a); + +__MATH_FUNCTIONS_DECL__ long long int llrint(float a); + +__MATH_FUNCTIONS_DECL__ float nearbyint(float a); + +__MATH_FUNCTIONS_DECL__ float fdim(float a, float b); + +__MATH_FUNCTIONS_DECL__ float fma(float a, float b, float c); + +__MATH_FUNCTIONS_DECL__ float fmax(float a, float b); + +__MATH_FUNCTIONS_DECL__ float fmin(float a, float b); +#endif /* ((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L) */ +#endif /* defined(__QNX__) || (defined(_LIBCPP_VERSION) && _LIBCPP_VERSION >= 3800) */ +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __host__ __device__ __cudart_builtin__ float __cdecl logb(float) throw(); +extern __host__ __device__ __cudart_builtin__ int __cdecl ilogb(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl scalbn(float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl scalbln(float, long int) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl exp2(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl expm1(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl log2(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl log1p(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl acosh(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl asinh(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl atanh(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl hypot(float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl cbrt(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl erf(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl erfc(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl lgamma(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl tgamma(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl copysign(float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl nextafter(float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl remainder(float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl remquo(float, float, int *) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl round(float) throw(); +extern __host__ __device__ __cudart_builtin__ long int __cdecl lround(float) throw(); +extern __host__ __device__ __cudart_builtin__ long long int __cdecl llround(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl trunc(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl rint(float) throw(); +extern __host__ __device__ __cudart_builtin__ long int __cdecl lrint(float) throw(); +extern __host__ __device__ __cudart_builtin__ long long int __cdecl llrint(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl nearbyint(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl fdim(float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl fma(float, float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl fmax(float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl fmin(float, float) throw(); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +__MATH_FUNCTIONS_DECL__ float exp10(const float a); + +__MATH_FUNCTIONS_DECL__ float rsqrt(const float a); + +__MATH_FUNCTIONS_DECL__ float rcbrt(const float a); + +__MATH_FUNCTIONS_DECL__ float sinpi(const float a); + +__MATH_FUNCTIONS_DECL__ float cospi(const float a); + +__MATH_FUNCTIONS_DECL__ void sincospi(const float a, float *const sptr, float *const cptr); + +__MATH_FUNCTIONS_DECL__ void sincos(const float a, float *const sptr, float *const cptr); + +__MATH_FUNCTIONS_DECL__ float j0(const float a); + +__MATH_FUNCTIONS_DECL__ float j1(const float a); + +__MATH_FUNCTIONS_DECL__ float jn(const int n, const float a); + +__MATH_FUNCTIONS_DECL__ float y0(const float a); + +__MATH_FUNCTIONS_DECL__ float y1(const float a); + +__MATH_FUNCTIONS_DECL__ float yn(const int n, const float a); + +__MATH_FUNCTIONS_DEVICE_DECL__ float cyl_bessel_i0(const float a); + +__MATH_FUNCTIONS_DEVICE_DECL__ float cyl_bessel_i1(const float a); + +__MATH_FUNCTIONS_DECL__ float erfinv(const float a); + +__MATH_FUNCTIONS_DECL__ float erfcinv(const float a); + +__MATH_FUNCTIONS_DECL__ float normcdfinv(const float a); + +__MATH_FUNCTIONS_DECL__ float normcdf(const float a); + +__MATH_FUNCTIONS_DECL__ float erfcx(const float a); + +__MATH_FUNCTIONS_DECL__ double copysign(const double a, const float b); + +__MATH_FUNCTIONS_DECL__ double copysign(const float a, const double b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ unsigned int min(const unsigned int a, const unsigned int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p int and \p unsigned \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned int min(const int a, const unsigned int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p int and \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned int min(const unsigned int a, const int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ long int min(const long int a, const long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ unsigned long int min(const unsigned long int a, const unsigned long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p long \p int and \p unsigned \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long int min(const long int a, const unsigned long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p long \p int and \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long int min(const unsigned long int a, const long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p long \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ long long int min(const long long int a, const long long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p long \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ unsigned long long int min(const unsigned long long int a, const unsigned long long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p long \p long \p int and \p unsigned \p long \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long long int min(const long long int a, const unsigned long long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p long \p long \p int and \p long \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long long int min(const unsigned long long int a, const long long int b); + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the minimum value of the input \p float arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + * Behavior is equivalent to ::fminf() function. + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ float min(const float a, const float b); + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the minimum value of the input \p float arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + * Behavior is equivalent to ::fmin() function. + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ double min(const double a, const double b); + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the minimum value of the input \p float and \p double arguments. + * + * Convert \p float argument \p a to \p double, followed by ::fmin(). + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ double min(const float a, const double b); + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the minimum value of the input \p double and \p float arguments. + * + * Convert \p float argument \p b to \p double, followed by ::fmin(). + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ double min(const double a, const float b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ unsigned int max(const unsigned int a, const unsigned int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p int and \p unsigned \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned int max(const int a, const unsigned int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p int and \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned int max(const unsigned int a, const int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ long int max(const long int a, const long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ unsigned long int max(const unsigned long int a, const unsigned long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p long \p int and \p unsigned \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long int max(const long int a, const unsigned long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p long \p int and \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long int max(const unsigned long int a, const long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p long \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ long long int max(const long long int a, const long long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p long \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ unsigned long long int max(const unsigned long long int a, const unsigned long long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p long \p long \p int and \p unsigned \p long \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long long int max(const long long int a, const unsigned long long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p long \p long \p int and \p long \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long long int max(const unsigned long long int a, const long long int b); + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the maximum value of the input \p float arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + * Behavior is equivalent to ::fmaxf() function. + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ float max(const float a, const float b); + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the maximum value of the input \p float arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + * Behavior is equivalent to ::fmax() function. + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ double max(const double a, const double b); + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the maximum value of the input \p float and \p double arguments. + * + * Convert \p float argument \p a to \p double, followed by ::fmax(). + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ double max(const float a, const double b); + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the maximum value of the input \p double and \p float arguments. + * + * Convert \p float argument \p b to \p double, followed by ::fmax(). + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ double max(const double a, const float b); + +#undef __MATH_FUNCTIONS_DECL__ +#undef __MATH_FUNCTIONS_DEVICE_DECL__ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ +#undef EXCLUDE_FROM_RTC + +extern "C"{ +inline __device__ void *__nv_aligned_device_malloc(size_t size, size_t align) +{ + __device__ void *__nv_aligned_device_malloc_impl(size_t, size_t); + return __nv_aligned_device_malloc_impl(size, align); +} +} + +#endif /* __cplusplus && __CUDACC__ */ + +#define EXCLUDE_FROM_RTC + +#if !defined(__CUDACC__) + +/******************************************************************************* +* * +* ONLY FOR HOST CODE! NOT FOR DEVICE EXECUTION * +* * +*******************************************************************************/ + +#include + +#if defined(_WIN32) +#pragma warning (push) +#pragma warning (disable : 4211) + +#endif /* _WIN32 */ + +__func__(double rsqrt(double a)); + +__func__(double rcbrt(double a)); + +__func__(double sinpi(double a)); + +__func__(double cospi(double a)); + +__func__(void sincospi(double a, double *sptr, double *cptr)); + +__func__(double erfinv(double a)); + +__func__(double erfcinv(double a)); + +__func__(double normcdfinv(double a)); + +__func__(double normcdf(double a)); + +__func__(double erfcx(double a)); + +__func__(float rsqrtf(float a)); + +__func__(float rcbrtf(float a)); + +__func__(float sinpif(float a)); + +__func__(float cospif(float a)); + +__func__(void sincospif(float a, float *sptr, float *cptr)); + +__func__(float erfinvf(float a)); + +__func__(float erfcinvf(float a)); + +__func__(float normcdfinvf(float a)); + +__func__(float normcdff(float a)); + +__func__(float erfcxf(float a)); + +__func__(int min(int a, int b)); + +__func__(unsigned int umin(unsigned int a, unsigned int b)); + +__func__(long long int llmin(long long int a, long long int b)); + +__func__(unsigned long long int ullmin(unsigned long long int a, unsigned long long int b)); + +__func__(int max(int a, int b)); + +__func__(unsigned int umax(unsigned int a, unsigned int b)); + +__func__(long long int llmax(long long int a, long long int b)); + +__func__(unsigned long long int ullmax(unsigned long long int a, unsigned long long int b)); + +#if defined(_WIN32) || defined(__APPLE__) || defined (__ANDROID__) + +__func__(int __isnan(double a)); + +#endif /* _WIN32 || __APPLE__ || __ANDROID__ */ + +#if defined(_WIN32) || defined(__APPLE__) || defined (__QNX__) + +__func__(void sincos(double a, double *sptr, double *cptr)); + +#endif /* _WIN32 || __APPLE__ || __QNX__ */ + +#if defined(_WIN32) || defined(__APPLE__) + +__func__(double exp10(double a)); + +__func__(float exp10f(float a)); + +__func__(void sincosf(float a, float *sptr, float *cptr)); + +__func__(int __isinf(double a)); + +#endif /* _WIN32 || __APPLE__ */ + +#if (defined(_WIN32) && (!defined(_MSC_VER) || _MSC_VER < 1800)) || defined (__ANDROID__) + +__func__(double log2(double a)); + +#endif /* (_WIN32 && (!defined(_MSC_VER) || _MSC_VER < 1800)) || __ANDROID__ */ + +#if defined(_WIN32) + +__func__(int __signbit(double a)); + +__func__(int __finite(double a)); + +__func__(int __signbitl(long double a)); + +__func__(int __signbitf(float a)); + +__func__(int __finitel(long double a)); + +__func__(int __finitef(float a)); + +__func__(int __isinfl(long double a)); + +__func__(int __isinff(float a)); + +__func__(int __isnanl(long double a)); + +__func__(int __isnanf(float a)); + +#endif /* _WIN32 */ + +#if defined(_WIN32) && (!defined(_MSC_VER) || _MSC_VER < 1800) + +__func__(double copysign(double a, double b)); + +__func__(double fmax(double a, double b)); + +__func__(double fmin(double a, double b)); + +__func__(double trunc(double a)); + +__func__(double round(double a)); + +__func__(long int lround(double a)); + +__func__(long long int llround(double a)); + +__func__(double rint(double a)); + +__func__(double nearbyint(double a)); + +__func__(long int lrint(double a)); + +__func__(long long int llrint(double a)); + +__func__(double fdim(double a, double b)); + +__func__(double scalbn(double a, int b)); + +__func__(double scalbln(double a, long int b)); + +__func__(double exp2(double a)); + +__func__(double log1p(double a)); + +__func__(double expm1(double a)); + +__func__(double cbrt(double a)); + +__func__(double acosh(double a)); + +__func__(double asinh(double a)); + +__func__(double atanh(double a)); + +__func__(int ilogb(double a)); + +__func__(double logb(double a)); + +__func__(double remquo(double a, double b, int *quo)); + +__func__(double remainder(double a, double b)); + +__func__(double fma (double a, double b, double c)); + +__func__(double nextafter(double a, double b)); + +__func__(double erf(double a)); + +__func__(double erfc(double a)); + +__func__(double lgamma(double a)); + +__func__(unsigned long long int __internal_host_nan_kernel(const char *s)); + +__func__(double nan(const char *tagp)); + +__func__(double __host_tgamma_kernel(double a)); + +__func__(double __host_stirling_poly(double a)); + +__func__(double __host_tgamma_stirling(double a)); + +__func__(double tgamma(double a)); + +__func__(float fmaxf(float a, float b)); + +__func__(float fminf(float a, float b)); + +__func__(float roundf(float a)); + +__func__(long int lroundf(float a)); + +__func__(long long int llroundf(float a)); + +__func__(float truncf(float a)); + +__func__(float rintf(float a)); + +__func__(float nearbyintf(float a)); + +__func__(long int lrintf(float a)); + +__func__(long long int llrintf(float a)); + +__func__(float logbf(float a)); + +__func__(float scalblnf(float a, long int b)); + +__func__(float log2f(float a)); + +__func__(float exp2f(float a)); + +__func__(float acoshf(float a)); + +__func__(float asinhf(float a)); + +__func__(float atanhf(float a)); + +__func__(float cbrtf(float a)); + +__func__(float expm1f(float a)); + +__func__(float fdimf(float a, float b)); + +__func__(float log1pf(float a)); + +__func__(float scalbnf(float a, int b)); + +__func__(float fmaf(float a, float b, float c)); + +__func__(int ilogbf(float a)); + +__func__(float erff(float a)); + +__func__(float erfcf(float a)); + +__func__(float lgammaf(float a)); + +__func__(float tgammaf(float a)); + +__func__(float remquof(float a, float b, int *quo)); + +__func__(float remainderf(float a, float b)); + +__func__(float copysignf(float a, float b)); + +__func__(float nextafterf(float a, float b)); + +__func__(float nanf(const char *tagp)); + +#endif /* _WIN32 && (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if defined(_WIN32) +#pragma warning (pop) +#endif /* _WIN32 */ + +#endif /* !__CUDACC__ */ + +#undef EXCLUDE_FROM_RTC + +#if !defined(__CUDACC_RTC__) + +#include "math_functions.hpp" + +#endif /* !__CUDACC_RTC__ */ + +#endif /* !__MATH_FUNCTIONS_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_MATH_FUNCTIONS_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_MATH_FUNCTIONS_H__ +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_100_rt.hpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_100_rt.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a5d620bf0b8091e0ea6cd48da00e8689b92cdd88 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_100_rt.hpp @@ -0,0 +1,157 @@ +/* + * Copyright 2024 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/sm_100_rt.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/sm_100_rt.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_100_RT_HPP__ +#endif + +#if !defined(__SM_100_RT_HPP__) +#define __SM_100_RT_HPP__ + +#if defined(__CUDACC_RTC__) +#define __SM_100_RT_DECL__ __host__ __device__ +#else /* !__CUDACC_RTC__ */ +#define __SM_100_RT_DECL__ static __device__ __inline__ +#endif /* __CUDACC_RTC__ */ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 1000 + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "device_types.h" +#include "host_defines.h" + +/******************************************************************************* +* * +* Below are implementations of SM-10.0 builtin functions which are included * +* as source (instead of being built in to the compiler) * +* * +*******************************************************************************/ + +extern "C" { + __device__ __device_builtin__ float2 __ffma2_rn_impl(float2 x, float2 y, float2 z); + __device__ __device_builtin__ float2 __ffma2_rz_impl(float2 x, float2 y, float2 z); + __device__ __device_builtin__ float2 __ffma2_rd_impl(float2 x, float2 y, float2 z); + __device__ __device_builtin__ float2 __ffma2_ru_impl(float2 x, float2 y, float2 z); + + __device__ __device_builtin__ float2 __fadd2_rn_impl(float2 x, float2 y); + __device__ __device_builtin__ float2 __fadd2_rz_impl(float2 x, float2 y); + __device__ __device_builtin__ float2 __fadd2_rd_impl(float2 x, float2 y); + __device__ __device_builtin__ float2 __fadd2_ru_impl(float2 x, float2 y); + + __device__ __device_builtin__ float2 __fmul2_rn_impl(float2 x, float2 y); + __device__ __device_builtin__ float2 __fmul2_rz_impl(float2 x, float2 y); + __device__ __device_builtin__ float2 __fmul2_rd_impl(float2 x, float2 y); + __device__ __device_builtin__ float2 __fmul2_ru_impl(float2 x, float2 y); +} // extern "C" + +__SM_100_RT_DECL__ float2 __ffma2_rn(float2 x, float2 y, float2 z) { + return __ffma2_rn_impl(x, y, z); +} +__SM_100_RT_DECL__ float2 __ffma2_rz(float2 x, float2 y, float2 z) { + return __ffma2_rz_impl(x, y, z); +} +__SM_100_RT_DECL__ float2 __ffma2_rd(float2 x, float2 y, float2 z) { + return __ffma2_rd_impl(x, y, z); +} +__SM_100_RT_DECL__ float2 __ffma2_ru(float2 x, float2 y, float2 z) { + return __ffma2_ru_impl(x, y, z); +} + +__SM_100_RT_DECL__ float2 __fadd2_rn(float2 x, float2 y) { + return __fadd2_rn_impl(x, y); +} +__SM_100_RT_DECL__ float2 __fadd2_rz(float2 x, float2 y) { + return __fadd2_rz_impl(x, y); +} +__SM_100_RT_DECL__ float2 __fadd2_rd(float2 x, float2 y) { + return __fadd2_rd_impl(x, y); +} +__SM_100_RT_DECL__ float2 __fadd2_ru(float2 x, float2 y) { + return __fadd2_ru_impl(x, y); +} + +__SM_100_RT_DECL__ float2 __fmul2_rn(float2 x, float2 y) { + return __fmul2_rn_impl(x, y); +} +__SM_100_RT_DECL__ float2 __fmul2_rz(float2 x, float2 y) { + return __fmul2_rz_impl(x, y); +} +__SM_100_RT_DECL__ float2 __fmul2_rd(float2 x, float2 y) { + return __fmul2_rd_impl(x, y); +} +__SM_100_RT_DECL__ float2 __fmul2_ru(float2 x, float2 y) { + return __fmul2_ru_impl(x, y); +} + +#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 1000 */ + +#endif /* __cplusplus && __CUDACC__ */ + +#undef __SM_100_RT_DECL__ + +#endif /* !__SM_100_RT_HPP__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_100_RT_HPP__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_100_RT_HPP__ +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_70_rt.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_70_rt.h new file mode 100644 index 0000000000000000000000000000000000000000..6046953afa8c5f71cf7058436de10397d6353e9e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_70_rt.h @@ -0,0 +1,139 @@ +/* + * Copyright 2017-2018 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + + //NOTE: For NVRTC, these declarations have been moved into the compiler (to reduce compile time) +#define EXCLUDE_FROM_RTC + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/sm_70_rt.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/sm_70_rt.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_70_RT_H__ +#endif + +#if !defined(__SM_70_RT_H__) +#define __SM_70_RT_H__ + +#if defined(__CUDACC_RTC__) +#define __SM_70_RT_DECL__ __host__ __device__ +#elif defined(_NVHPC_CUDA) +#define __SM_70_RT_DECL__ extern __device__ __cudart_builtin__ +#else /* !__CUDACC_RTC__ */ +#define __SM_70_RT_DECL__ static __device__ __inline__ +#endif /* __CUDACC_RTC__ */ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700 + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "device_types.h" +#include "host_defines.h" + +#if !defined(__CUDA_ARCH__) && !defined(_NVHPC_CUDA) +#define __DEF_IF_HOST { } +#else /* !__CUDA_ARCH__ */ +#define __DEF_IF_HOST ; +#endif /* __CUDA_ARCH__ */ + + +/****************************************************************************** + * match * + ******************************************************************************/ +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, unsigned value) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, int value) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, unsigned long value) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, long value) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, unsigned long long value) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, long long value) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, float value) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, double value) __DEF_IF_HOST + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, unsigned value, int *pred) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, int value, int *pred) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, unsigned long value, int *pred) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, long value, int *pred) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, unsigned long long value, int *pred) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, long long value, int *pred) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, float value, int *pred) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, double value, int *pred) __DEF_IF_HOST + +__SM_70_RT_DECL__ void __nanosleep(unsigned int ns) __DEF_IF_HOST + +__SM_70_RT_DECL__ unsigned short int atomicCAS(unsigned short int *address, unsigned short int compare, unsigned short int val) __DEF_IF_HOST + +#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 700 */ + +#endif /* __cplusplus && __CUDACC__ */ + +#undef __DEF_IF_HOST +#undef __SM_70_RT_DECL__ + +#if (!defined(__CUDACC_RTC__) && defined(__CUDA_ARCH__)) || defined(_NVHPC_CUDA) +#include "sm_70_rt.hpp" +#endif /* (!defined(__CUDACC_RTC__) && defined(__CUDA_ARCH__)) || defined(_NVHPC_CUDA) */ + +#endif /* !__SM_70_RT_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_70_RT_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_70_RT_H__ +#endif + + +#undef EXCLUDE_FROM_RTC \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_70_rt.hpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_70_rt.hpp new file mode 100644 index 0000000000000000000000000000000000000000..322496587325a1387e4280a509455e3ccc7caa1b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_70_rt.hpp @@ -0,0 +1,192 @@ +/* + * Copyright 2017-2021 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/sm_70_rt.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/sm_70_rt.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_70_RT_HPP__ +#endif + +#if !defined(__SM_70_RT_HPP__) +#define __SM_70_RT_HPP__ + +#if defined(__CUDACC_RTC__) +#define __SM_70_RT_DECL__ __host__ __device__ +#else /* !__CUDACC_RTC__ */ +#define __SM_70_RT_DECL__ static __device__ __inline__ +#endif /* __CUDACC_RTC__ */ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700 + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "device_types.h" +#include "host_defines.h" + +/******************************************************************************* +* * +* Below are implementations of SM-7.0 builtin functions which are included as * +* source (instead of being built in to the compiler) * +* * +*******************************************************************************/ + +// +// __match_any_sync +// +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, unsigned value) { + return __match32_any_sync(mask, value); +} + +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, int value) { + return __match32_any_sync(mask, value); +} + +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, unsigned long value) { + return (sizeof(long) == sizeof(long long)) ? + __match64_any_sync(mask, (unsigned long long)value): + __match32_any_sync(mask, (unsigned)value); +} + +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, long value) { + return (sizeof(long) == sizeof(long long)) ? + __match64_any_sync(mask, (unsigned long long)value): + __match32_any_sync(mask, (unsigned)value); +} + +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, unsigned long long value) { + return __match64_any_sync(mask, value); +} + +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, long long value) { + return __match64_any_sync(mask, value); +} + +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, float value) { + return __match32_any_sync(mask, __float_as_uint(value)); +} + +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, double value) { + return __match64_any_sync(mask, __double_as_longlong(value)); +} + +// +// __match_all_sync +// +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, unsigned value, int *pred) { + return __match32_all_sync(mask, value, pred); +} + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, int value, int *pred) { + return __match32_all_sync(mask, value, pred); +} + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, unsigned long value, int *pred) { + return (sizeof(long) == sizeof(long long)) ? + __match64_all_sync(mask, (unsigned long long)value, pred): + __match32_all_sync(mask, (unsigned)value, pred); +} + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, long value, int *pred) { + return (sizeof(long) == sizeof(long long)) ? + __match64_all_sync(mask, (unsigned long long)value, pred): + __match32_all_sync(mask, (unsigned)value, pred); +} + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, unsigned long long value, int *pred) { + return __match64_all_sync(mask, value, pred); +} + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, long long value, int *pred) { + return __match64_all_sync(mask, value, pred); +} + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, float value, int *pred) { + return __match32_all_sync(mask, __float_as_uint(value), pred); +} + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, double value, int *pred) { + return __match64_all_sync(mask, __double_as_longlong(value), pred); +} + +__SM_70_RT_DECL__ void __nanosleep(unsigned int ns) { + asm volatile("nanosleep.u32 %0;" :: "r"(ns)); +} + + +extern "C" __device__ __device_builtin__ +unsigned short __usAtomicCAS(unsigned short *, unsigned short, unsigned short); + +__SM_70_RT_DECL__ unsigned short int atomicCAS(unsigned short int *address, unsigned short int compare, unsigned short int val) { + return __usAtomicCAS(address, compare, val); +} + + +#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 700 */ + +#endif /* __cplusplus && __CUDACC__ */ + +#undef __SM_70_RT_DECL__ + +#endif /* !__SM_70_RT_HPP__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_70_RT_HPP__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_70_RT_HPP__ +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_90_rt.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_90_rt.h new file mode 100644 index 0000000000000000000000000000000000000000..8e250634fe76651c2a15b5b492378efec1d3e0c5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_90_rt.h @@ -0,0 +1,282 @@ +/* + * Copyright 2022-2023 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/sm_90_rt.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/sm_90_rt.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_90_RT_H__ +#endif + +#if !defined(__SM_90_RT_H__) +#define __SM_90_RT_H__ + +#if defined(__CUDACC_RTC__) +#define __SM_90_RT_DECL__ __host__ __device__ +#else /* !__CUDACC_RTC__ */ +#define __SM_90_RT_DECL__ static __device__ __inline__ +#endif /* __CUDACC_RTC__ */ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 900 + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "device_types.h" +#include "host_defines.h" + +#if !defined(__CUDA_ARCH__) && !defined(_NVHPC_CUDA) +#define __DEF_IF_HOST { } +#else /* !__CUDA_ARCH__ && !_NVHPC_CUDA */ +#define __DEF_IF_HOST ; +#endif /* __CUDA_ARCH__ || _NVHPC_CUDA */ + +//NOTE: For NVRTC, these declarations have been moved into the compiler (to reduce compile time) +#define EXCLUDE_FROM_RTC + +__SM_90_RT_DECL__ unsigned __isCtaShared(const void *ptr) __DEF_IF_HOST +__SM_90_RT_DECL__ unsigned __isClusterShared(const void *ptr) __DEF_IF_HOST +__SM_90_RT_DECL__ void *__cluster_map_shared_rank(const void *ptr, unsigned target_block_rank) __DEF_IF_HOST +__SM_90_RT_DECL__ unsigned __cluster_query_shared_rank(const void *ptr) __DEF_IF_HOST +__SM_90_RT_DECL__ uint2 __cluster_map_shared_multicast(const void *ptr, unsigned cluster_cta_mask) __DEF_IF_HOST +__SM_90_RT_DECL__ unsigned __clusterDimIsSpecified() __DEF_IF_HOST +__SM_90_RT_DECL__ dim3 __clusterDim() __DEF_IF_HOST +__SM_90_RT_DECL__ dim3 __clusterRelativeBlockIdx() __DEF_IF_HOST +__SM_90_RT_DECL__ dim3 __clusterGridDimInClusters() __DEF_IF_HOST +__SM_90_RT_DECL__ dim3 __clusterIdx() __DEF_IF_HOST +__SM_90_RT_DECL__ unsigned __clusterRelativeBlockRank() __DEF_IF_HOST +__SM_90_RT_DECL__ unsigned __clusterSizeInBlocks() __DEF_IF_HOST +__SM_90_RT_DECL__ void __cluster_barrier_arrive() __DEF_IF_HOST +__SM_90_RT_DECL__ void __cluster_barrier_arrive_relaxed() __DEF_IF_HOST +__SM_90_RT_DECL__ void __cluster_barrier_wait() __DEF_IF_HOST +__SM_90_RT_DECL__ void __threadfence_cluster() __DEF_IF_HOST + +__SM_90_RT_DECL__ float2 atomicAdd(float2 *__address, float2 val) __DEF_IF_HOST +__SM_90_RT_DECL__ float2 atomicAdd_block(float2 *__address, float2 val) __DEF_IF_HOST +__SM_90_RT_DECL__ float2 atomicAdd_system(float2 *__address, float2 val) __DEF_IF_HOST +__SM_90_RT_DECL__ float4 atomicAdd(float4 *__address, float4 val) __DEF_IF_HOST +__SM_90_RT_DECL__ float4 atomicAdd_block(float4 *__address, float4 val) __DEF_IF_HOST +__SM_90_RT_DECL__ float4 atomicAdd_system(float4 *__address, float4 val) __DEF_IF_HOST + +#undef EXCLUDE_FROM_RTC + +//Note: below atomic functions are templates, so cannot be represented in NVRTC +//builtins representation, so they have to be parsed on every NVRTC compilation. +//(notice 'EXCLUDE_FROM_RTC' ends above) + + +#ifndef __NV_DISABLE_128_ATOMICS +// lgen definitions for 128b atomics +extern "C" { + __device__ __device_builtin__ void __u128AtomicCAS(void *, void *, void *, void *); + __device__ __device_builtin__ void __u128AtomicCAS_block(void *, void *, void *, void *); + __device__ __device_builtin__ void __u128AtomicCAS_system(void *, void *, void *, void *); + __device__ __device_builtin__ void __u128AtomicExch(void *, void *, void *); + __device__ __device_builtin__ void __u128AtomicExch_block(void *, void *, void *); + __device__ __device_builtin__ void __u128AtomicExch_system(void *, void *, void *); +} + +// macro to get address of object, to workaround situations where the type overloads the "&" operator +#define __NV_ATOMIC_ADDRESSOF(__val) \ + (void *)(&(const_cast(reinterpret_cast(__val)))) + +// enable_if +template +struct __nv_atomic_enable_if { }; + +template +struct __nv_atomic_enable_if { typedef _T __type; }; + +// alignof +#if defined(__CUDACC_RTC__) +#define __NV_ATOMIC_ALIGNOF __alignof__ +#else +#define __NV_ATOMIC_ALIGNOF __alignof +#endif + +// trivially copyable +template +struct __nv_atomic_triv_cp_helper { +#if defined(__GNUC__) +#if (__GNUC__ < 4) || (__GNUC__ == 4 && __GNUC_MINOR__ < 3) + static const bool __val = true; +#elif (__GNUC__ < 5) + static const bool __val = __has_trivial_copy(_T); +#else + static const bool __val = __is_trivially_copyable(_T); +#endif +#else + static const bool __val = __is_trivially_copyable(_T); +#endif +}; +#define __NV_ATOMIC_TRIVIALLY_COPYABLE(_T) \ + __nv_atomic_triv_cp_helper<_T>::__val + +// return type +#if __cplusplus >= 202002L // C++20 or greater +#define __NV_ATOMIC_RET_TYPE(_T) _T +#else +#define __NV_ATOMIC_RET_TYPE(_T) typename \ + __nv_atomic_enable_if= 16 && \ + __NV_ATOMIC_TRIVIALLY_COPYABLE(_T), _T>::__type +#endif + +// requires +#if __cplusplus >= 202002L // C++20 or greater +#define __NV_ATOMIC_REQUIRES(_T) \ + requires(sizeof(_T) == 16 && \ + __NV_ATOMIC_ALIGNOF(_T) >= 16 && \ + __NV_ATOMIC_TRIVIALLY_COPYABLE(_T)) +#else +#define __NV_ATOMIC_REQUIRES(_T) +#endif + +// temp value and return value +#if __cplusplus >= 201103L || defined(_MSC_VER) // C++11 or greater, or MSC +#define __NV_ATOMIC_TEMP(_T) union _U \ + {_T __ret; __device__ __inline__ _U() {}}; _U __u +#define __NV_ATOMIC_RET(_T) __u.__ret +#else +#define __NV_ATOMIC_TEMP(_T) _T __ret +#define __NV_ATOMIC_RET(_T) __ret +#endif + +// templated 128-bit atomics +template +__SM_90_RT_DECL__ __NV_ATOMIC_RET_TYPE(_T) +atomicCAS(_T *__address, _T __compare, _T __val) __NV_ATOMIC_REQUIRES(_T) { + __NV_ATOMIC_TEMP(_T); + __u128AtomicCAS((void *)(__address), + __NV_ATOMIC_ADDRESSOF(__compare), + __NV_ATOMIC_ADDRESSOF(__val), + __NV_ATOMIC_ADDRESSOF(__NV_ATOMIC_RET(_T))); + return __NV_ATOMIC_RET(_T); +} + +template +__SM_90_RT_DECL__ __NV_ATOMIC_RET_TYPE(_T) +atomicCAS_block(_T *__address, _T __compare, _T __val) __NV_ATOMIC_REQUIRES(_T) { + __NV_ATOMIC_TEMP(_T); + __u128AtomicCAS_block((void *)(__address), + __NV_ATOMIC_ADDRESSOF(__compare), + __NV_ATOMIC_ADDRESSOF(__val), + __NV_ATOMIC_ADDRESSOF(__NV_ATOMIC_RET(_T))); + return __NV_ATOMIC_RET(_T); +} + +template +__SM_90_RT_DECL__ __NV_ATOMIC_RET_TYPE(_T) +atomicCAS_system(_T *__address, _T __compare, _T __val) __NV_ATOMIC_REQUIRES(_T) { + __NV_ATOMIC_TEMP(_T); + __u128AtomicCAS_system((void *)(__address), + __NV_ATOMIC_ADDRESSOF(__compare), + __NV_ATOMIC_ADDRESSOF(__val), + __NV_ATOMIC_ADDRESSOF(__NV_ATOMIC_RET(_T))); + return __NV_ATOMIC_RET(_T); +} + +template +__SM_90_RT_DECL__ __NV_ATOMIC_RET_TYPE(_T) +atomicExch(_T *__address, _T __val) __NV_ATOMIC_REQUIRES(_T) { + __NV_ATOMIC_TEMP(_T); + __u128AtomicExch((void *)(__address), + __NV_ATOMIC_ADDRESSOF(__val), + __NV_ATOMIC_ADDRESSOF(__NV_ATOMIC_RET(_T))); + return __NV_ATOMIC_RET(_T); +} + +template +__SM_90_RT_DECL__ __NV_ATOMIC_RET_TYPE(_T) +atomicExch_block(_T *__address, _T __val) __NV_ATOMIC_REQUIRES(_T) { + __NV_ATOMIC_TEMP(_T); + __u128AtomicExch_block((void *)(__address), + __NV_ATOMIC_ADDRESSOF(__val), + __NV_ATOMIC_ADDRESSOF(__NV_ATOMIC_RET(_T))); + return __NV_ATOMIC_RET(_T); +} + +template +__SM_90_RT_DECL__ __NV_ATOMIC_RET_TYPE(_T) +atomicExch_system(_T *__address, _T __val) __NV_ATOMIC_REQUIRES(_T) { + __NV_ATOMIC_TEMP(_T); + __u128AtomicExch_system((void *)(__address), + __NV_ATOMIC_ADDRESSOF(__val), + __NV_ATOMIC_ADDRESSOF(__NV_ATOMIC_RET(_T))); + return __NV_ATOMIC_RET(_T); +} +#endif /* !__NV_DISABLE_128_ATOMICS */ + +#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 900 */ + +#endif /* __cplusplus && __CUDACC__ */ + +#undef __DEF_IF_HOST +#undef __SM_90_RT_DECL__ + +#if (!defined(__CUDACC_RTC__) && defined(__CUDA_ARCH__)) || defined(_NVHPC_CUDA) +#include "sm_90_rt.hpp" +#endif /* (!defined(__CUDACC_RTC__) && defined(__CUDA_ARCH__)) || defined(_NVHPC_CUDA) */ + +#endif /* !__SM_90_RT_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_90_RT_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_90_RT_H__ +#endif + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/storage_class.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/storage_class.h new file mode 100644 index 0000000000000000000000000000000000000000..1fb19bd46ebde4a53dfad866050fad9fb0cbd222 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/storage_class.h @@ -0,0 +1,142 @@ +/* + * NVIDIA_COPYRIGHT_BEGIN + * + * Copyright (c) 2008-2018, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + * + * NVIDIA_COPYRIGHT_END + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/storage_class.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/storage_class.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_STORAGE_CLASS_H__ +#endif + +#if !defined(__STORAGE_CLASS_H__) +#define __STORAGE_CLASS_H__ + +#if !defined(__var_used__) + +#define __var_used__ + +#endif /* __var_used__ */ + +#if !defined(__loc_sc__) + +#define __loc_sc__(loc, size, sc) \ + __storage##_##sc##size##loc loc + +#endif /* !__loc_sc__ */ + +#if !defined(__storage___device__) +#define __storage___device__ static __var_used__ +#endif /* __storage___device__ */ + +#if !defined(__storage_extern__device__) +#define __storage_extern__device__ static __var_used__ +#endif /* __storage_extern__device__ */ + +#if !defined(__storage_auto__device__) +#define __storage_auto__device__ @@@ COMPILER @@@ ERROR @@@ +#endif /* __storage_auto__device__ */ + +#if !defined(__storage_static__device__) +#define __storage_static__device__ static __var_used__ +#endif /* __storage_static__device__ */ + +#if !defined(__storage___constant__) +#define __storage___constant__ static __var_used__ +#endif /* __storage___constant__ */ + +#if !defined(__storage_extern__constant__) +#define __storage_extern__constant__ static __var_used__ +#endif /* __storage_extern__constant__ */ + +#if !defined(__storage_auto__constant__) +#define __storage_auto__constant__ @@@ COMPILER @@@ ERROR @@@ +#endif /* __storage_auto__constant__ */ + +#if !defined(__storage_static__constant__) +#define __storage_static__constant__ static __var_used__ +#endif /* __storage_static__constant__ */ + +#if !defined(__storage___shared__) +#define __storage___shared__ static __var_used__ +#endif /* __storage___shared__ */ + +#if !defined(__storage_extern__shared__) +#define __storage_extern__shared__ static __var_used__ +#endif /* __storage_extern__shared__ */ + +#if !defined(__storage_auto__shared__) +#define __storage_auto__shared__ static +#endif /* __storage_auto__shared__ */ + +#if !defined(__storage_static__shared__) +#define __storage_static__shared__ static __var_used__ +#endif /* __storage_static__shared__ */ + +#if !defined(__storage__unsized__shared__) +#define __storage__unsized__shared__ @@@ COMPILER @@@ ERROR @@@ +#endif /* __storage__unsized__shared__ */ + +#if !defined(__storage_extern_unsized__shared__) +#define __storage_extern_unsized__shared__ static __var_used__ +#endif /* __storage_extern_unsized__shared__ */ + +#if !defined(__storage_auto_unsized__shared__) +#define __storage_auto_unsized__shared__ @@@ COMPILER @@@ ERROR @@@ +#endif /* __storage_auto_unsized__shared__ */ + +#if !defined(__storage_static_unsized__shared__) +#define __storage_static_unsized__shared__ @@@ COMPILER @@@ ERROR @@@ +#endif /* __storage_static_unsized__shared__ */ + +#if !defined(__storage___text__) +#define __storage___text__ static __var_used__ +#endif /* __storage___text__ */ + +#if !defined(__storage_extern__text__) +#define __storage_extern__text__ static __var_used__ +#endif /* __storage_extern__text__ */ + +#if !defined(__storage_auto__text__) +#define __storage_auto__text__ @@@ COMPILER @@@ ERROR @@@ +#endif /* __storage_auto__text__ */ + +#if !defined(__storage_static__text__) +#define __storage_static__text__ static __var_used__ +#endif /* __storage_static__text__ */ + +#if !defined(__storage___surf__) +#define __storage___surf__ static __var_used__ +#endif /* __storage___surf__ */ + +#if !defined(__storage_extern__surf__) +#define __storage_extern__surf__ static __var_used__ +#endif /* __storage_extern__surf__ */ + +#if !defined(__storage_auto__surf__) +#define __storage_auto__surf__ @@@ COMPILER @@@ ERROR @@@ +#endif /* __storage_auto__surf__ */ + +#if !defined(__storage_static__surf__) +#define __storage_static__surf__ static __var_used__ +#endif /* __storage_static__surf__ */ + +#endif /* !__STORAGE_CLASS_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_STORAGE_CLASS_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_STORAGE_CLASS_H__ +#endif diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..127ccf90fbef0c9b89a1d899cedeecc6ed52b3e3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/__init__.py @@ -0,0 +1,7 @@ +from .compiler import CompiledKernel, ASTSource, IRSource, compile, make_backend, LazyDict, get_cache_key +from .errors import CompilationError + +__all__ = [ + "compile", "make_backend", "ASTSource", "IRSource", "CompiledKernel", "CompilationError", "LazyDict", + "get_cache_key" +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ba842217485ef2fb0c4f9f167bf440ed89c05b6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/__pycache__/compiler.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/__pycache__/compiler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3e67cd94dffa97d9ac52f044b84c1e337465c3c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/__pycache__/compiler.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/__pycache__/errors.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/__pycache__/errors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5afdbc35e918d23e0246be60f38e8eda12feb829 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/__pycache__/errors.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/code_generator.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/code_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..176b6b515043d3d6b6dadb50328b8fa68633018f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/code_generator.py @@ -0,0 +1,1614 @@ +import ast +import builtins +import contextlib +import copy +import inspect +import re +import warnings +import textwrap +import itertools +from dataclasses import dataclass +from types import ModuleType +from typing import Any, Callable, Dict, Optional, Tuple, Type, Union, Iterable, List + +from .. import knobs, language +from .._C.libtriton import ir, gluon_ir +from ..language import constexpr, str_to_ty, tensor, tuple as tl_tuple +from ..language.core import _unwrap_if_constexpr, base_value, base_type +# ideally we wouldn't need any runtime component +from ..runtime.jit import get_jit_fn_file_line, get_full_name, JITCallable, BoundConstexprFunction, ConstexprFunction, JITFunction +from .._utils import find_paths_if, get_iterable_path, set_iterable_path + +from .errors import (CompilationError, CompileTimeAssertionFailure, UnsupportedLanguageConstruct) + + +def check_identifier_legality(name, type): + pattern = r'^[a-zA-Z_][a-zA-Z0-9_]*$' + if not re.match(pattern, name): + raise CompilationError(f"invalid {type} identifier: {name}", name) + return name + + +def mangle_fn(name, arg_tys, constants, caller_context): + # doesn't mangle ret type, which must be a function of arg tys + mangled_arg_names = '_'.join([ty.mangle() for ty in arg_tys]) + mangled_constants = '_'.join([f'{i}c{repr(constants[i])}' for i in sorted(constants)]) + mangled_constants = mangled_constants.replace('.', '_d_') + mangled_constants = mangled_constants.replace("'", '_sq_') + # [ and ] are not allowed in LLVM identifiers + mangled_constants = mangled_constants.replace('[', '_').replace(']', '_') + ret = f'{name}__{mangled_arg_names}__{mangled_constants}' + if caller_context is not None: + ret += caller_context.mangle() + return ret + + +def _is_triton_value(o: Any) -> bool: + return isinstance(o, base_value) + + +def _is_triton_tensor(o: Any) -> bool: + return isinstance(o, tensor) + + +def _is_constexpr(o: Any) -> bool: + return o is None or isinstance(o, (constexpr, language.core.dtype, JITCallable)) + + +def _is_non_scalar_tensor(o: Any) -> bool: + return _is_triton_tensor(o) and (o.type.is_block() and o.type.numel != 1) + + +def _is_list_like(o: Any) -> bool: + return isinstance(o, (list, tuple)) + + +def _check_fn_args(node, fn, args): + if fn.noinline: + for idx, arg in enumerate(args): + if not _is_constexpr(arg) and _is_non_scalar_tensor(arg): + raise UnsupportedLanguageConstruct( + fn.src, node, + f'Function {fn.__name__} is marked noinline, but was called with non-scalar argument {fn.arg_names[idx]}:{arg}' + ) + + +def _is_namedtuple(val): + return isinstance(val, type) and issubclass(val, tuple) and hasattr(val, "_fields") + + +def _apply_to_tuple_values(value, fn): + if _is_namedtuple(type(value)): + fields = value._fields + elif isinstance(value, language.tuple): + fields = value.type.fields + else: + assert False, f"Unsupported type {type(value)}" + + vals = [fn(v) for v in value] + vals = [constexpr(v) if v is None else v for v in vals] + types = [v.type for v in vals] + return language.tuple(vals, language.tuple_type(types, fields)) + + +def flatten_values_to_ir(values: Iterable[base_value]): + handles = [] + for v in values: + v._flatten_ir(handles) + return handles + + +def unflatten_ir_values(handles: List[ir.value], types: List[base_type]): + cursor = 0 + for ty in types: + value, cursor = ty._unflatten_ir(handles, cursor) + yield value + assert cursor == len(handles) + + +_condition_types = {bool, int, type(None)} # Python types accepted for conditionals inside kernels + + +def _clone_triton_value(val): + handles = [] + val._flatten_ir(handles) + clone, _ = val.type._unflatten_ir(handles, 0) + return clone + + +def _clone_scope(scope): + return {name: _clone_triton_value(val) if _is_triton_value(val) else val for name, val in scope.items()} + + +class enter_sub_region: + + def __init__(self, generator): + self.generator = generator + + def __enter__(self): + # record lscope & local_defs in the parent scope + self.liveins = _clone_scope(self.generator.lscope) + self.prev_defs = _clone_scope(self.generator.local_defs) + self.generator.local_defs = {} + self.insert_block = self.generator.builder.get_insertion_block() + self.insert_point = self.generator.builder.get_insertion_point() + return self.liveins, self.insert_block + + def __exit__(self, *args, **kwargs): + self.generator.builder.restore_insertion_point(self.insert_point) + self.generator.lscope = self.liveins + self.generator.local_defs = self.prev_defs + + +# Check if the given syntax node has an "early" return +class ContainsReturnChecker(ast.NodeVisitor): + + def __init__(self, gscope): + self.gscope = gscope + + def _visit_stmts(self, body) -> bool: + return any(self.visit(s) for s in body) + + def _visit_function(self, fn) -> bool: + # No need to check within the function as it won't cause an early return. + # If the function itself has unstructured control flow we may not be able to inline it causing poor performance, + # we should check for this and emit a warning. + return False + + def generic_visit(self, node) -> bool: + ret = False + for _, value in ast.iter_fields(node): + if isinstance(value, list): + for item in value: + if isinstance(item, ast.AST): + ret = ret or self.visit(item) + elif isinstance(value, ast.AST): + ret = ret or self.visit(value) + return ret + + def visit_Attribute(self, node: ast.Attribute) -> bool: + # If the left part is a name, it's possible that + # we call triton native function or a jit function from another module. + # If the left part is not a name, it must return a tensor or a constexpr + # whose methods do not contain return statements + # e.g., (tl.load(x)).to(y) + # So we only check if the expressions within value have return or not + if isinstance(node.value, ast.Name): + if node.value.id in self.gscope: + value = self.gscope[node.value.id] + fn = getattr(value, node.attr) + return self._visit_function(fn) + return False + return self.visit(node.value) + + def visit_Name(self, node: ast.Name) -> bool: + if type(node.ctx) is ast.Store: + return False + if node.id in self.gscope: + fn = self.gscope[node.id] + return self._visit_function(fn) + return False + + def visit_Return(self, node: ast.Return) -> bool: + return True + + def visit_Assign(self, node: ast.Assign) -> bool: + # There couldn't be an early return + # x = ... + return False + + def visit_AugAssign(self, node: ast.AugAssign) -> bool: + # There couldn't be an early return + # x += ... + return False + + def visit_Module(self, node: ast.Module) -> bool: + return self._visit_stmts(node.body) + + def visit_FunctionDef(self, node: ast.FunctionDef) -> bool: + return self._visit_stmts(node.body) + + def visit_If(self, node: ast.If) -> bool: + # TODO: optimize the following case in which we actually don't have + # a return when static_cond is false: + # if dynamic_cond + # if static_cond + # func_with_return + # else + # func_without_return + ret = self._visit_stmts(node.body) + if node.orelse: + ret = ret or self._visit_stmts(node.orelse) + return ret + + def visit_IfExp(self, node: ast.IfExp) -> bool: + return self.visit(node.body) or self.visit(node.orelse) + + def visit_Call(self, node: ast.Call) -> bool: + return self.visit(node.func) + + +class ASTFunction: + + def __init__(self, ret_types, arg_types, constants, attrs): + self.ret_types = ret_types + self.arg_types = arg_types + self.constants = constants + self.attrs = attrs + + def flatten_ir_types(self, builder: ir.builder, types: List[base_type]) -> List[ir.type]: + ir_types = [] + for ty in types: + if ty is None: + continue + ty._flatten_ir_types(builder, ir_types) + return ir_types + + def return_types_ir(self, builder: ir.builder) -> List[ir.type]: + return self.flatten_ir_types(builder, self.ret_types) + + def serialize(self, builder: ir.builder): + # fill up IR values in template + # > build function + is_val = lambda path, _: path not in self.constants and _ is not None + val_paths = list(find_paths_if(self.arg_types, is_val)) + arg_types = [get_iterable_path(self.arg_types, path) for path in val_paths] + arg_types_ir = self.flatten_ir_types(builder, arg_types) + ret_types_ir = self.return_types_ir(builder) + return builder.get_function_ty(arg_types_ir, ret_types_ir) + + def deserialize(self, fn): + # create "template" + def make_template(ty): + if isinstance(ty, (list, tuple, language.tuple_type)): + return language.tuple([make_template(x) for x in ty], ty) + return language.constexpr(None) + + vals = make_template(self.arg_types) + is_val = lambda path, _: path not in self.constants and _ is not None + val_paths = list(find_paths_if(self.arg_types, is_val)) + # > add IR values to the template + cursor = 0 + handles = [fn.args(i) for i in range(fn.get_num_args())] + for path in val_paths: + ty = get_iterable_path(self.arg_types, path) + # > set attributes + attr_specs = self.attrs.get(path, []) + for attr_name, attr_val in attr_specs: + fn.set_arg_attr(cursor, attr_name, attr_val) + # > build frontend value + val, cursor = ty._unflatten_ir(handles, cursor) + set_iterable_path(vals, path, val) + # > add constexpr values to the template + constants = self.constants + for path, val in constants.items(): + set_iterable_path(vals, path, language.constexpr(val)) + return vals + + +@dataclass(frozen=True) +class BoundJITMethod: + __self__: base_value + __func__: JITFunction + + +class CodeGenerator(ast.NodeVisitor): + + def __init__(self, context, prototype, gscope, function_name, jit_fn: JITFunction, *, options, codegen_fns, + module_map, is_gluon, module=None, is_kernel=False, function_types: Optional[Dict] = None, + noinline=False, caller_context=None, file_name: Optional[str] = None, begin_line=0): + self.context = context + self.is_gluon = is_gluon + if is_gluon: + from triton.experimental.gluon.language._semantic import GluonSemantic + self.builder = gluon_ir.GluonOpBuilder(context) + self.semantic = GluonSemantic(self.builder) + else: + from triton.language.semantic import TritonSemantic + self.builder = ir.builder(context) + self.semantic = TritonSemantic(self.builder) + + self.name_loc_as_prefix = None + self.file_name = file_name + # node.lineno starts from 1, so we need to subtract 1 + self.begin_line = begin_line - 1 + self.builder.set_loc(file_name, begin_line, 0) + self.builder.options = options + # dict of functions provided by the backend. Below are the list of possible functions: + # Convert custom types not natively supported on HW. + # convert_custom_types(input_tensor, dtype, fp_downcast_rounding=None, _builder=None) + self.builder.codegen_fns = codegen_fns + self.builder.module_map = {} if module_map is None else module_map + self.module = self.builder.create_module() if module is None else module + self.function_ret_types = {} if function_types is None else function_types + self.prototype = prototype + + self.gscope = {} + for k, v in gscope.items(): + if isinstance(v, ModuleType): + self.gscope[k] = module_map.get(v.__name__, v) + continue + + module_name = getattr(v, "__module__", "") + if module_name in module_map: + self.gscope[k] = getattr(module_map[module_name], v.__name__) + else: + self.gscope[k] = v + + self.lscope = {} + self.jit_fn = jit_fn + # TODO: we currently generate illegal names for non-kernel functions involving constexprs! + if is_kernel: + function_name = function_name[function_name.rfind('.') + 1:] + function_name = check_identifier_legality(function_name, "function") + self.function_name = function_name + self.is_kernel = is_kernel + self.cur_node = None + self.noinline = noinline + self.caller_context = caller_context + self.scf_stack = [] + self.ret_type = None + # SSA-construction + # name => language.tensor + self.local_defs: Dict[str, tensor] = {} + self.dereference_name: Callable[[str], Any] = self._define_name_lookup() + self.fn = None + # Are we currently visiting an ast.arg's default value? These have some + # special handling. + self.visiting_arg_default_value = False + + builtin_namespace: Dict[str, Any] = { + _.__name__: _ + for _ in (len, list, range, float, int, isinstance, getattr, hasattr) + } + builtin_namespace.update(( + ('print', language.core.device_print), + ('min', language.minimum), + ('max', language.maximum), + )) + + def _unsupported(self, node, message): + return UnsupportedLanguageConstruct(self.jit_fn.src, node, message) + + def _is_constexpr_global(self, name): + absent_marker = object() + val = self.gscope.get(name, absent_marker) + if val is absent_marker: + return False + + if _is_constexpr(val): + return True + + return False + + def _define_name_lookup(self): + + def local_lookup(name: str, absent): + # this needs to be re-fetched from `self` every time, because it gets switched occasionally + return self.lscope.get(name, absent) + + def global_lookup(name: str, absent): + val = self.gscope.get(name, absent) + # The high-level rule is that only constexpr globals are allowed. + # But actually a bunch of other things, such as module imports, are + # technically Python globals. We have to allow these too! + if any([ + val is absent, + name in self.builtin_namespace, # + type(val) is ModuleType, # + isinstance(val, JITCallable), # + getattr(val, "__triton_builtin__", False), # + getattr(val, "__triton_aggregate__", False), # + getattr(val, "__module__", "").startswith("triton.language"), # + getattr(val, "__module__", "").startswith("triton.experimental.gluon.language"), # + isinstance(val, language.dtype), # + _is_namedtuple(val), + self._is_constexpr_global(name), # + # Allow accesses to globals while visiting an ast.arg + # because you should be able to do + # @triton.jit def fn(x: tl.constexpr = GLOBAL): ... + self.visiting_arg_default_value, # + knobs.compilation.allow_non_constexpr_globals, + ]): + return val + raise NameError( + textwrap.dedent(f"""\ + Cannot access global variable {name} from within @jit'ed + function. Triton kernels can only access global variables that + are instanstiated as constexpr (`x = triton.language.constexpr(42)`). Note that this is different from + annotating a variable as constexpr (`x: triton.language.constexpr = 42`), which is not supported. Alternatively, set the + envvar TRITON_ALLOW_NON_CONSTEXPR_GLOBALS=1, but we do not + promise to support this forever.""").replace("\n", " ")) + + absent_marker = object() + + def name_lookup(name: str) -> Any: + absent = absent_marker + for lookup_function in local_lookup, global_lookup, self.builtin_namespace.get: + value = lookup_function(name, absent) + if value is not absent: + return value + raise NameError(f'{name} is not defined') + + return name_lookup + + @contextlib.contextmanager + def _name_loc_prefix(self, prefix): + self.name_loc_as_prefix = prefix + yield + self.name_loc_as_prefix = None + + def _maybe_set_loc_to_name(self, val, name): + if isinstance(val, (ir.value, ir.block_argument)): + val.set_loc(self.builder.create_name_loc(name, val.get_loc())) + elif _is_triton_value(val): + handles = [] + val._flatten_ir(handles) + for handle in handles: + handle.set_loc(self.builder.create_name_loc(name, handle.get_loc())) + + def set_value(self, name: str, value: Union[base_value, constexpr]) -> None: + ''' This function: + called by visit_Assign() & visit_FunctionDef() to store left value (lvalue) + 1. record local defined name (FIXME: should consider control flow) + 2. store tensor in self.lvalue + ''' + self.lscope[name] = value + self.local_defs[name] = value + + def _get_insertion_point_and_loc(self): + # XXX: this is a hack to get the location of the insertion point. + # The insertion point's location could be invalid sometimes, + # so we need to explicitly set the location + loc = self.builder.get_loc() + ip = self.builder.get_insertion_point() + return ip, loc + + def _set_insertion_point_and_loc(self, ip, loc): + self.builder.restore_insertion_point(ip) + self.builder.set_loc(loc) + + def _find_carries(self, node, liveins): + # create loop body block + block = self.builder.create_block() + self.builder.set_insertion_point_to_start(block) + # dry visit loop body + self.scf_stack.append(node) + self.visit_compound_statement(node.body) + self.scf_stack.pop() + block.erase() + + # If a variable (name) has changed value within the loop, then it's + # a loop-carried variable. (The new and old value must be of the + # same type) + init_tys = [] + init_handles = [] + names = [] + + for name, live_val in liveins.items(): + if _is_triton_value(live_val): + loop_val = self.lscope[name] + self._verify_loop_carried_variable(name, loop_val, live_val) + + live_handles = flatten_values_to_ir([live_val]) + loop_handles = flatten_values_to_ir([loop_val]) + if live_handles != loop_handles: + names.append(name) + init_tys.append(live_val.type) + init_handles.extend(live_handles) + else: + assert name not in self.local_defs, f'Loop carried variable {name} is not a triton value' + + # reset local scope to not pick up local defs from the dry run. + self.lscope = liveins.copy() + self.local_defs = {} + + return names, init_handles, init_tys + + # + # AST visitor + # + def visit_compound_statement(self, stmts): + # Ensure that stmts is iterable + if not _is_list_like(stmts): + stmts = [stmts] + for stmt in stmts: + self.visit(stmt) + # Stop parsing as soon as we hit a `return` statement; everything + # after this is dead code. + if isinstance(stmt, ast.Return): + break + + def visit_Module(self, node): + ast.NodeVisitor.generic_visit(self, node) + + def visit_List(self, node): + ctx = self.visit(node.ctx) + assert ctx is None + elts = language.tuple([self.visit(elt) for elt in node.elts]) + return elts + + def visit_ListComp(self, node: ast.ListComp): + if len(node.generators) != 1: + raise ValueError("nested comprehensions are not supported") + + comp = node.generators[0] + iter = self.visit(comp.iter) + if not isinstance(iter, tl_tuple): + raise NotImplementedError("only tuple comprehensions are supported") + + results = [] + for item in iter: + self.set_value(comp.target.id, item) + results.append(self.visit(node.elt)) + return tl_tuple(results) + + # By design, only non-kernel functions can return + def visit_Return(self, node): + ret_value = self.visit(node.value) + handles = [] + + def decay(value): + if isinstance(value, language.tuple): + return _apply_to_tuple_values(value, decay) + elif isinstance(value, (language.constexpr, int, float)): + return self.semantic.to_tensor(value) + return value + + ret_value = decay(ret_value) + + if ret_value is None: + ret_ty = language.void + else: + assert isinstance(ret_value, language.core.base_value) + ret_value._flatten_ir(handles) + ret_ty = ret_value.type + self.builder.ret(handles) + if self.ret_type is None: + self.ret_type = ret_ty + elif self.ret_type != ret_ty: + raise TypeError(f'Inconsistent return types: {self.ret_type} and {ret_ty}') + + # A return op must always terminate the basic block, so we create a dead + # basic block in case there are any ops after the return. + post_ret_block = self.builder.create_block() + self.builder.set_insertion_point_to_end(post_ret_block) + + def visit_Starred(self, node) -> Any: + args = self.visit(node.value) + assert isinstance(args, language.core.tuple) + return args.values + + def visit_FunctionDef(self, node): + arg_names, kwarg_names = self.visit(node.args) + if self.fn: + raise self._unsupported(node, "nested function definition is not supported.") + # initialize defaults + for i, default_value in enumerate(node.args.defaults[::-1]): + arg_node = node.args.args[-i - 1] + annotation = arg_node.annotation + name = arg_node.arg + st_target = ast.Name(id=name, ctx=ast.Store()) + if annotation is None: + init_node = ast.Assign(targets=[st_target], value=default_value) + else: + init_node = ast.AnnAssign(target=st_target, value=default_value, annotation=annotation) + try: + assert not self.visiting_arg_default_value + self.visiting_arg_default_value = True + self.visit(init_node) + finally: + self.visiting_arg_default_value = False + + # initialize function + visibility = "public" if self.is_kernel else "private" + fn_ty = self.prototype.serialize(self.builder) + self.fn = self.builder.get_or_insert_function(self.module, self.function_name, fn_ty, visibility, self.noinline) + self.module.push_back(self.fn) + entry = self.fn.add_entry_block() + arg_values = self.prototype.deserialize(self.fn) + if self.caller_context is not None: + self.caller_context.initialize_callee(self.fn, self.builder) + # bind arguments to symbols + for arg_name, arg_value in zip(arg_names, arg_values): + self._maybe_set_loc_to_name(arg_value, arg_name) + self.set_value(arg_name, arg_value) + insert_pt = self.builder.get_insertion_block() + self.builder.set_insertion_point_to_start(entry) + # visit function body + self.visit_compound_statement(node.body) + + # finalize function + assert not self.builder.get_insertion_block().has_terminator() + if self.ret_type is None or self.ret_type == language.void: + self.ret_type = language.void + self.builder.ret([]) + else: + if isinstance(self.ret_type, language.tuple_type): + self.prototype.ret_types = self.ret_type.types + else: + self.prototype.ret_types = [self.ret_type] + self.fn.reset_type(self.prototype.serialize(self.builder)) + self.builder.ret([self.builder.create_poison(ty) for ty in self.prototype.return_types_ir(self.builder)]) + self.fn.finalize() + + if insert_pt: + self.builder.set_insertion_point_to_end(insert_pt) + + def visit_arguments(self, node): + arg_names = [] + for arg in node.args: + arg_names += [self.visit(arg)] + kwarg_names = self.visit(node.kwarg) + return arg_names, kwarg_names + + def visit_arg(self, node): + ast.NodeVisitor.generic_visit(self, node) + return node.arg + + def visit_AnnAssign(self, node): + # extract attributes + annotation = self.visit(node.annotation) + target = self.visit(node.target) + value = self.visit(node.value) + # constexpr + if annotation == constexpr: + if target in self.lscope: + raise ValueError(f'{target} is already defined.' + f' constexpr cannot be reassigned.') + value = constexpr(value) + self.lscope[target] = value + return self.lscope[target] + # default: call visit_Assign + return self.visit_Assign(node) + + def assignTarget(self, target, value): + assert isinstance(target.ctx, ast.Store) + if isinstance(target, ast.Subscript): + return self.visit_Subscript_Store(target, value) + if isinstance(target, ast.Tuple): + for i, target in enumerate(target.elts): + self.assignTarget(target, value.values[i]) + return + if isinstance(target, ast.Attribute): + raise NotImplementedError("Attribute assignment is not supported in triton") + assert isinstance(target, ast.Name) + self.set_value(self.visit(target), value) + + def visit_Assign(self, node): + # construct values to assign + def _sanitize_value(value): + if isinstance(value, language.tuple): + return _apply_to_tuple_values(value, _sanitize_value) + native_nontensor_types = (language.dtype, language.tuple) + value = _unwrap_if_constexpr(value) + if value is not None and \ + not _is_triton_value(value) and \ + not isinstance(value, native_nontensor_types): + value = self.semantic.to_tensor(value) + return value + + targets = [node.target] if isinstance(node, ast.AnnAssign) else node.targets + assert len(targets) == 1 + target = targets[0] + if isinstance(target, ast.Name): + with self._name_loc_prefix(target.id): + values = _sanitize_value(self.visit(node.value)) + else: + values = _sanitize_value(self.visit(node.value)) + self.assignTarget(target, values) + + def visit_AugAssign(self, node): + lhs = copy.deepcopy(node.target) + lhs.ctx = ast.Load() + rhs = ast.BinOp(lhs, node.op, node.value) + assign = ast.Assign(targets=[node.target], value=rhs) + self.visit(assign) + return self.visit(lhs) + + def visit_Name(self, node): + if type(node.ctx) is ast.Store: + return node.id + return self.dereference_name(node.id) + + def visit_Store(self, node): + ast.NodeVisitor.generic_visit(self, node) + + def visit_Load(self, node): + ast.NodeVisitor.generic_visit(self, node) + + def visit_Tuple(self, node): + args = [self.visit(x) for x in node.elts] + return language.tuple(args) + + def _apply_binary_method(self, method_name, lhs, rhs): + # TODO: raise something meaningful if getattr fails below, esp for reverse method + if _is_triton_tensor(lhs): + return getattr(lhs, method_name)(rhs, _semantic=self.semantic) + if _is_triton_tensor(rhs): + reverse_method_name = re.sub(r"__(.*)__", r"__r\1__", method_name) + return getattr(rhs, reverse_method_name)(lhs, _semantic=self.semantic) + if not isinstance(lhs, (constexpr, language.tuple)) and isinstance(rhs, constexpr): + lhs = constexpr(lhs) + return getattr(lhs, method_name)(rhs) + + def visit_BinOp(self, node): + lhs = self.visit(node.left) + rhs = self.visit(node.right) + method_name = self._method_name_for_bin_op.get(type(node.op)) + if method_name is None: + raise self._unsupported(node, + "AST binary operator '{}' is not (currently) implemented.".format(node.op.__name__)) + return self._apply_binary_method(method_name, lhs, rhs) + + _method_name_for_bin_op: Dict[Type[ast.operator], str] = { + ast.Add: '__add__', + ast.Sub: '__sub__', + ast.Mult: '__mul__', + ast.Div: '__truediv__', + ast.FloorDiv: '__floordiv__', + ast.Mod: '__mod__', + ast.Pow: '__pow__', + ast.LShift: '__lshift__', + ast.RShift: '__rshift__', + ast.BitAnd: '__and__', + ast.BitOr: '__or__', + ast.BitXor: '__xor__', + } + + def visit_then_else_blocks(self, node, liveins, then_block, else_block): + # then block + self.builder.set_insertion_point_to_start(then_block) + self.visit_compound_statement(node.body) + then_block = self.builder.get_insertion_block() + then_defs = self.local_defs.copy() + then_vals = self.lscope.copy() + # else block + else_defs = {} + else_vals = liveins.copy() + if node.orelse: + self.builder.set_insertion_point_to_start(else_block) + self.lscope = liveins.copy() + self.local_defs = {} + self.visit_compound_statement(node.orelse) + else_defs = self.local_defs.copy() + else_block = self.builder.get_insertion_block() + else_vals = self.lscope.copy() + + # update block arguments + names = [] + # variables in livein whose value is updated in `if` + for name, value in liveins.items(): + # livein variable changed value in either then or else + if not _is_triton_value(value): + continue + then_handles = flatten_values_to_ir([then_vals[name]]) + else_handles = flatten_values_to_ir([else_vals[name]]) + if then_handles == else_handles: + continue + names.append(name) + then_defs[name] = then_vals[name] + else_defs[name] = else_vals[name] + # check type + for defs, block_name in [(then_defs, 'then'), (else_defs, 'else')]: + type_equal = type(defs[name]) == type(value) # noqa: E721 + assert type_equal and defs[name].type == value.type, \ + f'initial value for `{name}` is of type {value}, '\ + f'but the {block_name} block redefines it as {defs[name]}' + + # variables that are both in then and else but not in liveins + # TODO: could probably be cleaned up + for name in sorted(then_defs.keys() & else_defs.keys()): + if name in names: + continue + then_val = then_defs[name] + then_ty = then_val.type + else_val = else_defs[name] + else_ty = else_val.type + type_equal = type(then_val) == type(else_val) # noqa: E721 + assert type_equal and then_ty == else_ty, \ + f'Mismatched type for {name} between then block ({then_ty}) '\ + f'and else block ({else_ty})' + names.append(name) + + return then_defs, else_defs, then_block, else_block, names + + def visit_if_top_level(self, cond, node): + with enter_sub_region(self) as sr: + liveins, ip_block = sr + then_block = self.builder.create_block() + else_block = self.builder.create_block() + # create branch + self.builder.set_insertion_point_to_end(ip_block) + self.builder.create_cond_branch(cond.handle, then_block, else_block) + # visit then and else blocks + then_defs, else_defs, then_block, else_block, names = \ + self.visit_then_else_blocks(node, liveins, then_block, else_block) + # create basic-block after conditional + endif_block = self.builder.create_block() + # then terminator + self.builder.set_insertion_point_to_end(then_block) + assert not then_block.has_terminator(), f"{then_block}" + then_handles = flatten_values_to_ir(then_defs[name] for name in names) + self.builder.create_branch(endif_block, then_handles) + # else terminator + self.builder.set_insertion_point_to_end(else_block) + assert not else_block.has_terminator(), f"{else_block}" + else_handles = flatten_values_to_ir(else_defs[name] for name in names) + self.builder.create_branch(endif_block, else_handles) + assert len(then_handles) == len(else_handles) + for then_h, else_h in zip(then_handles, else_handles): + ty = then_h.get_type() + assert ty == else_h.get_type() + endif_block.add_argument(ty) + + # change block + self.builder.set_insertion_point_to_start(endif_block) + # update value + res_handles = [endif_block.arg(i) for i in range(len(then_handles))] + types = [then_defs[name].type for name in names] + new_values = unflatten_ir_values(res_handles, types) + for name, new_value in zip(names, new_values): + self.set_value(name, new_value) + + # TODO: refactor + def visit_if_scf(self, cond, node): + with enter_sub_region(self) as sr: + liveins, _ = sr + ip, last_loc = self._get_insertion_point_and_loc() + then_block = self.builder.create_block() + else_block = self.builder.create_block() if node.orelse else None + then_defs, else_defs, then_block, else_block, names = \ + self.visit_then_else_blocks(node, liveins, then_block, else_block) + # create if op + then_handles = flatten_values_to_ir(then_defs[name] for name in names) + for name, val in zip(names, then_handles): + self._maybe_set_loc_to_name(val, name) + self._set_insertion_point_and_loc(ip, last_loc) + if_op = self.builder.create_if_op([h.get_type() for h in then_handles], cond.handle, True) + then_block.merge_block_before(if_op.get_then_block()) + self.builder.set_insertion_point_to_end(if_op.get_then_block()) + if len(names) > 0: + self.builder.create_yield_op(then_handles) + if not node.orelse: + else_block = if_op.get_else_block() + else: + else_block.merge_block_before(if_op.get_else_block()) + self.builder.set_insertion_point_to_end(if_op.get_else_block()) + if len(names) > 0: + else_handles = flatten_values_to_ir(else_defs[name] for name in names) + for name, val in zip(names, else_handles): + self._maybe_set_loc_to_name(val, name) + self.builder.create_yield_op(else_handles) + # update values + res_handles = [if_op.get_result(i) for i in range(len(then_handles))] + types = [then_defs[name].type for name in names] + new_values = unflatten_ir_values(res_handles, types) + for name, new_value in zip(names, new_values): + self.set_value(name, new_value) + + def visit_If(self, node): + cond = self.visit(node.test) + + if _is_triton_tensor(cond): + if _is_non_scalar_tensor(cond): + raise self._unsupported(node, "Boolean value of Tensor with more than one value is ambiguous") + if cond.type.is_block(): + warnings.warn( + "If conditional called with multidimensional Tensor instead of scalar; please use \"if (%s).item()\" instead" + % ast.unparse(node.test)) + cond = language.core._unsplat(cond, _semantic=self.semantic, _generator=self) + cond = cond.to(language.int1, _semantic=self.semantic) + if ContainsReturnChecker(self.gscope).visit(node): + if self.scf_stack: + raise self._unsupported( + node, "Cannot have `return` statements inside `while` or `for` statements in triton.") + self.visit_if_top_level(cond, node) + else: + self.visit_if_scf(cond, node) + else: + cond = _unwrap_if_constexpr(cond) + # not isinstance - we insist the real thing, no subclasses and no ducks + if type(cond) not in _condition_types: + raise self._unsupported( + node, "`if` conditionals can only accept values of type {{{}}}, not objects of type {}".format( + ', '.join(_.__name__ for _ in _condition_types), + type(cond).__name__)) + + active_block = node.body if cond else node.orelse + self.visit_compound_statement(active_block) + + def visit_IfExp(self, node): + cond = self.visit(node.test) + if _is_triton_tensor(cond): + cond = cond.to(language.int1, _semantic=self.semantic) + # TODO: Deal w/ more complicated return types (e.g tuple) + with enter_sub_region(self): + ip, last_loc = self._get_insertion_point_and_loc() + + then_block = self.builder.create_block() + self.builder.set_insertion_point_to_start(then_block) + then_val = self.semantic.to_tensor(self.visit(node.body)) + then_block = self.builder.get_insertion_block() + + else_block = self.builder.create_block() + self.builder.set_insertion_point_to_start(else_block) + # do not need to reset lscope since + # ternary expressions cannot define new variables + else_val = self.semantic.to_tensor(self.visit(node.orelse)) + else_block = self.builder.get_insertion_block() + + self._set_insertion_point_and_loc(ip, last_loc) + + assert then_val.type == else_val.type, \ + f'Ternary expression with dynamic condition has inconsistent types {then_val.type} and {else_val.type}' + ret_type = then_val.type + + ret_type_ir = [ret_type.to_ir(self.builder)] if ret_type != language.void else [] + if_op = self.builder.create_if_op(ret_type_ir, cond.handle, True) + then_block.merge_block_before(if_op.get_then_block()) + if ret_type_ir: + self.builder.set_insertion_point_to_end(if_op.get_then_block()) + self.builder.create_yield_op([then_val.handle]) + + self.builder.set_insertion_point_to_end(if_op.get_then_block()) + else_block.merge_block_before(if_op.get_else_block()) + if ret_type_ir: + self.builder.set_insertion_point_to_end(if_op.get_else_block()) + self.builder.create_yield_op([else_val.handle]) + return language.core.tensor(if_op.get_result(0), ret_type) if ret_type_ir else None + else: + cond = _unwrap_if_constexpr(cond) + + # not isinstance - we insist the real thing, no subclasses and no ducks + if type(cond) not in _condition_types: + raise self._unsupported( + node, "`if` conditionals can only accept values of type {{{}}}, not objects of type {}".format( + ', '.join(_.__name__ for _ in _condition_types), + type(cond).__name__)) + if cond: + return self.visit(node.body) + else: + return self.visit(node.orelse) + + def visit_With(self, node): + # Lower `with` statements by constructing context managers and calling their enter/exit hooks + # Instantiate each context manager with builder injection + if len(node.items) == 1: # Handle async_task + context = node.items[0].context_expr + withitemClass = self.visit(context.func) + if withitemClass == language.async_task: + args = [self.visit(arg) for arg in context.args] + with withitemClass(*args, _builder=self.builder): + self.visit_compound_statement(node.body) + return + + cm_list = [] + for item in node.items: + call = item.context_expr + fn = self.visit(call.func) + args = [self.visit(arg) for arg in call.args] + kws = dict(self.visit(kw) for kw in call.keywords) + cm = fn(*args, _semantic=self.semantic, **kws) + cm_list.append(cm) + for cm, item in zip(cm_list, node.items): + res = cm.__enter__() + if item.optional_vars is not None: + var_name = self.visit(item.optional_vars) + self.set_value(var_name, res) + if ContainsReturnChecker(self.gscope).visit(node): + raise self._unsupported(node, "Cannot have `return` statements inside `with` statements in triton ") + self.visit_compound_statement(node.body) + for cm in reversed(cm_list): + cm.__exit__(None, None, None) + + def visit_Pass(self, node): + pass + + def visit_Compare(self, node): + if not (len(node.comparators) == 1 and len(node.ops) == 1): + raise self._unsupported(node, "simultaneous multiple comparison is not supported") + lhs = self.visit(node.left) + rhs = self.visit(node.comparators[0]) + lhs_value = _unwrap_if_constexpr(lhs) + rhs_value = _unwrap_if_constexpr(rhs) + if type(node.ops[0]) is ast.Is: + return constexpr(lhs_value is rhs_value) + if type(node.ops[0]) is ast.IsNot: + return constexpr(lhs_value is not rhs_value) + method_name = self._method_name_for_comp_op.get(type(node.ops[0])) + if method_name is None: + raise self._unsupported( + node, "AST comparison operator '{}' is not (currently) implemented.".format(node.ops[0].__name__)) + return self._apply_binary_method(method_name, lhs, rhs) + + _method_name_for_comp_op: Dict[Type[ast.cmpop], str] = { + ast.Eq: '__eq__', ast.NotEq: '__ne__', ast.Lt: '__lt__', ast.LtE: '__le__', ast.Gt: '__gt__', ast.GtE: '__ge__' + } + + def visit_UnaryOp(self, node): + operand = self.visit(node.operand) + fn = self._method_name_for_unary_op.get(type(node.op)) + if fn is None: + raise self._unsupported(node, f"AST unary operator '{node.op.__name__}' is not (currently) implemented.") + if _is_triton_tensor(operand): + return getattr(operand, fn)(_semantic=self.semantic) + try: + return getattr(operand, fn)() + except AttributeError: + if fn == "__not__": + return constexpr(not operand) + raise self._unsupported( + node, f"AST unary operator '{fn}' is not (currently) implemented on type {type(operand).__name__}") + + _method_name_for_unary_op: Dict[Type[ast.unaryop], str] = { + ast.USub: '__neg__', ast.UAdd: '__pos__', ast.Not: '__not__', ast.Invert: '__invert__' + } + + def _verify_loop_carried_variable(self, name, loop_val, live_val): + assert _is_triton_value(loop_val), f'cannot reassign constexpr {name} in the loop' + assert _is_triton_value(live_val), f'cannot reassign constexpr {name} in the loop' + assert type(loop_val) is type(live_val), ( + f'Loop carried variable {name} changed type, was {type(loop_val)} but is now {type(live_val)}') + assert not _is_triton_tensor(loop_val) or loop_val.type == live_val.type, \ + f'Loop-carried variable {name} has initial type {live_val.type} '\ + f'but is re-assigned to {loop_val.type} in loop! '\ + f'Please make sure that the type stays consistent.' + + def visit_withitem(self, node): + return self.visit(node.context_expr) + + def visit_While(self, node): + with enter_sub_region(self) as sr: + liveins, insert_block = sr + ip, last_loc = self._get_insertion_point_and_loc() + + names, init_handles, init_fe_tys = self._find_carries(node, liveins) + + init_tys = [h.get_type() for h in init_handles] + self._set_insertion_point_and_loc(ip, last_loc) + while_op = self.builder.create_while_op(init_tys, init_handles) + # merge the condition region + before_block = self.builder.create_block_with_parent(while_op.get_before(), init_tys) + self.builder.set_insertion_point_to_start(before_block) + block_args = [before_block.arg(i) for i in range(len(init_handles))] + condition_args = unflatten_ir_values(block_args, init_fe_tys) + for name, val in zip(names, condition_args): + self.lscope[name] = val + self.local_defs[name] = val + self._maybe_set_loc_to_name(val, name) + cond = self.visit(node.test) + if isinstance(cond, language.condition): + if cond.disable_licm: + while_op.set_attr("llvm.loop_annotation", self.builder.get_disable_loop_licm_attr()) + cond = cond.condition + self.builder.set_insertion_point_to_end(before_block) + # create ConditionOp: e.g., scf.condition(%cond) %arg0, %arg1, ... + self.builder.create_condition_op(cond.handle, block_args) + # merge the loop body + after_block = self.builder.create_block_with_parent(while_op.get_after(), init_tys) + + # generate loop body + self.builder.set_insertion_point_to_start(after_block) + body_handles = [after_block.arg(i) for i in range(len(init_handles))] + body_args = unflatten_ir_values(body_handles, init_fe_tys) + for name, val in zip(names, body_args): + self.lscope[name] = val + self.local_defs[name] = val + self._maybe_set_loc_to_name(val, name) + self.scf_stack.append(node) + self.visit_compound_statement(node.body) + self.scf_stack.pop() + + yield_handles = flatten_values_to_ir(self.lscope[name] for name in names) + self.builder.create_yield_op(yield_handles) + + # WhileOp defines new values, update the symbol table (lscope, local_defs) + result_handles = [while_op.get_result(i) for i in range(len(init_handles))] + result_vals = unflatten_ir_values(result_handles, init_fe_tys) + for name, new_def in zip(names, result_vals): + self.lscope[name] = new_def + self.local_defs[name] = new_def + self._maybe_set_loc_to_name(new_def, name) + + for stmt in node.orelse: + assert False, "Not implemented" + ast.NodeVisitor.generic_visit(self, stmt) + + def visit_Subscript_Load(self, node): + assert isinstance(node.ctx, ast.Load) + lhs = self.visit(node.value) + slices = self.visit(node.slice) + if _is_triton_value(lhs): + return self.call_Method(node, lhs.__getitem__, lhs, [slices], {}) + return lhs[slices] + + def visit_Subscript_Store(self, node, value): + raise NotImplementedError("__setitem__ is not supported in triton") + + def visit_Subscript(self, node): + return self.visit_Subscript_Load(node) + + def visit_ExtSlice(self, node): + return [self.visit(dim) for dim in node.dims] + + def visit_For(self, node): + IteratorClass = self.visit(node.iter.func) + iter_args = [self.visit(arg) for arg in node.iter.args] + iter_kwargs = dict(self.visit(keyword) for keyword in node.iter.keywords) + if IteratorClass == language.static_range: + iterator = IteratorClass(*iter_args, **iter_kwargs) + static_range = range(iterator.start.value, iterator.end.value, iterator.step.value) + for i in static_range: + self.lscope[node.target.id] = constexpr(i) + self.visit_compound_statement(node.body) + for stmt in node.orelse: + ast.NodeVisitor.generic_visit(self, stmt) + return + num_stages = None + loop_unroll_factor = None + disallow_acc_multi_buffer = False + flatten = False + warp_specialize = False + disable_licm = False + if IteratorClass is language.range: + iterator = IteratorClass(*iter_args, **iter_kwargs) + # visit iterator arguments + # note: only `range` iterator is supported now + # collect lower bound (lb), upper bound (ub), and step + lb = iterator.start + ub = iterator.end + step = iterator.step + num_stages = iterator.num_stages + loop_unroll_factor = iterator.loop_unroll_factor + disallow_acc_multi_buffer = iterator.disallow_acc_multi_buffer + flatten = iterator.flatten + warp_specialize = iterator.warp_specialize + disable_licm = iterator.disable_licm + elif IteratorClass is range: + # visit iterator arguments + # note: only `range` iterator is supported now + # collect lower bound (lb), upper bound (ub), and step + lb = iter_args[0] if len(iter_args) > 1 else self.visit(ast.Num(0)) + ub = iter_args[1] if len(iter_args) > 1 else self.visit(node.iter.args[0]) + step = iter_args[2] if len(iter_args) > 2 else self.visit(ast.Num(1)) + else: + raise RuntimeError('Only `range` and `static_range` iterators are currently supported') + # handle negative constant step (not supported by scf.for in MLIR) + negative_step = False + if _is_constexpr(step) and step.value < 0: + step = constexpr(-step.value) + negative_step = True + lb, ub = ub, lb + lb = self.semantic.to_tensor(lb) + ub = self.semantic.to_tensor(ub) + step = self.semantic.to_tensor(step) + # induction variable type + if not lb.dtype.is_int() or not ub.dtype.is_int() or not step.dtype.is_int(): + raise TypeError(f"For loop bounds and step must all be ints, are ({lb.dtype}, {ub.dtype}, {step.dtype})") + iv_type = self.semantic.integer_promote_impl(lb.dtype, ub.dtype) + iv_type = self.semantic.integer_promote_impl(iv_type, step.dtype) + iv_ir_type = iv_type.to_ir(self.builder) + iv_is_signed = iv_type.int_signedness == language.core.dtype.SIGNEDNESS.SIGNED + # lb/ub/step might be constexpr, we need to cast them to tensor + lb = lb.handle + ub = ub.handle + step = step.handle + # ForOp can only accept IndexType as lb/ub/step. Cast integer to Index + lb = self.builder.create_int_cast(lb, iv_ir_type, iv_is_signed) + ub = self.builder.create_int_cast(ub, iv_ir_type, iv_is_signed) + step = self.builder.create_int_cast(step, iv_ir_type, iv_is_signed) + # Create placeholder for the loop induction variable + iv = self.builder.create_poison(iv_ir_type) + self.set_value(node.target.id, language.core.tensor(iv, iv_type)) + + with enter_sub_region(self) as sr: + liveins, insert_block = sr + ip, last_loc = self._get_insertion_point_and_loc() + + names, init_handles, init_tys = self._find_carries(node, liveins) + + # create ForOp + self._set_insertion_point_and_loc(ip, last_loc) + for_op = self.builder.create_for_op(lb, ub, step, init_handles) + if _unwrap_if_constexpr(num_stages) is not None: + for_op.set_attr("tt.num_stages", self.builder.get_int32_attr(num_stages)) + if _unwrap_if_constexpr(loop_unroll_factor) is not None: + for_op.set_attr("tt.loop_unroll_factor", self.builder.get_int32_attr(loop_unroll_factor)) + if disallow_acc_multi_buffer: + for_op.set_attr("tt.disallow_acc_multi_buffer", self.builder.get_unit_attr()) + if flatten: + for_op.set_attr("tt.flatten", self.builder.get_unit_attr()) + if warp_specialize: + for_op.set_attr("tt.warp_specialize", self.builder.get_unit_attr()) + if disable_licm: + for_op.set_attr("llvm.loop_annotation", self.builder.get_disable_loop_licm_attr()) + + self.scf_stack.append(node) + for_op_body = for_op.get_body(0) + self.builder.set_insertion_point_to_start(for_op_body) + block_handles = [for_op_body.arg(i + 1) for i in range(len(init_handles))] + block_args = unflatten_ir_values(block_handles, init_tys) + for name, val in zip(names, block_args): + self._maybe_set_loc_to_name(val, name) + self.set_value(name, val) + self.visit_compound_statement(node.body) + self.scf_stack.pop() + yield_handles = flatten_values_to_ir(self.lscope[name] for name in names) + + # create YieldOp + if len(yield_handles) > 0: + self.builder.create_yield_op(yield_handles) + for_op_region = for_op_body.get_parent() + assert for_op_region.size() == 1, "We use SCF, so the loop body should only have one block" + + # update induction variable with actual value, and replace all uses + self.builder.set_insertion_point_to_start(for_op_body) + iv = for_op.get_induction_var() + if negative_step: + iv = self.builder.create_sub(ub, iv) + iv = self.builder.create_add(iv, lb) + self.lscope[node.target.id].handle.replace_all_uses_with(iv) + self.set_value(node.target.id, language.core.tensor(iv, iv_type)) + self._maybe_set_loc_to_name(iv, node.target.id) + + # update lscope & local_defs (ForOp defines new values) + result_handles = [for_op.get_result(i) for i in range(len(init_handles))] + result_values = unflatten_ir_values(result_handles, init_tys) + for name, val in zip(names, result_values): + self.set_value(name, val) + self._maybe_set_loc_to_name(val, name) + + for stmt in node.orelse: + assert False, "Don't know what to do with else after for" + ast.NodeVisitor.generic_visit(self, stmt) + + def visit_Slice(self, node): + lower = self.visit(node.lower) + upper = self.visit(node.upper) + step = self.visit(node.step) + return language.slice(lower, upper, step) + + def visit_Index(self, node): + return self.visit(node.value) + + def visit_keyword(self, node) -> Tuple[str, Any]: + return node.arg, self.visit(node.value) + + def visit_Assert(self, node) -> Any: + test = self.visit(node.test) + msg = self.visit(node.msg) if node.msg is not None else "" + return language.core.device_assert(test, msg, _semantic=self.semantic) + + def call_JitFunction(self, fn: JITFunction, args, kwargs, caller_context=None): + args = inspect.getcallargs(fn.fn, *args, **kwargs) + args = [args[name] for name in fn.arg_names] + for i, arg in enumerate(args): + if isinstance(arg, (language.dtype, float, int, bool, JITFunction)): + args[i] = language.core.constexpr(arg) + args_cst = find_paths_if(args, lambda _, x: _is_constexpr(x)) + args_cst = {path: get_iterable_path(args, path) for path in args_cst} + args_path = find_paths_if(args, lambda _, x: not _is_constexpr(x)) + args_val = [get_iterable_path(args, path) for path in args_path] + # mangle + caller_context = caller_context or self.caller_context + fn_name = mangle_fn(get_full_name(fn), [arg.type for arg in args_val], args_cst, caller_context) + # generate function def if necessary + if not self.module.has_function(fn_name): + # If the callee is not set, we use the same debug setting as the caller + file_name, begin_line = get_jit_fn_file_line(fn) + arg_types = [ + language.core.constexpr if arg is None or isinstance(arg, + (bool, int, language.core.dtype)) else arg.type + for arg in args + ] + prototype = ASTFunction([], arg_types, args_cst, dict()) + generator = CodeGenerator(self.context, prototype, fn.get_capture_scope(), module=self.module, jit_fn=fn, + function_name=fn_name, function_types=self.function_ret_types, + noinline=fn.noinline, file_name=file_name, begin_line=begin_line, + options=self.builder.options, codegen_fns=self.builder.codegen_fns, + module_map=self.builder.module_map, caller_context=caller_context, + is_gluon=self.is_gluon) + try: + generator.visit(fn.parse()) + except Exception as e: + # Wrap the error in the callee with the location of the call. + if knobs.compilation.front_end_debugging: + raise + raise CompilationError(self.jit_fn.src, self.cur_node, None) from e + + callee_ret_type = generator.ret_type + self.function_ret_types[fn_name] = callee_ret_type + else: + callee_ret_type = self.function_ret_types[fn_name] + symbol = self.module.get_function(fn_name) + args_val = flatten_values_to_ir(args_val) + call_op = self.builder.call(symbol, args_val) + if callee_ret_type == language.void: + return None + handles = [call_op.get_result(i) for i in range(call_op.get_num_results())] + return next(unflatten_ir_values(handles, [callee_ret_type])) + + def call_Function(self, node, fn, args, kws): + if isinstance(fn, (BoundJITMethod, BoundConstexprFunction)): + args.insert(0, fn.__self__) + fn = fn.__func__ + if isinstance(fn, JITFunction): + _check_fn_args(node, fn, args) + return self.call_JitFunction(fn, args, kws) + if (hasattr(fn, '__self__') and _is_triton_value(fn.__self__)) or language.core.is_builtin(fn) or isinstance( + fn, ConstexprFunction): + extra_kwargs = dict() + + if isinstance(fn, ConstexprFunction): + sig = inspect.signature(fn.__call__) + else: + sig = inspect.signature(fn) + if '_semantic' in sig.parameters: + extra_kwargs["_semantic"] = self.semantic + if '_generator' in sig.parameters: + extra_kwargs['_generator'] = self + try: + ret = fn(*args, **extra_kwargs, **kws) + # builtin functions return plain tuples for readability + if isinstance(ret, tuple): + ret = language.tuple(ret) + return ret + except Exception as e: + if knobs.compilation.front_end_debugging: + raise + # Normally when we raise a CompilationError, we raise it as + # `from None`, because the original fileline from the exception + # is not relevant (and often points into code_generator.py + # itself). But when calling a function, we raise as `from e` to + # preserve the traceback of the original error, which may e.g. + # be in core.py. + raise CompilationError(self.jit_fn.src, node, str(e)) from e + + if fn in self.builtin_namespace.values(): + args = map(_unwrap_if_constexpr, args) + ret = fn(*args, **kws) + + def wrap_constexpr(x): + if _is_triton_value(x): + return x + return constexpr(x) + + if isinstance(ret, (builtins.tuple, language.tuple)): + return _apply_to_tuple_values(ret, wrap_constexpr) + return wrap_constexpr(ret) + + def call_Method(self, node, fn, fn_self, args, kws): + if isinstance(fn, JITFunction): + args.insert(0, fn_self) + return self.call_Function(node, fn, args, kws) + + def visit_Call(self, node): + fn = _unwrap_if_constexpr(self.visit(node.func)) + if not isinstance(fn, BoundJITMethod): + static_implementation = self.statically_implemented_functions.get(fn) + if static_implementation is not None: + return static_implementation(self, node) + + mur = getattr(fn, '_must_use_result', False) + if mur and getattr(node, '_is_unused', False): + error_message = ["The result of %s is not being used." % ast.unparse(node.func)] + if isinstance(mur, str): + error_message.append(mur) + raise CompilationError(self.jit_fn.src, node, " ".join(error_message)) + + kws = dict(self.visit(keyword) for keyword in node.keywords) + args = [self.visit(arg) for arg in node.args] + args = list(itertools.chain.from_iterable(x if isinstance(x, list) else [x] for x in args)) + + return self.call_Function(node, fn, args, kws) + + def visit_Constant(self, node): + return constexpr(node.value) + + def visit_BoolOp(self, node: ast.BoolOp): + method_name = self._method_name_for_bool_op.get(type(node.op)) + if method_name is None: + raise self._unsupported( + node, "AST boolean operator '{}' is not (currently) implemented.".format(node.op.__name__)) + + nontrivial_values = [] + + for subnode in node.values: + # we visit the values in order, executing their side-effects + # and possibly early-exiting: + value = self.visit(subnode) + if not _is_triton_tensor(value): + # this is a constexpr, so we might be able to short-circuit: + bv = bool(value) + if (bv is False) and (method_name == "logical_and"): + # value is falsey so return that: + return value + if (bv is True) and (method_name == "logical_or"): + # value is truthy so return that: + return value + # otherwise, our constexpr has no effect on the output of the + # expression so we do not append it to nontrivial_values. + else: + if value.type.is_block(): + lineno = getattr(node, "lineno", None) + if lineno is not None: + lineno += self.begin_line + warnings.warn_explicit( + "Logical operators 'and' and 'or' are deprecated for non-scalar tensors; please use '&' or '|' instead", + category=UserWarning, + filename=self.file_name, + lineno=lineno, + source=ast.unparse(node), + ) + # not a constexpr so we must append it: + nontrivial_values.append(value) + + if len(nontrivial_values) == 0: + # the semantics of a disjunction of falsey values or conjunction + # of truthy values is to return the final value: + nontrivial_values.append(value) + + while len(nontrivial_values) >= 2: + rhs = nontrivial_values.pop() + lhs = nontrivial_values.pop() + res = self._apply_binary_method(method_name, lhs, rhs) + nontrivial_values.append(res) + + assert len(nontrivial_values) == 1 + return nontrivial_values[0] + + _method_name_for_bool_op: Dict[Type[ast.boolop], str] = {ast.And: 'logical_and', ast.Or: 'logical_or'} + + def visit_Attribute(self, node): + lhs = self.visit(node.value) + if _is_triton_tensor(lhs) and node.attr == "T": + return self.semantic.permute(lhs, (1, 0)) + # NOTE: special case ".value" for BC + if isinstance(lhs, constexpr) and node.attr not in ("value", "type"): + lhs = lhs.value + attr = getattr(lhs, node.attr) + if _is_triton_value(lhs) and isinstance(attr, JITFunction): + return BoundJITMethod(lhs, attr) + return attr + + def visit_Expr(self, node): + node.value._is_unused = True + ast.NodeVisitor.generic_visit(self, node) + + def visit_NoneType(self, node): + return None + + def visit_JoinedStr(self, node): + values = list(node.values) + for i, value in enumerate(values): + if isinstance(value, ast.Constant): + values[i] = str(value.value) + elif isinstance(value, ast.FormattedValue): + conversion_code = value.conversion + evaluated = self.visit(value.value) + if not _is_constexpr(evaluated): + raise self._unsupported( + node, + "Cannot evaluate f-string containing non-constexpr conversion values, found conversion of type " + + str(type(evaluated))) + values[i] = ("{}" if conversion_code < 0 else "{!" + chr(conversion_code) + "}").format(evaluated.value) + else: + raise AssertionError("encountered unexpected node of type {} in a JoinedStr node".format(type(value))) + return ''.join(values) + + def visit(self, node): + if node is None: + return + with warnings.catch_warnings(): + # The ast library added visit_Constant and deprecated some other + # methods but we can't move to that without breaking Python 3.6 and 3.7. + warnings.simplefilter("ignore", DeprecationWarning) # python 3.9 + warnings.simplefilter("ignore", PendingDeprecationWarning) # python 3.8 + last_node = self.cur_node + last_loc = self.builder.get_loc() + self.cur_node = node + if hasattr(node, 'lineno') and hasattr(node, 'col_offset'): + here_loc = self.builder.create_loc(self.file_name, self.begin_line + node.lineno, node.col_offset) + if self.name_loc_as_prefix is not None: + self.builder.set_loc(self.builder.create_name_loc(self.name_loc_as_prefix, here_loc)) + else: + self.builder.set_loc(here_loc) + last_loc = self.builder.get_loc() + try: + ret = super().visit(node) + except CompilationError: + raise + except Exception as e: + if knobs.compilation.front_end_debugging: + raise + # Wrap the error in a CompilationError which contains the source + # of the @jit function. + raise CompilationError(self.jit_fn.src, self.cur_node, repr(e)) from None + + # Reset the location to the last one before the visit + if last_loc: + self.cur_node = last_node + self.builder.set_loc(last_loc) + return ret + + def generic_visit(self, node): + raise self._unsupported(node, "unsupported AST node type: {}".format(type(node).__name__)) + + def execute_static_assert(self, node: ast.Call) -> None: + arg_count = len(node.args) + if not (0 < arg_count <= 2) or len(node.keywords): + raise TypeError("`static_assert` requires one or two positional arguments only") + + passed = _unwrap_if_constexpr(self.visit(node.args[0])) + if not isinstance(passed, bool): + raise NotImplementedError( + "Assertion condition could not be determined at compile-time. Make sure that it depends only on `constexpr` values" + ) + if not passed: + if arg_count == 1: + message = "" + else: + try: + message = self.visit(node.args[1]) + except Exception as e: + message = "" + + raise CompileTimeAssertionFailure(self.jit_fn.src, node, _unwrap_if_constexpr(message)) + return None + + def static_executor(python_fn): + + def ret(self, node: ast.Call): + kws = { + name: _unwrap_if_constexpr(value) + for name, value in (self.visit(keyword) for keyword in node.keywords) + } + args = [_unwrap_if_constexpr(self.visit(arg)) for arg in node.args] + return constexpr(python_fn(*args, **kws)) + + return ret + + from ..experimental.gluon import language as ttgl + statically_implemented_functions: Dict[object, Callable[[ast.Call], Any]] = { + language.core.static_assert: execute_static_assert, + language.core.static_print: static_executor(print), + ttgl.static_assert: execute_static_assert, + ttgl.static_print: static_executor(print), + int: static_executor(int), + len: static_executor(len), + } + + +def ast_to_ttir(fn, src, context, options, codegen_fns, module_map, module=None): + arg_types = [None] * len(fn.arg_names) + const_iter = iter(src.constants.items()) + kc, vc = next(const_iter, (None, None)) + + for i, (ks, v) in enumerate(src.signature.items()): + idx = fn.arg_names.index(ks) + cexpr = None + if kc is not None and kc[0] == i: + cexpr = vc + kc, vc = next(const_iter, (None, None)) + arg_types[idx] = str_to_ty(v, cexpr) + prototype = ASTFunction([], arg_types, src.constants, src.attrs) + file_name, begin_line = get_jit_fn_file_line(fn) + # query function representation + from collections import namedtuple + leaves = filter(lambda v: len(v) == 1, src.constants) + constants = {fn.arg_names[i[0]]: src.constants[i] for i in leaves} + signature = src.signature + proxy = namedtuple("SpecializationProxy", ["constants", "signature"])(constants, signature) + generator = CodeGenerator(context, prototype, gscope=fn.get_capture_scope(), function_name=fn.repr(proxy), + jit_fn=fn, is_kernel=True, file_name=file_name, begin_line=begin_line, options=options, + codegen_fns=codegen_fns, module_map=module_map, module=module, is_gluon=fn.is_gluon()) + generator.visit(fn.parse()) + module = generator.module + # module takes ownership of the context + module.context = context + if not module.verify_with_diagnostics(): + if not fn.is_gluon(): + print(module) + raise RuntimeError("error encountered during parsing") + return module diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/compiler.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..1f38e9ddf0ac493aa8442619030b00bcf28774db --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/compiler.py @@ -0,0 +1,509 @@ +from __future__ import annotations +import hashlib +import json +from .._C.libtriton import get_cache_invalidating_env_vars, ir +from ..backends import backends +from ..backends.compiler import Language +from ..backends.compiler import BaseBackend, GPUTarget +from .. import __version__, knobs +from ..runtime.autotuner import OutOfResources +from ..runtime.cache import get_cache_manager, get_dump_manager, get_override_manager, get_cache_key +from ..runtime.driver import driver +from ..tools.disasm import get_sass +from pathlib import Path +import re +import functools +import os +import time +import copy + +# - ^\s*tt\.func\s+ : match the start of the string, any leading whitespace, the keyword func, +# and any following whitespace +# - (public\s+)? : optionally match the keyword public and any following whitespace +# - (@\w+) : match an @ symbol followed by one or more word characters +# (letters, digits, or underscores), and capture it as group 1 (the function name) +# - (\((?:%\w+: \S+(?: \{\S+ = \S+ : \S+\})?(?:, )?)*\)) : match a pair of parentheses enclosing +# zero or more arguments separated by commas, and capture it as group 2 (the argument list) +# - (attributes \{[\S\s]+\})? : optionally match attributes enclosed in braces and capture it as group 3 +ptx_prototype_pattern = r"\.(?:visible|extern)\s+\.(?:entry|func)\s+(\w+)\s*\(([^)]*)\)" +prototype_pattern = { + "ptx": ptx_prototype_pattern, +} + +ptx_arg_type_pattern = r"\.param\s+\.(\w+)" +arg_type_pattern = { + "ptx": ptx_arg_type_pattern, +} + + +def convert_type_repr(x): + # Currently we only capture the pointer type and assume the pointer is on global memory. + # TODO: Capture and support shared memory space + match = re.search(r'!tt\.ptr<([^,]+)', x) + tma = re.search(r'tt.nv_tma_desc = 1', x) + if tma is not None: + return 'nvTmaDesc' + x = re.sub(r' {[^}]+}', '', x) + if match is not None: + return '*' + convert_type_repr(match.group(1)) + return x + + +class ASTSource: + + def __init__(self, fn, signature, constexprs=None, attrs=None) -> None: + self.fn = fn + self.language = Language.TRITON + self.ext = "ttir" + self.name = fn.__name__ + self.signature = signature + self.constants = dict() + if constexprs is not None: + for k, v in constexprs.items(): + k = (fn.arg_names.index(k), ) if isinstance(k, str) else k + assert isinstance(k, tuple) + self.constants[k] = v + self.attrs = attrs or dict() + for k in self.signature.keys(): + if not isinstance(k, str): + raise TypeError("Signature keys must be string") + + def hash(self): + sorted_sig = [v for k, v in sorted(self.signature.items())] + get_key = lambda x: x.cache_key if hasattr(x, 'cache_key') else str(x) + constants_key = '-'.join([get_key(v) for k, v in sorted(self.constants.items())]) + key = f"{self.fn.cache_key}-{str(self.attrs)}-{sorted_sig}-{constants_key}" + return hashlib.sha256(key.encode("utf-8")).hexdigest() + + def make_ir(self, target: GPUTarget, options, codegen_fns, module_map, context): + from .code_generator import ast_to_ttir + return ast_to_ttir(self.fn, self, context=context, options=options, codegen_fns=codegen_fns, + module_map=module_map) + + def parse_options(self): + return dict() + + +class IRSource: + + def __init__(self, path, context, backend): + self.path = path + path = Path(path) + self.ext = path.suffix[1:] + self.language = Language.TRITON + self.src = path.read_text() + ir.load_dialects(context) + backend.load_dialects(context) + + # We don't have a easy-to-use PTX parser that we can use, so keep that regex for now. + # TODO - replace with a proper parser + if self.ext == "ptx": + match = re.search(prototype_pattern[self.ext], self.src, re.MULTILINE) + self.name = match.group(1) + signature = match.group(2) + types = re.findall(arg_type_pattern[self.ext], signature) + self.signature = {k: convert_type_repr(ty) for k, ty in enumerate(types)} + else: + self.module = ir.parse_mlir_module(self.path, context) + fn_name = self.module.get_entry_func_name() + self.name = "@" + fn_name + funcOp = self.module.get_function(fn_name) + func_ty = self.module.get_function_signature(funcOp) + self.signature = {k: ty for k, ty in enumerate(func_ty)} + + def hash(self): + return hashlib.sha256(self.src.encode("utf-8")).hexdigest() + + def make_ir(self, target: GPUTarget, options, codegen_fns, module_map, context): + self.module.context = context + return self.module + + def parse_options(self): + if self.ext == "ttgir": + num_warps = self.module.get_int_attr("ttg.num-warps") + assert num_warps is not None, "Unable to parse ttg.num-warps attribute" + return {'num_warps': num_warps} + return dict() + + +@functools.lru_cache() +def max_shared_mem(device): + return driver.active.utils.get_device_properties(device)["max_shared_mem"] + + +def parse(full_name, ext, context): + if ext == "ttir" or ext == "ttgir": + module = ir.parse_mlir_module(full_name, context) + module.context = context + return module + if ext == "llir" or ext == "ptx" or ext == "amdgcn": + return Path(full_name).read_text() + if ext == "cubin" or ext == "hsaco": + return Path(full_name).read_bytes() + + +def filter_traceback(e: BaseException): + """ + Removes code_generator.py and related files from tracebacks. + + These are uninteresting to the user -- "just show me *my* code!" + """ + if knobs.compilation.front_end_debugging: + return + + if e.__cause__ is not None: + filter_traceback(e.__cause__) + if e.__context__ is not None: + filter_traceback(e.__context__) + + # If a user has a file that matches one of these, they're out of luck. + BAD_FILES = [ + "/triton/compiler/code_generator.py", + "/ast.py", + ] + BAD_FILES = [bad_file.replace("/", os.sep) for bad_file in BAD_FILES] + + tb = e.__traceback__ + frames = [] + while tb is not None: + if not any(f for f in BAD_FILES if tb.tb_frame.f_code.co_filename.endswith(f)): + frames.append(tb) + tb = tb.tb_next + + for (cur_frame, next_frame) in zip(frames, frames[1:]): + cur_frame.tb_next = next_frame + + if not frames: + e.__traceback__ = None + else: + frames[-1].tb_next = None + e.__traceback__ = frames[0] + + +class CompileTimer: + + def __init__(self) -> None: + self.start: float = time.time() + self.ir_initialization_end: float | None = None + self.lowering_stage_ends: list[tuple[str, float]] = [] + self.store_results_end: float | None = None + + def finished_ir_initialization(self) -> None: + self.ir_initialization_end = time.time() + + def stage_finished(self, stage_name: str) -> None: + self.lowering_stage_ends.append((stage_name, time.time())) + + def end(self) -> knobs.CompileTimes: + timestamp = time.time() + if self.ir_initialization_end is None: + self.ir_initialization_end = timestamp + else: + self.store_results_end = timestamp + + def delta(start: float, end: float | None) -> int: + if end is None: + return 0 + return int((end - start) * 1000000) + + lowering_stage_durations = [] + stage_start = self.ir_initialization_end + for stage_name, stage_end in self.lowering_stage_ends: + lowering_stage_durations.append((stage_name, delta(stage_start, stage_end))) + stage_start = stage_end + + return knobs.CompileTimes( + ir_initialization=delta(self.start, self.ir_initialization_end), + lowering_stages=lowering_stage_durations, + store_results=delta(stage_start, self.store_results_end), + ) + + +def compile(src, target=None, options=None, _env_vars=None): + compilation_listener = knobs.compilation.listener + if compilation_listener: + timer = CompileTimer() + + if target is None: + target = driver.active.get_current_target() + assert isinstance(target, GPUTarget), "target must be of GPUTarget type" + backend = make_backend(target) + ir_source = not isinstance(src, ASTSource) + # create backend + if ir_source: + assert isinstance(src, str), "source must be either AST or a filepath" + context = ir.context() + src = IRSource(src, context, backend) + + extra_options = src.parse_options() + options = backend.parse_options(dict(options or dict(), **extra_options)) + # create cache manager + env_vars = get_cache_invalidating_env_vars() if _env_vars is None else _env_vars + key = get_cache_key(src, backend, options, env_vars=env_vars) + hash = hashlib.sha256(key.encode("utf-8")).hexdigest() + fn_cache_manager = get_cache_manager(hash) + # For dumping/overriding only hash the source as we want it to be independent of triton + # core changes to make it easier to track kernels by hash. + enable_override = knobs.compilation.override + enable_ir_dump = knobs.compilation.dump_ir + store_only_binary = knobs.compilation.store_binary_only + fn_override_manager = get_override_manager(src.hash()) if enable_override else None + fn_dump_manager = get_dump_manager(src.hash()) if enable_ir_dump else None + # Pre-truncate the file name here to avoid hitting the 255 character limit on common platforms. + # The final file name in the cache will have a format of f"{filename}.{ext}.tmp.pid_{pid}_{uuid}". + # A PID string can be 5-character long. A UUID string has typically 36 characters. Let's truncate + # the file name to 150 characters to be safe. + file_name = src.name[:150] + metadata_filename = f"{file_name}.json" + metadata_group = fn_cache_manager.get_group(metadata_filename) or {} + metadata_path = metadata_group.get(metadata_filename) + always_compile = knobs.compilation.always_compile + if not always_compile and metadata_path is not None: + # cache hit! + res = CompiledKernel(src, metadata_group, hash) + if compilation_listener: + compilation_listener( + src=src, + metadata=res.metadata._asdict(), + metadata_group=metadata_group, + times=timer.end(), + cache_hit=True, + ) + return res + + # initialize metadata + metadata = { + "hash": hash, + "target": target, + **options.__dict__, + **env_vars, + } + metadata["triton_version"] = __version__ + # run compilation pipeline and populate metadata + stages = dict() + backend.add_stages(stages, options, src.language) + first_stage = list(stages.keys()).index(src.ext) + # when the source is an IR file, don't apply the passes related to this stage. This makes it easier to write IR level tests. + if ir_source: + first_stage += 1 + + # For IRSource, we have already grabbed the context + called both + # ir.load_dialects and backend.load_dialects. + if not isinstance(src, IRSource): + context = ir.context() + ir.load_dialects(context) + backend.load_dialects(context) + + codegen_fns = backend.get_codegen_implementation(options) + module_map = backend.get_module_map() + try: + module = src.make_ir(target, options, codegen_fns, module_map, context) + except Exception as e: + filter_traceback(e) + raise + + if ir_source: + ir_filename = f"{file_name}.{src.ext}" + metadata_group[ir_filename] = fn_cache_manager.put(module, ir_filename) + else: + ir_filename = f"{file_name}.source" + metadata_group[ir_filename] = fn_cache_manager.put(module, ir_filename) + + use_ir_loc = knobs.compilation.use_ir_loc + if ir_source and use_ir_loc: + module.create_location_snapshot(src.path) + print(f"Creating new locations for {src.path}") + + if compilation_listener: + timer.finished_ir_initialization() + for ext, compile_ir in list(stages.items())[first_stage:]: + next_module = compile_ir(module, metadata) + ir_filename = f"{file_name}.{ext}" + if fn_override_manager is None: + # Users can override kernels at scale by setting `ir_override` in autotune config + # without TRITON_KERNEL_OVERRIDE + if (ir_override := metadata.get("ir_override", None)) and ir_override.endswith(f".{ext}"): + next_module = parse(ir_override, ext, context) + elif full_name := fn_override_manager.get_file(ir_filename): + print(f"\nOverriding kernel with file {full_name}") + next_module = parse(full_name, ext, context) + # If TRITON_STORE_BINARY_ONLY is 1, only store cubin/hsaco/json + if (not store_only_binary) or (ext in ("cubin", "hsaco", "json")): + metadata_group[ir_filename] = fn_cache_manager.put(next_module, ir_filename) + if fn_dump_manager is not None: + fn_dump_manager.put(next_module, ir_filename) + if ext == "cubin": + sass = get_sass(next_module) + fn_dump_manager.put(sass, file_name + ".sass") + # use an env variable to parse ir from file + if use_ir_loc == ext: + ir_full_name = fn_cache_manager.get_file(ir_filename) + next_module.create_location_snapshot(ir_full_name) + print(f"Creating new locations for {ir_full_name}") + module = next_module + if compilation_listener: + timer.stage_finished(ext) + # write-back metadata + metadata_group[metadata_filename] = fn_cache_manager.put(json.dumps(metadata, default=vars), metadata_filename, + binary=False) + fn_cache_manager.put_group(metadata_filename, metadata_group) + # Compilation completed, disabling multithreading in context. + # This is needed to safely finalize threads pool inside context: if current process forks before + # python GC deletes context object, thread pool in child process will be invalid, which could + # lead to child crash or hang. + # + # However disabling multithreading causes the code to hang if the ASAN pass is enabled + # this is likely due to the llvm-symbolizer forking a process + # TODO: Reconcile the difference here between the ASAN and non-ASAN path with enabling + # multithreading in the MLIR context + if not knobs.compilation.enable_asan: + context.disable_multithreading() + + # notify any listener + if compilation_listener: + compilation_listener(src=src, metadata=metadata, metadata_group=metadata_group, times=timer.end(), + cache_hit=False) + # return handle to compiled kernel + return CompiledKernel(src, metadata_group, hash) + + +def make_backend(target: GPUTarget) -> BaseBackend: + actives = [x.compiler for x in backends.values() if x.compiler.supports_target(target)] + if len(actives) != 1: + raise RuntimeError( + f"{len(actives)} compatible backends for target ({target.backend}) ({actives}). There should only be one.") + return actives[0](target) + + +class LazyDict: + + def __init__(self, data): + self.data = data + self.extras = [] + + def get(self): + for func, args in self.extras: + self.data = self.data | func(*args) + self.extras.clear() + return self.data + + def add(self, func, args): + self.extras.append((func, args)) + + +class AsmDict(dict): + + def __missing__(self, key): + + if key == "sass": + value = get_sass(self["cubin"]) + else: + raise KeyError("Unknown key: '%s'" % key) + + self[key] = value + return value + + +def _raise_error(err, *args, **kwargs): + raise copy.deepcopy(err) + + +class CompiledKernel: + + def __init__(self, src, metadata_group, hash): + from collections import namedtuple + metadata_path = next((Path(p) for c, p in metadata_group.items() if c.endswith(".json"))) + metadata = json.loads(metadata_path.read_text()) + metadata['cluster_dims'] = tuple(metadata['cluster_dims']) + # JSON serialization dumps the target as a dict. Restore it to a GPUTarget. + target = metadata['target'] + metadata['target'] = GPUTarget(target['backend'], target['arch'], target['warp_size']) + KernelMetadata = namedtuple('KernelMetadata', sorted(list(metadata.keys()))) + self.metadata = KernelMetadata(**metadata) + backend = make_backend(self.metadata.target) + self.packed_metadata = backend.pack_metadata(self.metadata) + self.src = src + self.hash = hash + self.name = self.metadata.name + # stores the text of each level of IR that was generated during compilation + asm_files = [Path(p) for c, p in metadata_group.items() if not c.endswith(".json")] + binary_ext = backend.binary_ext + self.asm = AsmDict({ + file.suffix[1:]: file.read_bytes() if file.suffix[1:] == binary_ext else file.read_text() + for file in asm_files + }) + self.metadata_group = metadata_group + self.kernel = self.asm[binary_ext] + # binaries are lazily initialized + # because it involves doing runtime things + # (e.g., checking amount of shared memory on current device) + self.module = None + self.function = None + self._run = None + + def _init_handles(self): + if self.module is not None: + return + + def raise_(err): + # clone the exception object so that the one saved in the closure + # of the partial function below doesn't get assigned a stack trace + # after the subsequent raise. otherwise, the CompiledKernel instance + # saved in the (global) kernel cache will keep references to all the + # locals in the traceback via the exception instance in the closure. + cloned_err = copy.deepcopy(err) + self._run = functools.partial(_raise_error, cloned_err) + raise err + + device = driver.active.get_current_device() + # create launcher + self._run = driver.active.launcher_cls(self.src, self.metadata) + # not enough shared memory to run the kernel + max_shared = max_shared_mem(device) + if self.metadata.shared > max_shared: + raise_(OutOfResources(self.metadata.shared, max_shared, "shared memory")) + if hasattr(self.metadata, "tmem_size") and self.metadata.tmem_size is not None: + # Use blackwell max tmem size for now, this should be moved in device properties + max_tmem_size = 512 # tmem size in number of columns + if self.metadata.tmem_size > max_tmem_size: + raise_(OutOfResources(self.metadata.tmem_size, max_tmem_size, "tensor memory")) + if knobs.runtime.kernel_load_start_hook is not None: + knobs.runtime.kernel_load_start_hook(self.module, self.function, self.name, self.metadata_group, self.hash) + # TODO: n_regs, n_spills should be metadata generated when calling `ptxas` + self.module, self.function, self.n_regs, self.n_spills, self.n_max_threads = driver.active.utils.load_binary( + self.name, self.kernel, self.metadata.shared, device) + warp_size = driver.active.get_current_target().warp_size + if self.metadata.num_warps * warp_size > self.n_max_threads: + raise_(OutOfResources(self.metadata.num_warps * warp_size, self.n_max_threads, "threads")) + if knobs.runtime.kernel_load_end_hook is not None: + knobs.runtime.kernel_load_end_hook(self.module, self.function, self.name, self.metadata_group, self.hash) + + @property + def run(self): + if self._run is None: + self._init_handles() + return self._run + + def launch_metadata(self, grid, stream, *args): + if knobs.runtime.launch_enter_hook is None: + return None + self._init_handles() + ret = LazyDict({"name": self.name, "function": self.function, "stream": stream}) + if not isinstance(self.src, ASTSource) or self.src.fn.launch_metadata is None: + return ret + arg_dict = {name: arg for name, arg in zip(self.src.fn.arg_names, args)} + ret.add(self.src.fn.launch_metadata, (grid, self.metadata, arg_dict)) + return ret + + def __getitem__(self, grid): + self._init_handles() + + def runner(*args, stream=None): + if stream is None: + device = driver.active.get_current_device() + stream = driver.active.get_current_stream(device) + launch_metadata = self.launch_metadata(grid, stream, *args) + self.run(grid[0], grid[1], grid[2], stream, self.function, self.packed_metadata, launch_metadata, + knobs.runtime.launch_enter_hook, knobs.runtime.launch_exit_hook, *args) + + return runner diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/errors.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..39e6c4dfb04dd2067d50ce7c79f762c5e7e2d5b8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/errors.py @@ -0,0 +1,51 @@ +import ast +from typing import Optional +from ..errors import TritonError + + +class CompilationError(TritonError): + """Base class for all errors raised during compilation""" + source_line_count_max_in_message = 12 + + def _format_message(self) -> str: + node = self.node + if self.src is None: + source_excerpt = " " + else: + if hasattr(node, 'lineno'): + source_excerpt = self.src.split('\n')[:node.lineno][-self.source_line_count_max_in_message:] + if source_excerpt: + source_excerpt.append(' ' * node.col_offset + '^') + source_excerpt = '\n'.join(source_excerpt) + else: + source_excerpt = " " + else: + source_excerpt = self.src + + message = "at {}:{}:\n{}".format(node.lineno, node.col_offset, source_excerpt) if hasattr( + node, 'lineno') else source_excerpt + if self.error_message: + message += '\n' + self.error_message + return message + + def __init__(self, src: Optional[str], node: ast.AST, error_message: Optional[str] = None): + self.src = src + self.node = node + self.error_message = error_message + self.message = self._format_message() + + def __str__(self): + return self.message + + def __reduce__(self): + # this is necessary to make CompilationError picklable + return type(self), (self.src, self.node, self.error_message) + + +class CompileTimeAssertionFailure(CompilationError): + """Specific exception for failed tests in `static_assert` invocations""" + pass + + +class UnsupportedLanguageConstruct(CompilationError): + pass diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/make_launcher.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/compiler/make_launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/errors.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..3a0a863553b9d62ccb60d0090ee6d66f8b9e3b79 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/errors.py @@ -0,0 +1,5 @@ +"""Base class for all errors raised by Triton""" + + +class TritonError(Exception): + ... diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..164ebdcac64af4a27ec50493817e2a1b7e371b9b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/__init__.py @@ -0,0 +1,5 @@ +from . import nvidia +from ._runtime import constexpr_function, jit +from triton.language.core import must_use_result + +__all__ = ["constexpr_function", "jit", "must_use_result", "nvidia"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/_compiler.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/_compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/_runtime.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..d98bb2098b1385e0d338b5dffec62884d3d9a5d9 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/_runtime.py @@ -0,0 +1,102 @@ +from __future__ import annotations +from triton.compiler.compiler import ASTSource +from triton.backends.compiler import Language +from triton.runtime.jit import JITFunction, constexpr_function +from typing import TypeVar, Optional, Callable, Iterable, Union +from triton._C.libtriton import ir + +T = TypeVar("T") + +__all__ = ["constexpr_function", "jit"] + + +class GluonASTSource(ASTSource): + + def __init__(self, fn, signature, constexprs=None, attrs=None) -> None: + super().__init__(fn, signature, constexprs, attrs) + self.language = Language.GLUON + self.ext = "ttgir" + + def make_ir(self, target, options, codegen_fns, module_map, context): + from triton.compiler.compiler import make_backend + from triton.compiler.code_generator import ast_to_ttir + + builder = ir.builder(context) + module = builder.create_module() + + # Assign module attributes eagerly, as they are needed to verify layouts + backend = make_backend(target) + target = backend.get_target_name(options) + + module.set_attr("ttg.target", builder.get_string_attr(target)) + module.set_attr("ttg.num-warps", builder.get_int32_attr(options.num_warps)) + module.set_attr("ttg.num-ctas", builder.get_int32_attr(options.num_ctas)) + module.set_attr("ttg.threads-per-warp", builder.get_int32_attr(options.warp_size)) + + is_cuda = options.backend_name == "cuda" + if is_cuda and options.maxnreg is not None: + module.set_attr("ttg.maxnreg", builder.get_int32_attr(options.maxnreg)) + + module = ast_to_ttir(self.fn, self, context=context, options=options, codegen_fns=codegen_fns, + module_map=module_map, module=module) + return module + + +class GluonJITFunction(JITFunction[T]): + + def create_binder(self): + result = super().create_binder() + self.ASTSource = GluonASTSource + return result + + def is_gluon(self): + return True + + +def jit( + fn: Optional[T] = None, + *, + version=None, + repr: Optional[Callable] = None, + launch_metadata: Optional[Callable] = None, + do_not_specialize: Optional[Iterable[int | str]] = None, + do_not_specialize_on_alignment: Optional[Iterable[int | str]] = None, + debug: Optional[bool] = None, + noinline: Optional[bool] = None, +) -> Union[GluonJITFunction[T], Callable[[T], JITFunction[T]]]: + """ + Decorator for JIT-compiling a function using the Triton compiler. + + :note: When a jit'd function is called, arguments are + implicitly converted to pointers if they have a :code:`.data_ptr()` method + and a `.dtype` attribute. + + :note: This function will be compiled and run on the GPU. It will only have access to: + + * python primitives, + * builtins within the triton package, + * arguments to this function, + * other jit'd functions + + :param fn: the function to be jit-compiled + :type fn: Callable + """ + + def decorator(fn: T) -> JITFunction[T]: + assert callable(fn) + return GluonJITFunction( + fn, + version=version, + do_not_specialize=do_not_specialize, + do_not_specialize_on_alignment=do_not_specialize_on_alignment, + debug=debug, + noinline=noinline, + repr=repr, + launch_metadata=launch_metadata, + ) + + if fn is not None: + return decorator(fn) + + else: + return decorator diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ed98ddc6747cb148b1d881d52fac1422a375ab6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/__init__.py @@ -0,0 +1,119 @@ +from ._core import ( + base_value, + base_type, + block_type, + broadcast, + constexpr, + dtype, + void, + int1, + int8, + int16, + int32, + int64, + uint8, + uint16, + uint32, + uint64, + float8e5, + float8e5b16, + float8e4nv, + float8e4b8, + float8e4b15, + float16, + bfloat16, + float32, + float64, + pointer_type, + shared_memory_descriptor, + tensor, + tuple, + tuple_type, + _unwrap_if_constexpr, + # API Functions + allocate_shared_memory, + arange, + associative_scan, + atomic_add, + atomic_and, + atomic_cas, + atomic_max, + atomic_min, + atomic_or, + atomic_xchg, + atomic_xor, + convert_layout, + device_assert, + expand_dims, + full, + histogram, + inline_asm_elementwise, + join, + load, + map_elementwise, + max_constancy, + max_contiguous, + maximum, + minimum, + multiple_of, + num_programs, + permute, + program_id, + reduce, + reshape, + set_auto_layout, + split, + static_assert, + static_print, + static_range, + store, + thread_barrier, + to_tensor, + warp_specialize, + where, +) +from ._layouts import ( + AutoLayout, + BlockedLayout, + SliceLayout, + DistributedLinearLayout, + DotOperandLayout, + NVMMADistributedLayout, + NVMMASharedLayout, + SwizzledSharedLayout, + PaddedSharedLayout, +) +from ._math import ( + umulhi, + exp, + exp2, + fma, + log, + log2, + cos, + rsqrt, + sin, + sqrt, + sqrt_rn, + abs, + fdiv, + div_rn, + erf, + floor, + ceil, +) +from ._standard import ( + cdiv, + full_like, + max, + min, + reduce_or, + sum, + xor_sum, + zeros, + zeros_like, +) + +from . import nvidia +from . import amd +from . import extra diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/_core.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/_core.py new file mode 100644 index 0000000000000000000000000000000000000000..34cd6fa3b1613dde5e5c6d111f72007b36ad25b8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/_core.py @@ -0,0 +1,490 @@ +from __future__ import annotations +import math +from typing import TypeVar, List, TYPE_CHECKING, Tuple +from functools import wraps + +if TYPE_CHECKING: + from triton._C.libtriton.gluon_ir import GluonOpBuilder + from ._semantic import GluonSemantic + +from ._layouts import SharedLayout, DistributedLayout +from triton._C.libtriton import ir +import triton.language.core as tl_core +from triton.language.core import ( + constexpr, + base_value, + base_type, + dtype, + block_type, # TODO: block type with layout info + pointer_type, + void, + int1, + int8, + int16, + int32, + int64, + uint8, + uint16, + uint32, + uint64, + float8e5, + float8e5b16, + float8e4nv, + float8e4b8, + float8e4b15, + float16, + bfloat16, + float32, + float64, + _unwrap_if_constexpr, + _unwrap_shape, + static_range, + tensor, + tuple, + tuple_type, +) + +# We define __all__ only to appease the python linter, these are not used in +# this file but we want to import them anyway so they are importable from here. +__all__ = [ + "constexpr", + "pointer_type", + "void", + "int1", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "float8e5", + "float8e5b16", + "float8e4nv", + "float8e4b8", + "float8e4b15", + "float16", + "bfloat16", + "float32", + "float64", + "static_range", + "tuple", + "tuple_type", +] + +T = TypeVar("T") + +# TODO: split these +GLUON_BUILTIN = "__triton_builtin__" + + +def builtin(fn: T) -> T: + """Mark a function as a builtin.""" + assert callable(fn) + + @wraps(fn) + def wrapper(*args, **kwargs): + if "_semantic" not in kwargs or kwargs["_semantic"] is None: + raise ValueError("Did you forget to add @triton.gluon.jit ? " + "(`_semantic` argument must be provided outside of JIT functions.)") + return fn(*args, **kwargs) + + setattr(wrapper, GLUON_BUILTIN, True) + + return wrapper + + +# Explicitly import forwarded Triton language symbols so mypy sees them. +associative_scan = builtin(tl_core.associative_scan) +atomic_add = builtin(tl_core.atomic_add) +atomic_and = builtin(tl_core.atomic_and) +atomic_cas = builtin(tl_core.atomic_cas) +atomic_max = builtin(tl_core.atomic_max) +atomic_min = builtin(tl_core.atomic_min) +atomic_or = builtin(tl_core.atomic_or) +atomic_xchg = builtin(tl_core.atomic_xchg) +atomic_xor = builtin(tl_core.atomic_xor) +broadcast = builtin(tl_core.broadcast) +device_assert = builtin(tl_core.device_assert) +expand_dims = builtin(tl_core.expand_dims) +inline_asm_elementwise = builtin(tl_core.inline_asm_elementwise) +join = builtin(tl_core.join) +load = builtin(tl_core.load) +map_elementwise = builtin(tl_core.map_elementwise) +max_constancy = builtin(tl_core.max_constancy) +max_contiguous = builtin(tl_core.max_contiguous) +maximum = builtin(tl_core.maximum) +minimum = builtin(tl_core.minimum) +multiple_of = builtin(tl_core.multiple_of) +num_programs = builtin(tl_core.num_programs) +permute = builtin(tl_core.permute) +program_id = builtin(tl_core.program_id) +reduce = builtin(tl_core.reduce) +reshape = builtin(tl_core.reshape) +split = builtin(tl_core.split) +static_assert = builtin(tl_core.static_assert) +static_print = builtin(tl_core.static_print) +store = builtin(tl_core.store) +to_tensor = builtin(tl_core.to_tensor) +where = builtin(tl_core.where) + + +class distributed_type(block_type): + + def __init__(self, element_ty: dtype, shape: List[int], layout): + super().__init__(element_ty, shape) + self.layout = layout + self.name = f"<{self.shape}, {self.element_ty}, {self.layout}>" + assert isinstance(layout, DistributedLayout) + + def to_ir(self, builder: ir.builder) -> ir.type: + elem_ty = self.element_ty.to_ir(builder) + layout = self.layout._to_ir(builder) + return builder.get_distributed_ty(elem_ty, self.shape, layout) + + def mangle(self) -> str: + elt = self.scalar.mangle() + shape = "_".join(map(str, self.shape)) + layout = self.layout.mangle() + return f"{elt}S{shape}SL{layout}L" + + def with_element_ty(self, scalar_ty: dtype) -> block_type: + return distributed_type(scalar_ty, self.shape, self.layout) + + def __eq__(self, other) -> bool: + if not isinstance(other, distributed_type): + return False + return super().__eq__(other) and self.layout == other.layout + + +class shared_memory_descriptor_type(base_type): + + def __init__(self, element_ty, shape, layout, alloc_shape): + self.element_ty = element_ty + self.shape = shape + self.layout = layout + self.alloc_shape = alloc_shape + assert isinstance(layout, SharedLayout) + + def to_ir(self, builder: GluonOpBuilder) -> None: + return builder.get_shared_mem_desc_ty( + self.element_ty.to_ir(builder), + self.shape, + self.layout._to_ir(builder), + self.alloc_shape, + ) + + def _unflatten_ir(self, handles: List[ir.Value], cursor: int) -> Tuple[shared_memory_descriptor, int]: + value = shared_memory_descriptor(handles[cursor], self.element_ty, self.shape, self.layout, self.alloc_shape) + return value, cursor + 1 + + def _flatten_ir_types(self, builder: GluonOpBuilder, out: List[ir.type]) -> None: + out.append(self.to_ir(builder)) + + def __str__(self) -> str: + return f"shared_memory_descriptor<{self.element_ty}, {self.shape}, {self.layout}, {self.alloc_shape}>" + + def __eq__(self, other) -> bool: + return (type(self) is type(other) and self.shape == other.shape and self.layout == other.layout + and self.alloc_shape == other.alloc_shape) + + def __neq__(self, other) -> bool: + return not (self == other) + + def mangle(self) -> str: + shape_str = "_".join([str(s) for s in self.shape]) + return f"MD{self.element_ty.mangle()}S{shape_str}SL{self.layout.mangle()}LAS{self.alloc_shape}ASMD" + + +class shared_memory_descriptor(base_value): + """ + Represents a handle to a shared memory allocation in Gluon IR. + """ + + def __init__(self, handle, element_ty, shape, layout, alloc_shape): + self.handle = handle + self.type = shared_memory_descriptor_type(element_ty, shape, layout, alloc_shape) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + handles.append(self.handle) + + @property + def dtype(self): + return self.type.element_ty + + @property + def shape(self): + return self.type.shape + + @property + def rank(self): + return len(self.shape) + + @property + def numel(self) -> int: + return math.prod(self.shape) + + @property + def layout(self): + return self.type.layout + + def __str__(self) -> str: + return str(self.type) + + @builtin + def load(self, layout, _semantic: GluonSemantic = None) -> tensor: + """ + Load a tensor from shared memory. + + Args: + layout (DistributedLayout): The destination layout of the tensor. + + Returns: + tensor: A Gluon tensor containing the loaded data. + """ + layout = _unwrap_if_constexpr(layout) + return _semantic.shared_load(self, layout) + + @builtin + def store(self, value, _semantic: GluonSemantic = None) -> None: + """ + Store a tensor into shared memory. + + Args: + value (tensor): The tensor whose contents to store. + """ + return _semantic.shared_store(self, value) + + @builtin + def slice(self, start, length, dim=0, _semantic: GluonSemantic = None) -> shared_memory_descriptor: + """ + Create a subview of shared memory by slicing along a given dimension. + + Args: + start (int): The starting index of the slice. + length (int): The length of the slice. + dim (int): The dimension to slice (default: 0). + + Returns: + shared_memory_descriptor: Descriptor for the sliced subview. + """ + start = _unwrap_if_constexpr(start) + length = _unwrap_if_constexpr(length) + dim = _unwrap_if_constexpr(dim) + return _semantic.memdesc_slice(self, start, length, dim) + + @builtin + def index(self, index, _semantic: GluonSemantic = None) -> shared_memory_descriptor: + """ + Create a subview of shared memory by indexing along the first dimension. + + Args: + index (int): The index at which to take the subview. + + Returns: + shared_memory_descriptor: Descriptor for the indexed subview. + """ + index = _unwrap_if_constexpr(index) + return _semantic.memdesc_index(self, index) + + @builtin + def permute(self, order, _semantic: GluonSemantic = None) -> shared_memory_descriptor: + """ + Permute the dimensions of the shared memory descriptor. + + Args: + order (List[int]): The new ordering of dimensions. + + Returns: + shared_memory_descriptor: Descriptor with permuted dimensions. + """ + order = [_unwrap_if_constexpr(o) for o in order] + return _semantic.memdesc_trans(self, order) + + @builtin + def reshape(self, shape, _semantic: GluonSemantic = None) -> shared_memory_descriptor: + """ + Reshape the shared memory descriptor to a new shape and layout. + + Args: + shape (List[int]): The target shape. + + Returns: + shared_memory_descriptor: Descriptor with the new shape and layout. + """ + shape = [_unwrap_if_constexpr(s) for s in shape] + + return _semantic.memdesc_reshape(self, shape) + + @builtin + def _reinterpret(self, dtype, shape, layout, _semantic: GluonSemantic = None) -> shared_memory_descriptor: + """ + Reinterpret the shared memory descriptor as a different dtype, shape, or layout. + + Args: + dtype (dtype): The new data type. + shape (List[int]): The new shape. + layout (SharedLayout): The new layout. + + Returns: + shared_memory_descriptor: Descriptor with updated type and layout. + """ + dtype = _unwrap_if_constexpr(dtype) + shape = [_unwrap_if_constexpr(s) for s in shape] + layout = _unwrap_if_constexpr(layout) + + return _semantic.memdesc_reinterpret(self, dtype, shape, layout) + + @builtin + def _keep_alive(self, _semantic: GluonSemantic = None) -> None: + """ + Dummy use to keep the shared memory descriptor alive. + """ + return _semantic.shared_dealloc(self) + + +@builtin +def arange(start, end, layout=None, _semantic=None): + """ + Generate a sequence tensor with values in [start, end) using a specified layout. + + Args: + start (int): Inclusive start of the sequence. + end (int): Exclusive end of the sequence. + layout (DistributedLayout): The layout of the output tensor. Defaults to AutoLayout. + + Returns: + tensor: A 1D tensor containing sequential values. + """ + start = _unwrap_if_constexpr(start) + end = _unwrap_if_constexpr(end) + layout = _unwrap_if_constexpr(layout) + return _semantic.arange(start, end, layout) + + +@builtin +def convert_layout(value, layout, assert_trivial=False, _semantic=None): + """ + Convert a tensor to a different distributed layout. + + Args: + value (tensor): The input tensor. + layout (DistributedLayout): The target layout. + assert_trivial (bool): If True, asserts that the conversion is trivial (no data movement). + + Returns: + tensor: The tensor with the new layout. + """ + layout = _unwrap_if_constexpr(layout) + return _semantic.convert_layout(value, layout, assert_trivial) + + +@builtin +def full(shape, value, dtype, layout=None, _semantic=None): + """ + Create a tensor filled with a scalar value, with specified shape, dtype, and layout. + + Args: + shape (Sequence[int]): The shape of the tensor. + value (int or float): The fill value. + dtype (dtype): The data type for the tensor. + layout (Optional[DistributedLayout]): The layout of the output tensor, defaults to AutoLayout(). + + Returns: + tensor: A tensor where every element equals value. + """ + shape = _unwrap_shape(shape) + value = _unwrap_if_constexpr(value) + dtype = _unwrap_if_constexpr(dtype) + layout = _unwrap_if_constexpr(layout) + return _semantic.full(shape, value, dtype, layout) + + +@builtin +def histogram(input, num_bins, mask=None, layout=None, _semantic=None, _generator=None): + """ + Compute a histogram of a 1D integer tensor. + + Args: + input (tensor): 1D tensor of integer values. + num_bins (int): Number of bins. Bins have width 1 and start at 0. + mask (Optional[tensor]): Boolean mask to exclude elements when False. + layout (DistributedLayout): Destination layout of the output histogram. + + Returns: + tensor: 1D int32 tensor of length `num_bins` with the requested layout. + """ + num_bins = _unwrap_if_constexpr(num_bins) + layout = _unwrap_if_constexpr(layout) + if mask is not None: + mask = _semantic.to_tensor(mask) + return _semantic.histogram(input, num_bins, mask, layout) + + +@builtin +def allocate_shared_memory(element_ty, shape, layout, value=None, _semantic=None) -> shared_memory_descriptor: + """ + Allocate shared memory for a tensor with the given element type, shape, and layout. + + Args: + element_ty (dtype): The element data type. + shape (Sequence[int]): The dimensions of the shared memory. + layout (SharedLayout): The shared memory layout. + value (tensor, optional): Initial value to copy into shared memory. + + Returns: + shared_memory_descriptor: Descriptor for the allocated memory. + """ + element_ty = _unwrap_if_constexpr(element_ty) + shape = _unwrap_if_constexpr(shape) + shape = [_unwrap_if_constexpr(s) for s in shape] + layout = _unwrap_if_constexpr(layout) + return _semantic.allocate_shared(element_ty, shape, layout, value) + + +@builtin +def set_auto_layout(value, layout, _semantic=None): + """ + Set a a tensor with AutoLayout to a concrete layout + + Args: + value (tensor): The input tensor. + layout (DistribtedLayout): The target layout. + + Returns: + tensor: The tensor with the new layout. + """ + layout = _unwrap_if_constexpr(layout) + return _semantic.set_auto_layout(value, layout) + + +@builtin +def warp_specialize(default_args, default_partition, worker_args, worker_partitions, worker_num_warps, worker_num_regs, + _semantic=None, _generator=None): + """ + Create a warp-specialized execution region, partitioning work across warps. + + Args: + default_args (List[Any]): Arguments for the default region. + default_partition (callable): Function to build the default execution region. + worker_args (List[Any]): Arguments for each warp partition. + worker_partitions (List[callable]): Functions for each warp partition. + worker_num_warps (List[int]): Number of warps per partition. + worker_num_regs (List[int]): Number of registers per partition. + + Returns: + Tuple[Any, ...]: Results from the default region. + """ + worker_num_warps = [_unwrap_if_constexpr(w) for w in worker_num_warps] + worker_num_regs = [_unwrap_if_constexpr(r) for r in worker_num_regs] + return _semantic.warp_specialize(default_args, default_partition, worker_args, worker_partitions, worker_num_warps, + worker_num_regs, _generator) + + +@builtin +def thread_barrier(_semantic=None): + """ + Insert a barrier to synchronize threads within a CTA. + """ + return _semantic.debug_barrier() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/_layouts.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/_layouts.py new file mode 100644 index 0000000000000000000000000000000000000000..18dd7a6bc6a16aae5cf7c9ea03051213dec1f66a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/_layouts.py @@ -0,0 +1,583 @@ +from dataclasses import dataclass +from typing import List, Optional +from triton.language.core import _unwrap_if_constexpr, _unwrap_shape, constexpr_type +from triton.runtime.jit import constexpr_function + + +def _realize_cta_layout(layout, rank): + ctas_per_cga = layout.ctas_per_cga or [1] * rank + cta_split_num = layout.cta_split_num or [1] * rank + cta_order = layout.cta_order or list(reversed(range(rank))) + object.__setattr__(layout, "ctas_per_cga", ctas_per_cga) + object.__setattr__(layout, "cta_split_num", cta_split_num) + object.__setattr__(layout, "cta_order", cta_order) + + +class DistributedLayout: + """ + Base class for distributed memory layouts in Gluon IR. + """ + + @property + def type(self): + return constexpr_type(self) + + +@dataclass(frozen=True) +class AutoLayout(DistributedLayout): + + def _to_ir(self, builder): + return builder.get_auto_layout() + + def mangle(self): + return "AL" + + +@dataclass(frozen=True) +class BlockedLayout(DistributedLayout): + """ + Represents a blocked layout, partitioning a tensor across threads, warps, and CTAs. + + Args: + size_per_thread (List[int]): Number of elements per thread per dimension. + threads_per_warp (List[int]): Number of threads per warp per dimension. + warps_per_cta (List[int]): Number of warps per CTA per dimension. + order (List[int]): The ordering of dimensions for partitioning. + ctas_per_cga (Optional[List[int]]): CTAs per CGA grouping. + cta_split_num (Optional[List[int]]): Split factors for CTAs. + cta_order (Optional[List[int]]): Ordering for CTAs. + """ + size_per_thread: List[int] + threads_per_warp: List[int] + warps_per_cta: List[int] + order: List[int] + ctas_per_cga: Optional[List[int]] = None + cta_split_num: Optional[List[int]] = None + cta_order: Optional[List[int]] = None + + def __post_init__(self): + super().__setattr__("size_per_thread", _unwrap_if_constexpr(self.size_per_thread)) + super().__setattr__("threads_per_warp", _unwrap_if_constexpr(self.threads_per_warp)) + super().__setattr__("warps_per_cta", _unwrap_if_constexpr(self.warps_per_cta)) + super().__setattr__("order", _unwrap_if_constexpr(self.order)) + super().__setattr__("ctas_per_cga", _unwrap_if_constexpr(self.ctas_per_cga)) + super().__setattr__("cta_split_num", _unwrap_if_constexpr(self.cta_split_num)) + super().__setattr__("cta_order", _unwrap_if_constexpr(self.cta_order)) + + rank = len(self.size_per_thread) + _realize_cta_layout(self, rank) + assert len(self.threads_per_warp) == rank + assert len(self.warps_per_cta) == rank + assert len(self.order) == rank + assert len(self.ctas_per_cga) == rank + assert len(self.cta_split_num) == rank + assert len(self.cta_order) == rank + + def _to_ir(self, builder): + return builder.get_blocked_layout( + self.size_per_thread, + self.threads_per_warp, + self.warps_per_cta, + self.order, + self.ctas_per_cga, + self.cta_split_num, + self.cta_order, + ) + + def mangle(self) -> str: + + def stringify(x): + if x is None: + return "" + return "_".join(map(str, x)) + + size_per_thread = stringify(self.size_per_thread) + threads_per_warp = stringify(self.threads_per_warp) + warps_per_cta = stringify(self.warps_per_cta) + order = stringify(self.order) + ctas_per_cga = stringify(self.ctas_per_cga) + cta_split_num = stringify(self.cta_split_num) + cta_order = stringify(self.cta_order) + return f"B{size_per_thread}B{threads_per_warp}B{warps_per_cta}B{order}B{ctas_per_cga}B{cta_split_num}B{cta_order}B" + + def __hash__(self): + return hash(( + tuple(self.size_per_thread), + tuple(self.threads_per_warp), + tuple(self.warps_per_cta), + tuple(self.order), + tuple(self.ctas_per_cga) if self.ctas_per_cga else None, + tuple(self.cta_split_num) if self.cta_split_num else None, + tuple(self.cta_order) if self.cta_order else None, + )) + + +@dataclass(frozen=True) +class SliceLayout(DistributedLayout): + """ + Represents a layout corresponding to slicing a distributed tensor along one dimension. + + Args: + dim (int): The dimension index to slice. + parent (DistributedLayout): The parent layout before slicing. + """ + dim: int + parent: DistributedLayout + + def __post_init__(self): + super().__setattr__("dim", _unwrap_if_constexpr(self.dim)) + super().__setattr__("parent", _unwrap_if_constexpr(self.parent)) + + def _to_ir(self, builder): + return builder.get_slice_layout( + self.dim, + self.parent._to_ir(builder), + ) + + def mangle(self) -> str: + return f"SL{self.dim}_{self.parent.mangle()}SL" + + def __hash__(self): + return hash((self.dim, self.parent)) + + +@dataclass(frozen=True) +class DistributedLinearLayout(DistributedLayout): + """ + Represents a linear distributed layout with explicit bases at register, lane, warp, and block levels. + See: https://arxiv.org/abs/2505.23819 for reference. + + Args: + reg_bases (List[List[int]]): Bases for register-level distribution. + lane_bases (List[List[int]]): Bases for lane-level distribution. + warp_bases (List[List[int]]): Bases for warp-level distribution. + block_bases (List[List[int]]): Bases for block-level distribution. + shape (List[int]): The tensor global shape. + """ + reg_bases: List[List[int]] + lane_bases: List[List[int]] + warp_bases: List[List[int]] + block_bases: List[List[int]] + shape: List[int] + + def __post_init__(self): + super().__setattr__("reg_bases", _unwrap_shape(self.reg_bases)) + super().__setattr__("lane_bases", _unwrap_shape(self.lane_bases)) + super().__setattr__("warp_bases", _unwrap_shape(self.warp_bases)) + super().__setattr__("block_bases", _unwrap_shape(self.block_bases)) + super().__setattr__("shape", _unwrap_shape(self.shape)) + + rank = len(self.shape) + + for basis in self.reg_bases: + assert len(basis) == rank + for basis in self.lane_bases: + assert len(basis) == rank + for basis in self.warp_bases: + assert len(basis) == rank + for basis in self.block_bases: + assert len(basis) == rank + + def _to_ir(self, builder): + return builder.get_distributed_linear_layout(self.reg_bases, self.lane_bases, self.warp_bases, self.block_bases, + self.shape) + + def mangle(self): + return f"DLL{self.reg_bases}_{self.lane_bases}_{self.warp_bases}_{self.block_bases}_{self.shape}DLL" + + def __hash__(self): + return hash(( + tuple(map(tuple, self.reg_bases)), + tuple(map(tuple, self.lane_bases)), + tuple(map(tuple, self.warp_bases)), + tuple(map(tuple, self.block_bases)), + tuple(self.shape), + )) + + +@dataclass(frozen=True) +class DotOperandLayout(DistributedLayout): + """ + Represents a layout for a dot operand. + + Args: + operand_index (int): 0 for LHS and 1 for RHS of the dot operation. + parent (DistributedLayout): The parent layout, representing the MMA. + k_width (int): Number of elements per 32-bits. + """ + operand_index: int + parent: DistributedLayout + k_width: int + + def __post_init__(self): + super().__setattr__("operand_index", _unwrap_if_constexpr(self.operand_index)) + super().__setattr__("parent", _unwrap_if_constexpr(self.parent)) + super().__setattr__("k_width", _unwrap_if_constexpr(self.k_width)) + + def _to_ir(self, builder): + return builder.get_dot_operand_layout(self.operand_index, self.parent._to_ir(builder), self.k_width) + + def mangle(self) -> str: + return f"DO{self.operand_index}_{self.parent.mangle()}_{self.k_width}DO" + + def __hash__(self): + return hash((self.operand_index, self.parent, self.k_width)) + + +@dataclass(frozen=True, eq=True) +class NVMMADistributedLayout(DistributedLayout): + """ + Represents a layout for NVIDIA MMA (tensor core) operations. + + Args: + version (List[int]): Version identifier for the MMA instruction. + warps_per_cta (List[int]): Number of warps per CTA. + instr_shape (List[int]): Instruction shape for MMA. + ctas_per_cga (Optional[List[int]]): CTAs per CGA grouping. + cta_split_num (Optional[List[int]]): Split factors for CTAs. + cta_order (Optional[List[int]]): CTA ordering. + """ + version: List[int] + warps_per_cta: List[int] + instr_shape: List[int] + ctas_per_cga: Optional[List[int]] = None + cta_split_num: Optional[List[int]] = None + cta_order: Optional[List[int]] = None + + def __post_init__(self): + super().__setattr__("version", _unwrap_if_constexpr(self.version)) + super().__setattr__("warps_per_cta", _unwrap_if_constexpr(self.warps_per_cta)) + super().__setattr__("instr_shape", _unwrap_if_constexpr(self.instr_shape)) + super().__setattr__("ctas_per_cga", _unwrap_if_constexpr(self.ctas_per_cga)) + super().__setattr__("cta_split_num", _unwrap_if_constexpr(self.cta_split_num)) + super().__setattr__("cta_order", _unwrap_if_constexpr(self.cta_order)) + + rank = len(self.warps_per_cta) + _realize_cta_layout(self, rank) + assert len(self.ctas_per_cga) == rank + assert len(self.cta_split_num) == rank + assert len(self.cta_order) == rank + + def _to_ir(self, builder): + return builder.get_mma_layout(self.version, self.warps_per_cta, self.ctas_per_cga, self.cta_split_num, + self.cta_order, self.instr_shape) + + def mangle(self) -> str: + return f"MMA_{self.version}_{self.warps_per_cta}_{self.instr_shape}_{self.ctas_per_cga}_{self.cta_split_num}_{self.cta_order}_MMA" + + def __hash__(self): + return hash((tuple(self.version), tuple(self.warps_per_cta), + tuple(self.instr_shape), tuple(self.ctas_per_cga) if self.ctas_per_cga else None, + tuple(self.cta_split_num) if self.cta_split_num else None, + tuple(self.cta_order) if self.cta_order else None)) + + +class SharedLayout: + """ + Base class for shared memory layouts in Gluon IR. + """ + + @property + def type(self): + return constexpr_type(self) + + +@constexpr_function +def _get_shape_per_cta(shape, cta_split_num): + shape_per_cta = shape + if cta_split_num is not None: + assert len(cta_split_num) == len(shape) + for dim in range(len(shape_per_cta)): + shape_per_cta[dim] /= cta_split_num[dim] + return shape_per_cta + + +@dataclass(frozen=True) +class NVMMASharedLayout(SharedLayout): + """ + Represents a layout for shared memory suitable for NVIDIA MMA operations. + + Args: + swizzle_byte_width (int): Width in bytes for swizzling. + element_bitwidth (int): Bitwidth of element type. + rank (int): Rank of the tensor. + transposed (bool): Whether the layout is transposed. + fp4_padded (bool): Whether FP4 padding is used. + ctas_per_cga (Optional[List[int]]): CTAs per CGA grouping. + cta_split_num (Optional[List[int]]): Split factors for CTAs. + cta_order (Optional[List[int]]): CTA ordering. + """ + swizzle_byte_width: int + element_bitwidth: int + rank: int + transposed: bool = False + fp4_padded: bool = False + ctas_per_cga: Optional[List[int]] = None + cta_split_num: Optional[List[int]] = None + cta_order: Optional[List[int]] = None + + def __post_init__(self): + super().__setattr__("swizzle_byte_width", _unwrap_if_constexpr(self.swizzle_byte_width)) + super().__setattr__("element_bitwidth", _unwrap_if_constexpr(self.element_bitwidth)) + super().__setattr__("rank", _unwrap_if_constexpr(self.rank)) + super().__setattr__("transposed", _unwrap_if_constexpr(self.transposed)) + super().__setattr__("fp4_padded", _unwrap_if_constexpr(self.fp4_padded)) + super().__setattr__("ctas_per_cga", _unwrap_if_constexpr(self.ctas_per_cga)) + super().__setattr__("cta_split_num", _unwrap_if_constexpr(self.cta_split_num)) + super().__setattr__("cta_order", _unwrap_if_constexpr(self.cta_order)) + + assert self.element_bitwidth in [8, 16, 32, 64] + assert self.swizzle_byte_width in [0, 32, 64, 128] + rank = self.rank + _realize_cta_layout(self, rank) + assert len(self.ctas_per_cga) == rank + assert len(self.cta_split_num) == rank + assert len(self.cta_order) == rank + + def _to_ir(self, builder): + return builder.get_nvmma_shared_layout( + self.swizzle_byte_width, + self.element_bitwidth, + self.transposed, + self.fp4_padded, + self.ctas_per_cga, + self.cta_split_num, + self.cta_order, + ) + + @staticmethod + @constexpr_function + def get_default_for(block_shape, dtype, transposed=False, fp4_padded=False, ctas_per_cga=None, cta_split_num=None, + cta_order=None): + """Returns an NVMMASharedLayout with default swizzling for a given shape. + + This picks the largest swizzle pattern compatible with the shape, which + allows emitting the fewest TMA or MMA messages. + """ + packing_factor = 2 if fp4_padded else 1 + shape_per_cta = _get_shape_per_cta(block_shape, cta_split_num) + rank = len(block_shape) + if transposed: + shape_per_cta = shape_per_cta[1:] + shape_per_cta[:1] + contig_dim_size = shape_per_cta[-1] * packing_factor + contig_dim_bytes = contig_dim_size * dtype.primitive_bitwidth // 8 + if contig_dim_bytes >= 128 and contig_dim_bytes % 128 == 0: + swizzle_byte_width = 128 + elif contig_dim_bytes >= 64 and contig_dim_bytes % 64 == 0: + swizzle_byte_width = 64 + elif contig_dim_bytes >= 32 and contig_dim_bytes % 32 == 0: + swizzle_byte_width = 32 + else: + swizzle_byte_width = 0 + + flatten_outer_dim = 1 + for size in shape_per_cta[:-1]: + flatten_outer_dim *= size + if len(block_shape) < 2 or flatten_outer_dim < 8: + swizzle_byte_width = 0 + + return NVMMASharedLayout( + swizzle_byte_width=swizzle_byte_width, + element_bitwidth=dtype.primitive_bitwidth, + rank=rank, + transposed=transposed, + fp4_padded=fp4_padded, + ctas_per_cga=ctas_per_cga, + cta_split_num=cta_split_num, + cta_order=cta_order, + ) + + def mangle(self) -> str: + return f"NVMMA_{self.swizzle_byte_width}_{self.element_bitwidth}_{self.transposed}_{self.fp4_padded}_NVMMA" + + def __hash__(self): + return hash((self.swizzle_byte_width, self.element_bitwidth, self.rank, self.transposed, self.fp4_padded, + tuple(self.ctas_per_cga) if self.ctas_per_cga else None, + tuple(self.cta_split_num) if self.cta_split_num else None, + tuple(self.cta_order) if self.cta_order else None)) + + +@dataclass(frozen=True, eq=True) +class SwizzledSharedLayout(SharedLayout): + """ + Represents a generic swizzled shared memory layout. + + Args: + vec (int): Vector width for swizzling. + per_phase (int): Elements per swizzle phase. + max_phase (int): Maximum number of swizzle phases. + order (List[int]): Dimension ordering for swizzling. + ctas_per_cga (Optional[List[int]]): CTAs per CGA grouping. + cta_split_num (Optional[List[int]]): Split factors for CTAs. + cta_order (Optional[List[int]]): CTA ordering. + """ + vec: int + per_phase: int + max_phase: int + order: List[int] + ctas_per_cga: Optional[List[int]] = None + cta_split_num: Optional[List[int]] = None + cta_order: Optional[List[int]] = None + + def __post_init__(self): + super().__setattr__("vec", _unwrap_if_constexpr(self.vec)) + super().__setattr__("per_phase", _unwrap_if_constexpr(self.per_phase)) + super().__setattr__("max_phase", _unwrap_if_constexpr(self.max_phase)) + super().__setattr__("order", _unwrap_if_constexpr(self.order)) + super().__setattr__("ctas_per_cga", _unwrap_if_constexpr(self.ctas_per_cga)) + super().__setattr__("cta_split_num", _unwrap_if_constexpr(self.cta_split_num)) + super().__setattr__("cta_order", _unwrap_if_constexpr(self.cta_order)) + + rank = len(self.order) + _realize_cta_layout(self, rank) + assert len(self.ctas_per_cga) == rank + assert len(self.cta_split_num) == rank + assert len(self.cta_order) == rank + + def _to_ir(self, builder): + return builder.get_swizzled_shared_layout( + self.vec, + self.per_phase, + self.max_phase, + self.order, + self.ctas_per_cga, + self.cta_split_num, + self.cta_order, + ) + + def mangle(self) -> str: + + def stringify(x): + if x is None: + return "" + return "_".join(map(str, x)) + + return f"SSS_{self.vec}_{self.per_phase}_{self.max_phase}_{stringify(self.order)}_{stringify(self.ctas_per_cga)}_{stringify(self.cta_split_num)}_{stringify(self.cta_order)}_SSS" + + def __hash__(self): + return hash((self.vec, self.per_phase, self.max_phase, + tuple(self.order), tuple(self.ctas_per_cga) if self.ctas_per_cga else None, + tuple(self.cta_split_num) if self.cta_split_num else None, + tuple(self.cta_order) if self.cta_order else None)) + + +@dataclass(frozen=True, eq=True) +class PaddedSharedLayout(SharedLayout): + """ + Represents a layout for the access to shared memory. Compared to SwizzledSharedLayout, + it uses padding to avoid shared memory bank conflicts. After every interval tensor elements, + the corresponding number of padding elements are inserted. + If a position corresponds to multiple intervals, the padding amounts are summed. + + In the following example of a tensor, + `eM` represents original elements in the and `pN` represents padded element. + + Before padding, the shared memory looks like: + [e0, e1, + e2, e3, + e4, e5, + e6, e7, + ...] + + After padding with interval-padding list [[2, 1], [4, 2]], + the shared memory will be + [e0, e1, p0, + e2, e3, p1, p2, p3, + e4, e5, p4, + e6, e7, p5, p6, p7, + ...] + + Args: + interval_padding_pairs (List[int]): List of [interval, padding] pair and both interval and padding must be powers of 2. + order (List[int]): Order of logical tensor dimensions; fastest-varying first. + ctas_per_cga (Optional[List[int]]): CTAs per CGA grouping. + cta_split_num (Optional[List[int]]): Split factors for CTAs. + cta_order (Optional[List[int]]): CTA ordering. + """ + interval_padding_pairs: List[List[int]] + order: List[int] + ctas_per_cga: Optional[List[int]] = None + cta_split_num: Optional[List[int]] = None + cta_order: Optional[List[int]] = None + + def __post_init__(self): + super().__setattr__("interval_padding_pairs", _unwrap_shape(self.interval_padding_pairs)) + super().__setattr__("order", _unwrap_if_constexpr(self.order)) + super().__setattr__("ctas_per_cga", _unwrap_if_constexpr(self.ctas_per_cga)) + super().__setattr__("cta_split_num", _unwrap_if_constexpr(self.cta_split_num)) + super().__setattr__("cta_order", _unwrap_if_constexpr(self.cta_order)) + + self.verify() + + def _to_ir(self, builder): + intervals, paddings = zip(*self.interval_padding_pairs) + return builder.get_padded_shared_layout(intervals, paddings, self.order, self.ctas_per_cga, self.cta_split_num, + self.cta_order) + + def mangle(self) -> str: + + def stringify(x): + if x is None: + return "" + return "_".join(map(str, x)) + + return f"PaddedShared_{stringify(self.interval_padding_pairs)}_{stringify(self.order)}_{stringify(self.ctas_per_cga)}_{stringify(self.cta_split_num)}_{stringify(self.cta_order)}_PaddedShared" + + def verify(self): + pairs = self.interval_padding_pairs + assert len(pairs) > 0, "PaddedSharedLayout interval_padding_pairs must have at least one interval-padding pair" + assert all(len(pair) == 2 for pair in pairs) + intervals, paddings = zip(*pairs) + + unique_intervals = list(set(intervals)) + assert len(unique_intervals) == len(intervals) + + is_power_of_2 = lambda n: n > 0 and n & (n - 1) == 0 + assert all(is_power_of_2(n) for n in intervals), "PaddedSharedLayout interval values must all be power of two" + assert all(is_power_of_2(n) for n in paddings), "PaddedSharedLayout padding values must all be power of two" + + rank = len(self.order) + assert rank > 0, "PaddedSharedLayout order must not be empty" + _realize_cta_layout(self, rank) + + assert len(self.ctas_per_cga) == rank + assert len(self.cta_split_num) == rank + assert len(self.cta_order) == rank + + def __hash__(self): + return hash((tuple(map(tuple, self.interval_padding_pairs)), + tuple(self.order), tuple(self.ctas_per_cga) if self.ctas_per_cga else None, + tuple(self.cta_split_num) if self.cta_split_num else None, + tuple(self.cta_order) if self.cta_order else None)) + + +# Python impl of LinearEncodingAttr::basesPerDim +def bases_per_dim(bases, rank, skip_broadcast=True): + result = [1] * rank + + if not bases: + return result + + non_zero_idx = None + + for basis in bases: + # Find the first non-zero index in the current basis + idx = next((i for i, v in enumerate(basis) if v != 0), None) + if idx is not None: + non_zero_idx = idx + result[idx] *= 2 + elif not skip_broadcast: + # If no non-zero found and we're not skipping broadcasts, use the last found non-zero index + assert non_zero_idx is not None + result[non_zero_idx] *= 2 + + return result + + +def warps_per_cta(layout, shape): + if isinstance(layout, DistributedLinearLayout): + return bases_per_dim(layout.warp_bases, len(shape)) + elif isinstance(layout, (SliceLayout, DotOperandLayout)): + return warps_per_cta(layout.parent, shape) + else: + return layout.warps_per_cta diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/_math.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/_math.py new file mode 100644 index 0000000000000000000000000000000000000000..b9c8d7605e0c25ef5b063027e320486c7c697d66 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/_math.py @@ -0,0 +1,20 @@ +import triton.language.math as tl_math +from ._core import builtin + +umulhi = builtin(tl_math.umulhi) +exp = builtin(tl_math.exp) +exp2 = builtin(tl_math.exp2) +fma = builtin(tl_math.fma) +log = builtin(tl_math.log) +log2 = builtin(tl_math.log2) +cos = builtin(tl_math.cos) +rsqrt = builtin(tl_math.rsqrt) +sin = builtin(tl_math.sin) +sqrt = builtin(tl_math.sqrt) +sqrt_rn = builtin(tl_math.sqrt_rn) +abs = builtin(tl_math.abs) +fdiv = builtin(tl_math.fdiv) +div_rn = builtin(tl_math.div_rn) +erf = builtin(tl_math.erf) +floor = builtin(tl_math.floor) +ceil = builtin(tl_math.ceil) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/_semantic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/_semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..3c97a9f8657ac5d1fe1366ca96c923931f0801ac --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/_semantic.py @@ -0,0 +1,380 @@ +from typing import Sequence, List, TypeVar, Tuple, Callable +import math +from triton.language.semantic import TritonSemantic +from . import _core as ttgl +from ._layouts import AutoLayout, DistributedLayout, SliceLayout +from triton._C.libtriton.gluon_ir import GluonOpBuilder +from triton.compiler.code_generator import flatten_values_to_ir, unflatten_ir_values + +TensorTy = TypeVar("TensorTy") + + +def _check(cond: bool, msg_fn: Callable[[], str], category=ValueError): + if not cond: + raise category(msg_fn()) + + +class GluonCallerContext: + + def __init__(self, num_warps: int): + self.num_warps = num_warps + + def mangle(self): + return f"_NW{self.num_warps}" + + def initialize_callee(self, fn, builder): + fn.set_attr("ttg.num-warps", builder.get_int32_attr(self.num_warps)) + + +class GluonSemantic(TritonSemantic[TensorTy]): + tensor = ttgl.tensor + lang = ttgl + + builder: GluonOpBuilder + + def __init__(self, builder: GluonOpBuilder): + self.builder = builder + + def _wrap_handle_infer_layout(self, handle, scalar_ty, shape): + if shape == []: + ty = scalar_ty + else: + ty = ttgl.distributed_type(scalar_ty, shape, self.builder.get_gluon_layout_from_tensor(handle)) + return self.tensor(handle, ty) + + def _wrap_tensor_infer_layout(self, tensor): + return self._wrap_handle_infer_layout(tensor.handle, tensor.type.scalar, tensor.shape) + + def _broadcast_shapes(self, lhs_shape: List[int], rhs_shape: List[int]): + if len(lhs_shape) != len(rhs_shape): + raise ValueError(f"Cannot broadcast, rank mismatch: {lhs_shape}, {rhs_shape}") + + ret_shape = [] + for i, left in enumerate(lhs_shape): + right = rhs_shape[i] + if left == 1: + ret_shape.append(right) + elif (right == 1) or (right == left): + ret_shape.append(left) + else: + raise ValueError("Cannot make_shape_compatible: incompatible dimensions " + "at index " + str(i) + ": " + str(left) + " and " + str(right)) + return ret_shape + + def expand_dims(self, input: TensorTy, axis: int) -> TensorTy: + dst_shape = [ttgl._unwrap_if_constexpr(x) for x in input.shape] + dst_shape.insert(axis, 1) + + if axis < 0: + axis += len(input.shape) + + _check(isinstance(input.type, ttgl.distributed_type), + lambda: f"expected expand_dims input to be a distributed_type but got: {input.type!r}") + layout = input.type.layout + _check(isinstance(layout, (SliceLayout, AutoLayout)), + lambda: f"expected expand_dims input to have a SliceLayout, but got: {layout}") + _check( + isinstance(layout, AutoLayout) or layout.dim == axis, + lambda: f"expected expand_dims input layout to be sliced in axis {axis} but got {layout.dim}") + + handle = self.builder.create_expand_dims(input.handle, axis) + return self._wrap_handle_infer_layout(handle, input.type.scalar, dst_shape) + + def join(self, a: TensorTy, b: TensorTy) -> TensorTy: + a, b = self.broadcast_impl_value(a, b) + _check(a.shape != [], "Cannot join scalars in gluon") + value = super().join(a, b) + return self._wrap_tensor_infer_layout(value) + + def split(self, a: TensorTy) -> Tuple[TensorTy, TensorTy]: + lhs, rhs = super().split(a) + return self._wrap_tensor_infer_layout(lhs), self._wrap_tensor_infer_layout(rhs) + + def permute(self, input: TensorTy, dims: Tuple[int]) -> TensorTy: + value = super().permute(input, dims) + return self._wrap_tensor_infer_layout(value) + + def broadcast_impl_shape(self, input: TensorTy, shape: Tuple[int]) -> TensorTy: + _check(isinstance(input.type, ttgl.distributed_type), + lambda: f"expected expand_dims input to be a distributed_type but got: {input.type!r}") + src_shape = input.type.get_block_shapes() + _check(len(src_shape) == len(shape), lambda: f"Cannot broadcast, rank mismatch: {src_shape}, {shape}") + if shape == src_shape: + return input + for i, item in enumerate(src_shape): + if shape[i] != item and item != 1: + raise ValueError(f"Cannot broadcast, the expanded size of the tensor ({shape[i]})" + f" must match the existing size ({item}) at non-singleton dimension" + f" {i}: {src_shape}, {shape}") + ret_ty = ttgl.distributed_type(input.type.scalar, shape, input.type.layout) + handle = self.builder.create_broadcast(input.handle, ret_ty.to_ir(self.builder)) + return self.tensor(handle, ret_ty) + + def broadcast_impl_value(self, lhs: TensorTy, rhs: TensorTy) -> TensorTy: + lhs_ty = lhs.type + rhs_ty = rhs.type + + if not lhs_ty.is_block() or not rhs_ty.is_block(): + return super().broadcast_impl_value(lhs, rhs) + + _check(isinstance(lhs_ty, ttgl.distributed_type), + lambda: f"expected broadcast left input to be a distributed_type but got: {lhs_ty!r}") + _check(isinstance(rhs_ty, ttgl.distributed_type), + lambda: f"expected broadcast right input to be a distributed_type but got: {rhs_ty!r}") + + lhs_shape = lhs_ty.get_block_shapes() + rhs_shape = rhs_ty.get_block_shapes() + ret_shape = self._broadcast_shapes(lhs_shape, rhs_shape) + + is_lhs_auto = isinstance(lhs_ty.layout, AutoLayout) + is_rhs_auto = isinstance(rhs_ty.layout, AutoLayout) + if is_lhs_auto and not is_rhs_auto: + lhs = self.set_auto_layout(lhs, rhs_ty.layout) + elif is_rhs_auto and not is_lhs_auto: + rhs = self.set_auto_layout(rhs, lhs_ty.layout) + elif lhs_ty.layout != rhs_ty.layout: + raise ValueError(f"Layout mismatch in broadcast: {lhs_ty.layout} vs {rhs_ty.layout}") + + lhs = self.broadcast_impl_shape(lhs, ret_shape) + rhs = self.broadcast_impl_shape(rhs, ret_shape) + return lhs, rhs + + def arange(self, start, end, layout): + shape = [end - start] + if layout is None: + layout = AutoLayout() + ret_ty = ttgl.distributed_type(ttgl.int32, shape, layout) + return super().arange(start, end, ret_ty=ret_ty) + + def reshape(self, input: TensorTy, dst_shape: List[int], can_reorder: bool): + _check(not can_reorder, "can_reorder is not supported in gluon") + value = super().reshape(input, dst_shape, can_reorder) + return self._wrap_tensor_infer_layout(value) + + def splat(self, value, shape, layout): + ret_ty = ttgl.distributed_type(value.dtype, shape, layout) + handle = self.builder.create_splat(ret_ty.to_ir(self.builder), value.handle) + return ttgl.tensor(handle, ret_ty) + + def full(self, shape, value, dtype, layout): + scalar = self.make_scalar(value, dtype) + if layout is None: + layout = AutoLayout() + return self.splat(scalar, shape, layout) + + def convert_layout(self, value, layout, assert_trivial=False): + ty = value.type + _check(isinstance(ty, ttgl.distributed_type), + lambda: f"expected convert_layout input to be a distributed_type but got: {ty!r}") + ret_ty = ttgl.distributed_type(ty.element_ty, ty.shape, layout) + ret_ty_ir = ret_ty.to_ir(self.builder) + if assert_trivial and not self.builder.is_convert_layout_trivial(ret_ty_ir, value.handle): + raise TypeError(f"layout conversion from {ty.layout} to {layout} is not trivial") + handle = self.builder.create_convert_layout(ret_ty_ir, value.handle) + return ttgl.tensor(handle, ret_ty) + + def allocate_shared(self, element_ty, shape, layout, value): + ty = ttgl.shared_memory_descriptor_type(element_ty, shape, layout, shape) + if value is not None: + handle = self.builder.create_local_alloc(ty.to_ir(self.builder), value.handle) + else: + handle = self.builder.create_local_alloc(ty.to_ir(self.builder)) + return ttgl.shared_memory_descriptor(handle, element_ty, shape, layout, shape) + + def shared_load(self, mem_desc, layout): + ret_ty = ttgl.distributed_type(mem_desc.dtype, mem_desc.shape, layout) + handle = self.builder.create_local_load(ret_ty.to_ir(self.builder), mem_desc.handle) + return ttgl.tensor(handle, ret_ty) + + def shared_store(self, mem_desc, value): + assert value.shape == mem_desc.shape, f"source shape {value.shape} and destination shape {mem_desc.shape} must match" + assert value.dtype == mem_desc.dtype, f"source dtype {value.dtype} and destination dtype {mem_desc.dtype} must match" + self.builder.create_local_store(mem_desc.handle, value.handle) + + def shared_dealloc(self, mem_desc): + self.builder.create_local_dealloc(mem_desc.handle) + + def set_auto_layout(self, value, layout): + src_ty = value.type + assert isinstance(layout, + DistributedLayout), f"set_auto_layout must set to a distributed layout but got {layout}" + assert isinstance(src_ty.layout, + AutoLayout), f"set_auto_layout input must have auto layout but got {value.type.layout}" + handle = self.builder.create_set_auto_layout(layout._to_ir(self.builder), value.handle) + res_ty = ttgl.distributed_type(src_ty.element_ty, src_ty.shape, layout) + return self.tensor(handle, res_ty) + + def memdesc_slice(self, mem_desc, start, length, dim): + offsets = [0] * mem_desc.rank + offsets[dim] = start + shape = list(mem_desc.shape) + shape[dim] = length + layout = mem_desc.layout + ty = ttgl.shared_memory_descriptor_type(mem_desc.dtype, shape, layout, mem_desc.type.alloc_shape) + builder = self.builder + handle = builder.create_memdesc_subslice(ty.to_ir(builder), mem_desc.handle, offsets) + return ttgl.shared_memory_descriptor(handle, **ty.__dict__) + + def memdesc_index(self, mem_desc, index): + shape = mem_desc.shape[1:] + index = self.to_tensor(index).handle + layout = mem_desc.layout + ty = ttgl.shared_memory_descriptor_type(mem_desc.dtype, shape, layout, mem_desc.type.alloc_shape) + builder = self.builder + handle = builder.create_memdesc_index(ty.to_ir(builder), mem_desc.handle, index) + return ttgl.shared_memory_descriptor(handle, **ty.__dict__) + + def memdesc_trans(self, mem_desc, order): + assert len(order) == len( + mem_desc.shape), f"source rank ({mem_desc.rank}) and order length ({len(order)}) must match" + + shape = [mem_desc.shape[i] for i in order] + alloc_shape = mem_desc.type.alloc_shape + new_alloc_shape = alloc_shape[:len(alloc_shape) - mem_desc.rank] + new_alloc_shape += [alloc_shape[len(alloc_shape) - mem_desc.rank:][i] for i in order] + + handle = self.builder.create_memdesc_trans(mem_desc.handle, order) + layout = self.builder.get_gluon_layout_from_memdesc(handle) + return ttgl.shared_memory_descriptor(handle, element_ty=mem_desc.dtype, shape=shape, + alloc_shape=new_alloc_shape, layout=layout) + + def memdesc_reshape(self, mem_desc, shape): + _check( + math.prod(shape) == math.prod(mem_desc.shape), + lambda: (f"memdesc_reshape total elements mismatch: " + f"{mem_desc.shape} -> {shape}"), + ) + + handle = self.builder.create_memdesc_reshape(mem_desc.handle, shape) + layout = self.builder.get_gluon_layout_from_memdesc(handle) + alloc_shape = mem_desc.type.alloc_shape + prefix_len = len(alloc_shape) - mem_desc.rank + new_alloc_shape = alloc_shape[:prefix_len] + list(shape) + + return ttgl.shared_memory_descriptor( + handle, + element_ty=mem_desc.dtype, + shape=shape, + alloc_shape=new_alloc_shape, + layout=layout, + ) + + def memdesc_reinterpret(self, mem_desc, dtype, shape, layout): + ty = ttgl.shared_memory_descriptor_type(dtype, shape, layout, shape) + handle = self.builder.create_memdesc_reinterpret(ty.to_ir(self.builder), mem_desc.handle) + return ttgl.shared_memory_descriptor(handle, **ty.__dict__) + + def wrap_tensor(self, x, scalar_ty, ret_shape, layout): + if ret_shape: + res_ty = ttgl.distributed_type(scalar_ty, ret_shape, layout) + else: + res_ty = scalar_ty + return self.tensor(x, res_ty) + + @staticmethod + def _check_same_layout(xs): + for x in xs: + _check(isinstance(x.type, ttgl.distributed_type), lambda: f"expected distributed_type but got: {x.type!r}") + layouts = [x.type.layout for x in xs] + l0 = layouts[0] + _check(all(l == l0 for l in layouts[1:]), + lambda: f"Expected inputs to have matching layouts, but got: {layouts}") + + def associative_scan(self, inputs: Sequence[TensorTy], axis: int, region_builder_fn, + reverse: bool) -> Tuple[TensorTy, ...]: + shape = inputs[0].type.shape + rank = len(shape) + + assert -rank <= axis < rank, f"scan axis {axis} must be < inputs rank ({rank})" + + if axis < 0: + axis += rank + + for t in inputs: + assert t.type.shape == shape, "all scan inputs must have the same shape" + + scan_op = self.builder.create_scan([t.handle for t in inputs], axis, reverse) + region_builder_fn(scan_op) + assert scan_op.verify() + + return tuple( + self._wrap_handle_infer_layout(scan_op.get_result(i), inputs[i].type.scalar, shape) + for i in range(len(inputs))) + + def reduction(self, inputs: Sequence[TensorTy], axis: int, region_builder_fn) -> Tuple[TensorTy, ...]: + _check(axis is not None, lambda: "All-reduce is not yet implemented in gluon") + # get result shape + shape = inputs[0].type.shape + rank = len(shape) + _check(0 <= axis < rank, lambda: f"expected reduction axis to be in the range [0, {rank}) but got {axis}") + self._check_same_layout(inputs) + ret_shape = [s for i, s in enumerate(shape) if i != axis] + assert all(t.type.shape == shape for t in inputs), "all reduction inputs must have the same shape" + + reduce_op = self.builder.create_reduce([t.handle for t in inputs], axis) + region_builder_fn(reduce_op) + assert reduce_op.verify() + + return tuple( + self._wrap_handle_infer_layout(reduce_op.get_result(i), inputs[i].type.scalar, ret_shape) + for i in range(len(inputs))) + + def histogram(self, input: TensorTy, num_bins: int, mask: TensorTy, layout) -> TensorTy: + _check(len(input.shape) == 1, lambda: "histogram only supports 1D input") + _check(input.dtype.is_int(), lambda: "histogram only supports integer input") + _check(layout is not None, lambda: "histogram requires a destination layout") + if mask is not None: + mask, input = self.broadcast_impl_value(mask, input) + _check(mask.type.scalar.is_bool(), lambda: "Mask must have boolean scalar type") + mask = mask.handle + layout_attr = layout._to_ir(self.builder) + handle = self.builder.create_histogram(input.handle, num_bins, mask, layout_attr) + return self.wrap_tensor(handle, ttgl.int32, [num_bins], layout) + + def warp_specialize(self, default_args, default_partition, worker_args, worker_partitions, + worker_num_warps: Sequence[int], worker_num_regs: Sequence[int], generator): + num_partitions = len(worker_partitions) + assert num_partitions == len( + worker_num_warps + ), f"warp specialize got {num_partitions} partitions but {len(worker_num_warps)} warp counts" + assert num_partitions == len( + worker_num_regs + ), f"warp specialize got {num_partitions} partitions but {len(worker_num_regs)} register counts" + + builder = self.builder + insert_pt = builder.get_insertion_point() + + # Emit the default partition to get the result types. + default_block = builder.new_block() + builder.set_insertion_point_to_start(default_block) + default_results = generator.call_JitFunction(default_partition, default_args, kwargs={}) + mlir_results = [] + if default_results is not None: + mlir_results = flatten_values_to_ir(default_results) + builder.create_warp_yield(mlir_results) + result_types = [r.get_type() for r in mlir_results] + + # Create the warp specialize op. + builder.restore_insertion_point(insert_pt) + mlir_args = flatten_values_to_ir(worker_args) + ws_op = builder.create_warp_specialize(result_types, mlir_args, worker_num_warps) + ws_op.get_default_region().push_back(default_block) + ws_op.set_requested_registers(worker_num_regs) + + # Emit the partition regions. + builder.create_block_with_parent(ws_op.get_partition_op_holder(), []) + partitions_op = builder.create_warp_specialize_partitions(num_partitions) + arg_types = [arg.get_type() for arg in mlir_args] + for i in range(num_partitions): + caller_context = GluonCallerContext(num_warps=worker_num_warps[i]) + block = builder.create_block_with_parent(partitions_op.get_region(i), arg_types) + block_args = [block.get_argument(j) for j in range(len(mlir_args))] + block_args = unflatten_ir_values(block_args, [arg.type for arg in worker_args]) + generator.call_JitFunction(worker_partitions[i], block_args, kwargs={}, caller_context=caller_context) + builder.create_warp_return() + + builder.set_insertion_point_after(ws_op.get_operation()) + mlir_results = [ws_op.get_result(i) for i in range(len(result_types))] + if default_results is None: + return + return tuple(unflatten_ir_values(mlir_results, [r.type for r in default_results])) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/_standard.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/_standard.py new file mode 100644 index 0000000000000000000000000000000000000000..e2fb41fd29a10dc8562df95132cca9181783dbaf --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/_standard.py @@ -0,0 +1,80 @@ +from typing import TypeVar +from triton.runtime.jit import JITFunction +import triton.language.standard as tl_standard +from .._runtime import GluonJITFunction, jit +from triton import knobs +from . import _core as ttgl + +T = TypeVar("T") + + +def _import_from_triton(fn: JITFunction[T]) -> GluonJITFunction[T]: + assert knobs.runtime.interpret or isinstance(fn, JITFunction) + # Wrap the function and preserve its original docstring + gluon_fn = jit(fn.fn) + gluon_fn.__doc__ = fn.__doc__ + return gluon_fn + + +cdiv = _import_from_triton(tl_standard.cdiv) +sum = _import_from_triton(tl_standard.sum) +max = _import_from_triton(tl_standard.max) +min = _import_from_triton(tl_standard.min) +reduce_or = _import_from_triton(tl_standard.reduce_or) +xor_sum = _import_from_triton(tl_standard.xor_sum) + + +@jit +def zeros(shape, dtype, layout=None): + """ + Create a tensor filled with zeros. + + Args: + shape (Sequence[int]): The shape of the tensor. + dtype (dtype): The data type for the tensor. + layout (Optional[DistributedLayout]): The distributed layout of the tensor, defaults to AutoLayout(). + + Returns: + tensor: A tensor where every element is zero. + """ + return ttgl.full(shape, 0, dtype, layout) + + +@jit +def full_like(input, value, shape=None, dtype=None, layout=None): + """ + Create a tensor with the same properties as a given tensor, filled with a specified value. + + Args: + input (tensor): Reference tensor to infer default shape, dtype, and layout. + value (int or float): The fill value. + shape (Sequence[int], optional): Target shape. Defaults to input.shape. + dtype (dtype, optional): Target data type. Defaults to input.dtype. + layout (DistributedLayout, optional): Target layout. Defaults to input.layout. + + Returns: + tensor: A tensor where every element equals value. + """ + return ttgl.full( + input.shape if shape is None else shape, + value, + input.dtype if dtype is None else dtype, + input.type.layout if layout is None else layout, + ) + + +@jit +def zeros_like(input, shape=None, dtype=None, layout=None): + """ + Create a tensor with the same properties as a given tensor, filled with zeros. + + Args: + input (tensor): Reference tensor to infer default shape, dtype, and layout. + shape (Sequence[int], optional): Target shape. Defaults to input.shape. + dtype (dtype, optional): Target data type. Defaults to input.dtype. + layout (DistributedLayout, optional): Target layout. Defaults to input.layout. + + Returns: + tensor: A tensor where every element is zero. + """ + return full_like(input, 0, shape=shape, dtype=dtype, layout=layout) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2802c4951c202118a9491044ded47d53f98e2dab --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/__init__.py @@ -0,0 +1,4 @@ +from ._layouts import AMDMFMALayout +from . import cdna3, cdna4 + +__all__ = ["AMDMFMALayout", "cdna3", "cdna4"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/_layouts.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/_layouts.py new file mode 100644 index 0000000000000000000000000000000000000000..67da13659ba9b1e52f6e8c27525741115bd2fd2d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/_layouts.py @@ -0,0 +1,96 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import List, Optional +from triton.language.core import _unwrap_if_constexpr + +from triton.experimental.gluon.language._layouts import _realize_cta_layout, DistributedLayout +from triton.experimental.gluon import language as ttgl + +__all__ = [ + "AMDMFMALayout", +] + + +@dataclass(frozen=True) +class AMDMFMALayout(DistributedLayout): + """ + Represents a layout for AMD MFMA (matrix core) operations. + + Args: + version (int): Major and minor identifier for the MFMA instruction. + instr_shape: (M, N) dimension for the instrinsic shape. + transposed (bool): indicates the result tensor is transposed so that each thread holds consecutive elements in the same row instead of column, which is good for chained dot and global write. + warps_per_cta (List[int]): Number of warps per CTA. + elem_type Optional(ttgl.dtype): Supported types are int32, fp32 and fp64. Default is fp32. + tiles_per_warp Optional(List[int]): Number of tiles per WARP. For mfma layout, if missing, use the default where we have unit tile size on all dimensions. + ctas_per_cga (Optional[List[int]]): CTAs per CGA grouping. + cta_split_num (Optional[List[int]]): Split factors for CTAs. + cta_order (Optional[List[int]]): CTA ordering. + """ + version: int + instr_shape: List[int] + transposed: bool + warps_per_cta: List[int] + elem_type: ttgl.dtype = ttgl.float32 + tiles_per_warp: Optional[List[int]] = None + ctas_per_cga: Optional[List[int]] = None + cta_split_num: Optional[List[int]] = None + cta_order: Optional[List[int]] = None + + def __post_init__(self): + super().__setattr__("version", _unwrap_if_constexpr(self.version)) + super().__setattr__("instr_shape", _unwrap_if_constexpr(self.instr_shape)) + super().__setattr__("transposed", _unwrap_if_constexpr(self.transposed)) + super().__setattr__("warps_per_cta", _unwrap_if_constexpr(self.warps_per_cta)) + super().__setattr__("tiles_per_warp", _unwrap_if_constexpr(self.tiles_per_warp)) + super().__setattr__("elem_type", _unwrap_if_constexpr(self.elem_type)) + super().__setattr__("ctas_per_cga", _unwrap_if_constexpr(self.ctas_per_cga)) + super().__setattr__("cta_split_num", _unwrap_if_constexpr(self.cta_split_num)) + super().__setattr__("cta_order", _unwrap_if_constexpr(self.cta_order)) + + if self.tiles_per_warp is None: + object.__setattr__(self, "tiles_per_warp", [1] * len(self.warps_per_cta)) + + self.verify() + + def _to_ir(self, builder): + type = self.elem_type.to_ir(builder) + return builder.get_amd_mfma_layout(self.version, self.instr_shape, self.transposed, self.warps_per_cta, type, + self.tiles_per_warp, self.ctas_per_cga, self.cta_split_num, self.cta_order) + + def mangle(self) -> str: + + def stringify(x): + if x is None: + return "" + return "_".join(map(str, x)) + + return f"MFMA_{self.version}_{stringify(self.instr_shape)}_{self.transposed}_{stringify(self.warps_per_cta)}_{stringify(self.tiles_per_warp)}_{self.elem_type}_{stringify(self.ctas_per_cga)}_{stringify(self.cta_split_num)}_{stringify(self.cta_order)}_MFMA" + + def verify(self): + assert self.version >= 1 and self.version <= 4, "version must be in the [1, 4] range" + valid_shapes = [[32, 32], [16, 16], [64, 4], [4, 64]] + assert self.instr_shape in valid_shapes, "invalid intrinsic shape; accepted shapes are " + str(valid_shapes) + + assert self.elem_type.is_fp32() or self.elem_type.is_fp64() \ + or self.elem_type.is_int32() , "element type must be float32, float64, or int32" + + rank = len(self.warps_per_cta) + _realize_cta_layout(self, rank) + assert len(self.ctas_per_cga) == rank + assert len(self.cta_split_num) == rank + assert len(self.cta_order) == rank + + def __hash__(self): + return hash(( + self.version, + tuple(self.instr_shape), + self.transposed, + tuple(self.warps_per_cta), + self.elem_type, + tuple(self.tiles_per_warp) if self.tiles_per_warp else None, + tuple(self.ctas_per_cga) if self.ctas_per_cga else None, + tuple(self.cta_split_num) if self.cta_split_num else None, + tuple(self.cta_order) if self.cta_order else None, + )) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna3/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..460fffadd1ee5695de5e3a7aa363c3d3c6fbc999 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna3/__init__.py @@ -0,0 +1,100 @@ +from __future__ import annotations +from typing import TYPE_CHECKING + +from triton import knobs +from triton.experimental.gluon.language import _core as ttgl +from triton._C.libtriton import ir +from ..._core import builtin, _unwrap_if_constexpr + +if TYPE_CHECKING: + from ..._semantic import GluonSemantic + +__all__ = ["buffer_load", "buffer_store", "mfma"] + + +def _verify_buffer_ops(ptr, offsets, mask=None, other=None): + assert ptr.type.is_ptr(), "ptr must be a scalar pointer type" + + assert isinstance(offsets.type, ttgl.distributed_type), "expected offsets type to be a distributed_type" + assert offsets.dtype.is_int32() or offsets.dtype.is_uint32(), "offsets element type must be int32 or uint32" + + element_type = ptr.type.scalar.element_ty + + if other is not None: + assert mask is not None, "when other is not None, mask should not be None" + assert other.dtype == element_type, "other must have the same data type as ptr scalar type" + + +@builtin +def buffer_load(ptr, offsets, mask=None, other=None, cache=None, _semantic=None): + """ + AMD buffer load from global memory via a scalar base pointer and a tensor of + offsets instead of a tensor of pointers. This operation will load data + directly into registers. + + Args: + ptr (pointer to scalar): Global memory scalar base pointer to load from. + offsets (tensor): Offsets tensor for the load operation. + mask (tensor, optional): Mask tensor for predicated loads. Defaults to None. + other (tensor, optional): Tensor providing default values for masked elements. Defaults to None. + cache_modifier (str): Cache modifier specifier. Defaults to "". + """ + _verify_buffer_ops(ptr, offsets, mask, other) + + mask = _unwrap_if_constexpr(mask) + if mask is not None: + offsets, mask = _semantic.broadcast_impl_value(offsets, mask) + + other = _unwrap_if_constexpr(other) + if other is not None: + offsets, other = _semantic.broadcast_impl_value(offsets, other) + + other = other.handle if other is not None else ir.value() + mask = mask.handle if mask is not None else ir.value() + cache_modifier = _semantic._str_to_load_cache_modifier(cache) if cache is not None else ir.CACHE_MODIFIER.NONE + + ret_ty = offsets.type.with_element_ty(ptr.type.scalar.element_ty) + builder = _semantic.builder + handle = builder.create_buffer_load(ret_ty.to_ir(builder), ptr.handle, offsets.handle, mask, other, cache_modifier) + return ttgl.tensor(handle, ret_ty) + + +@builtin +def buffer_store(stored_value, ptr, offsets, mask=None, cache=None, _semantic: GluonSemantic = None): + """ + AMD buffer store a tensor directly to global memory via a scalar base pointer and a tensor of + offsets instead of a tensor of pointers. + Args: + stored_value (tensor to be stored): The tensor to be stored to global memory. + ptr (pointer to scalar): Global memory scalar base pointer to store to. + offsets (tensor): Offsets tensor for the store operation. + mask (tensor, optional): Mask tensor for predicated store. Defaults to None. + cache_modifier (str): Cache modifier specifier. Defaults to "". + """ + _verify_buffer_ops(ptr, offsets, mask) + + if mask is not None: + offsets, mask = _semantic.broadcast_impl_value(offsets, mask) + + mask = mask.handle if mask is not None else ir.value() + cache_modifier = _semantic._str_to_store_cache_modifier(cache) if cache is not None else ir.CACHE_MODIFIER.NONE + + _semantic.builder.create_buffer_store(stored_value.handle, ptr.handle, offsets.handle, mask, cache_modifier) + + +@builtin +def mfma(a, b, acc, _semantic: GluonSemantic = None): + """ + Computes matrix-multiplication of a * b + acc using AMD native matrix core units. + Args: + a (tensor): The first operand of mfma. + b (tensor): The second operand of mfma. + acc (tensor): The accumulator tensor. + """ + assert acc is not None, "acc is required" + ret_type = acc.type + acc = ttgl._unwrap_if_constexpr(acc) + + handle = _semantic.dot(a, b, acc, input_precision=knobs.language.fp32_default, max_num_imprecise_acc=None, + out_dtype=acc.dtype).handle + return ttgl.tensor(handle, ret_type) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna4/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna4/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..39c360692d5d8f80dc612c177b7ac7804ba2c7db --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna4/__init__.py @@ -0,0 +1,48 @@ +from triton.experimental.gluon.language import _core as ttgl +from ..._core import builtin, float32 +from ..._layouts import DotOperandLayout +from .._layouts import AMDMFMALayout +from ..cdna3 import * # NOQA: F403 +from ..cdna3 import __all__ as __cdna3_all +from . import async_copy + +__all__ = [*__cdna3_all, "async_copy", "mfma_scaled"] + + +@builtin +def mfma_scaled(a, a_scale, a_format, b, b_scale, b_format, acc, _semantic=None): + """ + AMD Scaled MFMA operation. + + ``` + c = a * a_scale @ b * b_scale + acc + ``` + + `a` and `b` use microscaling formats described in + "OCP Microscaling Formats (MX) Specification": + https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf. + Currently supported only on CDNA4 hardware. + + Args: + a (tensor): The operand A to be multiplied. + a_scale (tensor): Scale factor for operand A. + a_format (str): Format of the operand A. Available formats: `e2m1`, `e4m3`, `e5m2`. + b (tensor): The operand B to be multiplied. + b_scale (tensor): Scale factor for operand B. Available formats: `e2m1`, `e4m3`, `e5m2`. + b_format (str): Format of the operand B. + acc (tensor): Accumulator tensor. + """ + layout = acc.type.layout + assert isinstance(layout, AMDMFMALayout), "Expected layout to be an instance of AMDMFMALayout" + assert (isinstance(a.type.layout, DotOperandLayout) and a.type.layout.parent== layout), \ + "Expected lhs layout to be a DotOperandLayout with parent matching MFMA layout" + assert (isinstance(b.type.layout, DotOperandLayout) and b.type.layout.parent == layout), \ + "Expected rhs layout to be a DotOperandLayout with parent matching MFMA layout" + + assert a_format.value in {"e2m1", "e4m3", "e5m2"}, f"Unsupported lhs_format: {a_format.value}" + assert b_format.value in {"e2m1", "e4m3", "e5m2"}, f"Unsupported rhs_format: {b_format.value}" + + tensor = _semantic.dot_scaled(a, a_scale, a_format, b, b_scale, b_format, acc, False, True, True, float32) + + ret_ty = ttgl.distributed_type(tensor.dtype, tensor.shape, layout) + return ttgl.tensor(tensor.handle, ret_ty) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna4/async_copy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna4/async_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..51a35574551a8631bff062c309182388fa36be68 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna4/async_copy.py @@ -0,0 +1,151 @@ +from ..._core import ir, builtin, _unwrap_if_constexpr +from ..._semantic import _check +from ..._layouts import BlockedLayout, SliceLayout +from ..cdna3 import _verify_buffer_ops + +__all__ = [ + "global_load_to_shared", + "buffer_load_to_shared", + "async_wait", + "load_shared_relaxed", +] + + +@builtin +def global_load_to_shared(dest, ptr, mask=None, other=None, cache_modifier="", _semantic=None): + """ + AMD global load to shared operation. This operation loads data directly + from global memory to shared memory without going through registers. It + happens asynchronously and requires a subsequent `async_wait` to ensure the + data is available in shared memory. + Compared to `buffer_load_to_shared`, it requires a tensor pointer which + supports 64-bit indexing range for each thread in a block, which gives more + flexibility, but at the cost of higher register pressure and no hardware + out-of-bound masking support. Prefer to use `buffer_load_to_shared` when + possible for better performance. + + The underlying hardware instruction uses separate registers for global + memory address for each thread but the same register for local memory + address for the whole warp. Therefore, while using this operation + the following conditions must be met or lowering to LLVM will fail: + + - For the `ptr` layout, size per thread * bits per element must be 128 or 32. + To get ideal performance, it is recommended to use 128 bits per element. + - Writes to `dest` must be coalesced. + - If `dest` is swizzled, it only can be swizzled within warp boundary. + + Args: + dest (shared_memory_descriptor): Destination shared memory descriptor. + ptr (pointer tensor): Tensor of pointers to global memory to load from. + mask (tensor, optional): Mask tensor for predicated loads. Defaults to None. + other (tensor, optional): Tensor providing default values for masked elements. Defaults to None. + cache_modifier (str): Cache modifier specifier. Defaults to "". + """ + _check(ptr.type.is_block(), lambda: "expected ptr to be a tensor") + _check(isinstance(ptr.type.layout, (BlockedLayout, SliceLayout)), + lambda: "expected ptr type layout to be BlockedLayout or SliceLayout") + _check( + dest.shape == ptr.shape, lambda: + f"expected dest shape to match pointer shape but got dest.shape = {dest.shape}, pointer.shape = {ptr.shape}") + + mask = _unwrap_if_constexpr(mask) + if mask is not None: + ptr, mask = _semantic.broadcast_impl_value(ptr, mask) + other = _unwrap_if_constexpr(other) + if other is not None: + ptr, other = _semantic.broadcast_impl_value(ptr, other) + + cache_modifier = _semantic._str_to_load_cache_modifier(cache_modifier) + mask_handle = mask.handle if mask is not None else ir.value() + other_handle = other.handle if other is not None else ir.value() + _semantic.builder.create_async_copy_global_to_local(dest.handle, ptr.handle, mask_handle, other_handle, + cache_modifier, ir.EVICTION_POLICY.NORMAL, False) + + +@builtin +def buffer_load_to_shared(dest, ptr, offsets, mask=None, other=None, cache_modifier="", _semantic=None): + """ + AMD buffer load to shared operation. Buffer load is similar to global load + but it accesses global memory via a scalar base pointer and a tensor of + 32-bit offsets instead of a tensor of pointers. This operation loads data + directly from global memory to shared memory without going through + registers. It happens asynchronously and requires a subsequent `async_wait` + to ensure the data is available in shared memory. + Compared to `global_load_to_shared`, it has better performance and also + supports hardware out-of-bound masking. But it strictly requires a + 32-bit offset instead of a 64-bit tensor pointer. + + The underlying hardware instruction uses separate registers for global + memory address for each thread but the same register for local memory + address for the whole warp. Therefore, while using this operation + the following conditions must be met or lowering to LLVM will fail: + + - For the `offsets` layout, size per thread * bits per element must be 128 or 32. + To get ideal performance, it is recommended to use 128 bits per element. + - Writes to `dest` must be coalesced. + - If `dest` is swizzled, it only can be swizzled within warp boundary. + + Args: + dest (shared_memory_descriptor): Destination shared memory descriptor. + ptr (pointer to scalar): Global memory scalar base pointer to load from. + offsets (tensor): Offsets tensor for the load operation. + mask (tensor, optional): Mask tensor for predicated loads. Defaults to None. + other (tensor, optional): Tensor providing default values for masked elements. Defaults to None. + cache_modifier (str): Cache modifier specifier. Defaults to "". + """ + _check(isinstance(offsets.type.layout, (BlockedLayout, SliceLayout)), + lambda: "expected offsets type layout to be BlockedLayout or SliceLayout") + _verify_buffer_ops(ptr, offsets, mask, other) + + mask = _unwrap_if_constexpr(mask) + if mask is not None: + offsets, mask = _semantic.broadcast_impl_value(offsets, mask) + other = _unwrap_if_constexpr(other) + if other is not None: + offsets, other = _semantic.broadcast_impl_value(offsets, other) + + mask = mask.handle if mask is not None else ir.value() + other = other.handle if other is not None else ir.value() + stride = ir.value() + cache_modifier = _semantic._str_to_load_cache_modifier(cache_modifier) + + _semantic.builder.create_buffer_load_to_local(dest.handle, ptr.handle, offsets.handle, mask, other, stride, + cache_modifier) + + +@builtin +def async_wait(num_outstanding=0, _semantic=None): + """ + Wait for outstanding memory operations, this includes normal load like + `load` and `buffer_load`, as well as direct load to shared memory + like `global_load_to_shared` and `buffer_load_to_shared`. + It will block until the number of outstanding memory operations is less than + or equal to `num_outstanding`. + + Args: + num_outstanding (int): The number of outstanding operations to wait for. Defaults to 0. + """ + num_outstanding = _unwrap_if_constexpr(num_outstanding) + _semantic.builder.create_async_wait_group(num_outstanding) + + +@builtin +def load_shared_relaxed(smem, layout, _semantic=None): + """ + Load a tensor from shared memory with extra hints for the underlying + compiler to avoid emitting unnecessary waits before loading from the target + shared memory. + + Args: + smem (shared_memory_descriptor): Shared memory descriptor to load from. + layout (DistributedLayout): The destination layout of the tensor. + + Returns: + tensor: A Gluon tensor containing the loaded data. + """ + SYNCED_VIA_WAIT_ATTR_NAME = "ttg.amdgpu.syncedViaAsyncWait" + + layout = _unwrap_if_constexpr(layout) + ret = _semantic.shared_load(smem, layout) + ret.handle.set_attr(SYNCED_VIA_WAIT_ATTR_NAME, _semantic.builder.get_bool_attr(True)) + return ret diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/extra/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/extra/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2091e0b7e2afcd9fb914745dc64c35351d487f92 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/extra/__init__.py @@ -0,0 +1,3 @@ +from triton.language.extra import libdevice + +__all__ = ["libdevice"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3ecf36d3b950635111e792c62a48497ee621ae02 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/__init__.py @@ -0,0 +1,4 @@ +from . import blackwell +from . import hopper + +__all__ = ["blackwell", "hopper"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ac5071411fbdac8633649b420c75f6c0069d993f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/__init__.py @@ -0,0 +1,3 @@ +from . import async_copy, mbarrier + +__all__ = ["async_copy", "mbarrier"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/async_copy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/async_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..b6752402bfda1f308724f9fc5a11d2ce2d010fa7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/async_copy.py @@ -0,0 +1,74 @@ +from ..._semantic import _check +from ..._core import _unwrap_if_constexpr, builtin +from triton._C.libtriton import ir + +__all__ = [ + "async_copy_global_to_shared", + "mbarrier_arrive", + "commit_group", + "wait_group", +] + + +@builtin +def async_copy_global_to_shared(smem, pointer, mask=None, cache_modifier="", eviction_policy="", volatile=False, + _semantic=None): + """ + Asynchronously copy elements from global memory to shared memory. + + Args: + smem (shared_memory_descriptor): Destination shared memory descriptor. + pointer (tensor): Source pointer tensor. + mask (tensor, optional): Mask tensor for predicated loads. Defaults to None. + cache_modifier (str): Cache modifier specifier. Defaults to "". + eviction_policy (str): Eviction policy specifier. Defaults to "". + volatile (bool): Whether the load is volatile. Defaults to False. + """ + mask = _unwrap_if_constexpr(mask) + cache_modifier = _semantic._str_to_load_cache_modifier(cache_modifier) + eviction_policy = _semantic._str_to_eviction_policy(eviction_policy) + volatile = _unwrap_if_constexpr(volatile) + if mask is not None: + pointer, mask = _semantic.broadcast_impl_value(pointer, mask) + _check( + smem.shape == pointer.shape, lambda: + f"expected smem shape to match pointer shape but got smem.shape = {smem.shape}, pointer.shape = {pointer.shape}" + ) + mask_handle = mask.handle if mask is not None else ir.value() + _semantic.builder.create_async_copy_global_to_local(smem.handle, pointer.handle, mask_handle, ir.value(), + cache_modifier, eviction_policy, volatile) + + +@builtin +def mbarrier_arrive(mbarrier, increment_count=True, _semantic=None): + """ + Arrive on the mbarrier once all outstanding async copies are complete. + + Args: + mbarrier (shared_memory_descriptor): Barrier object to arrive on. + increment_count (bool): Whether to increment the arrival count. Defaults to True. + """ + increment_count = _unwrap_if_constexpr(increment_count) + _semantic.builder.create_async_copy_mbarrier_arrive(mbarrier.handle, increment_count) + + +@builtin +def commit_group(_semantic=None): + """ + Commit the current asynchronous copy group. + + This finalizes a set of asynchronous copy operations. + """ + _semantic.builder.create_async_commit_group() + + +@builtin +def wait_group(num_outstanding=0, _semantic=None): + """ + Wait for outstanding asynchronous copy group operations. + + Args: + num_outstanding (int): Wait until `num_outstanding` or less async copy groups in-flight. Defaults to 0. + """ + num_outstanding = _unwrap_if_constexpr(num_outstanding) + _semantic.builder.create_async_wait_group(num_outstanding) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/mbarrier.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/mbarrier.py new file mode 100644 index 0000000000000000000000000000000000000000..d8c37c3af8cda75d9e6918d84669cc6315656b64 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/mbarrier.py @@ -0,0 +1,80 @@ +from triton.experimental.gluon.language._layouts import SwizzledSharedLayout +from triton.experimental.gluon.language._core import builtin, _unwrap_if_constexpr + +__all__ = ["arrive", "init", "invalidate", "MBarrierLayout", "wait"] + + +class MBarrierLayout(SwizzledSharedLayout): + """ + Layout for mbarrier synchronization in Ampere and later architectures. + + Args: + ctas_per_cga (int): CTAs per CGA grouping. Defaults to 1. + cta_split_num (int): CTA split factor. Defaults to 1. + """ + + def __init__(self, ctas_per_cga: int = 1, cta_split_num: int = 1): + super().__init__( + vec=1, + per_phase=1, + max_phase=1, + order=[0], + ctas_per_cga=[ctas_per_cga], + cta_split_num=[cta_split_num], + cta_order=[0], + ) + + +@builtin +def init(mbarrier, count, _semantic=None): + """ + Initialize an mbarrier with a specified count. + + Args: + mbarrier (shared_memory_descriptor): The barrier object to initialize. + count (int): The initial count for the barrier. + """ + count = _unwrap_if_constexpr(count) + _semantic.builder.create_mbarrier_init(mbarrier.handle, count) + + +@builtin +def invalidate(mbarrier, _semantic=None): + """ + Invalidate an mbarrier, resetting its state. + + Args: + mbarrier (shared_memory_descriptor): The barrier object to invalidate. + """ + _semantic.builder.create_mbarrier_inval(mbarrier.handle) + + +@builtin +def wait(mbarrier, phase, pred=True, deps=(), _semantic=None): + """ + Wait until the mbarrier object completes its current phase. + + Args: + mbarrier (shared_memory_descriptor): The barrier object to wait on. + phase (int): The phase index to wait for. + pred (bool): Predicate. Operation is skipped if predicate is False. Defaults to True. + deps (Sequence[shared_memory_descriptor]): Dependent allocations barrier is waiting on. Used to track liveness of dependent allocations. Defaults to (). + """ + phase = _semantic.to_tensor(phase) + pred = _semantic.to_tensor(pred) + deps = [x.handle for x in deps] + _semantic.builder.create_mbarrier_wait(mbarrier.handle, phase.handle, pred.handle, deps) + + +@builtin +def arrive(mbarrier, *, pred=True, _semantic=None): + """ + Arrive on an mbarrier, signaling that a thread has reached the barrier. + + Args: + mbarrier (shared_memory_descriptor): The barrier object to arrive on. + pred (bool): Predicate. Operation is skipped if predicate is False. Defaults to True. + """ + count = 1 + pred = _semantic.to_tensor(pred) + _semantic.builder.create_mbarrier_arrive(mbarrier.handle, count, pred.handle) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/blackwell/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/blackwell/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3cbf629e5e59d9699e97bb1456cc30beb74f67bd --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/blackwell/__init__.py @@ -0,0 +1,387 @@ +from __future__ import annotations +from typing import Optional, Tuple, List, TYPE_CHECKING + +from dataclasses import dataclass +from triton.runtime.jit import constexpr_function +from triton.experimental.gluon.language import _core as ttgl +from triton.experimental.gluon.language._core import builtin, base_type, base_value, _unwrap_if_constexpr +from triton.experimental.gluon.language._layouts import BlockedLayout, _get_shape_per_cta +from triton.experimental.gluon.language._semantic import _check + +from . import tma +from ..hopper import fence_async_shared, mbarrier +from ..ampere import async_copy + +from triton._C.libtriton import ir +if TYPE_CHECKING: + from triton._C.libtriton.gluon_ir import GluonOpBuilder + from ..._semantic import GluonSemantic + +__all__ = [ + "allocate_tensor_memory", + "async_copy", + "fence_async_shared", + "get_tmem_32x32b_reg_layout", + "mbarrier", + "tensor_memory_descriptor", + "TensorMemoryLayout", + "tma", +] + + +@dataclass(frozen=True, eq=True) +class TensorMemoryLayout: + """ + Describes the layout for tensor memory in Blackwell architecture. + + Args: + block (Tuple[int, int]): Tiling block dimensions (M/rows, N/cols). + unpacked (bool): For sub-32 bit elements, whether they are unpacked to 32 bits. + cta_split_num (Optional[Tuple[int, int]]): CTA split factors. Defaults to None. + """ + block: Tuple[int, int] + unpacked: bool + cta_split_num: Optional[Tuple[int, int]] = None + + def __post_init__(self): + assert len(self.block) == 2 + assert self.cta_split_num is None or len(self.cta_split_num) == 2 + + def _to_ir(self, builder): + cta_split_num = self.cta_split_num or [1, 1] + return builder.get_tensor_memory_layout( + self.block, + self.unpacked, + cta_split_num, + ) + + def mangle(self) -> str: + block_str = f"{self.block[0]}x{self.block[1]}" + unpacked_str = "U" if self.unpacked else "P" + cta_split_str = f"CS{self.cta_split_num[0]}x{self.cta_split_num[1]}" if self.cta_split_num else "" + return f"TL{block_str}{unpacked_str}{cta_split_str}TL" + + +@dataclass(frozen=True, eq=True) +class TensorMemoryScalesLayout: + """ + Describes the layout for tensor memory scales in Blackwell architecture. + + Args: + cta_split_num (Optional[Tuple[int, int]]): CTA split factors. Defaults to None. + """ + cta_split_num: Optional[Tuple[int, int]] = None + + def __post_init__(self): + assert self.cta_split_num is None or len(self.cta_split_num) == 2 + + def _to_ir(self, builder): + cta_split_num = self.cta_split_num or [1, 1] + return builder.get_tensor_memory_scales_layout(cta_split_num, ) + + def mangle(self) -> str: + cta_split_str = f"CS{self.cta_split_num[0]}x{self.cta_split_num[1]}" if self.cta_split_num else "" + return f"TLS{cta_split_str}TLS" + + +@constexpr_function +def _cdiv(x, div): + return (x + div - 1) // div + + +@constexpr_function +def get_tmem_32x32b_reg_layout(M, N, shape, num_warps, ctas_per_cga=None, cta_split_num=None, cta_order=None): + """Returns a BlockedLayout compatible with load/store on tensor memory with the 32x32b instruction variant. + """ + assert len(shape) == 2, "expected a 2D tensor" + assert num_warps in [4, 8], "expected 4 or 8 warps" + + shape_per_cta = _get_shape_per_cta(shape, cta_split_num) + blocks_per_tile = [shape_per_cta[0] // M, shape_per_cta[1] // N] + num_blocks = blocks_per_tile[0] * blocks_per_tile[1] + + num_warp_groups = num_warps // 4 + if M == 64: + threads_per_warp = [16, 2] + if num_blocks == 1: + size_per_thread = [1, _cdiv(N, num_warp_groups * 2)] + warps_per_cta = [4, num_warp_groups] + else: + size_per_thread = [1, _cdiv(N, 2)] + warps_per_cta = [4 * min(blocks_per_tile[0], num_warp_groups)] + warps_per_cta.append(_cdiv(num_warp_groups, warps_per_cta[0] // 4)) + else: + if shape[0] > 128: + size_per_thread = [1, N] + threads_per_warp = [32, 1] + warps_per_cta = [4 * num_warp_groups, 1] + else: + size_per_thread = [1, _cdiv(N, num_warp_groups)] + threads_per_warp = [32, 1] + warps_per_cta = [4, num_warp_groups] + return BlockedLayout( + size_per_thread=size_per_thread, + threads_per_warp=threads_per_warp, + warps_per_cta=warps_per_cta, + order=[0, 1], + ctas_per_cga=ctas_per_cga, + cta_split_num=cta_split_num, + cta_order=cta_order, + ) + + +class tensor_memory_descriptor_type(base_type): + + def __init__(self, element_ty, shape, layout, alloc_shape): + self.element_ty = element_ty + self.shape = shape + self.layout = layout + self.alloc_shape = alloc_shape + assert isinstance(layout, TensorMemoryLayout) or isinstance(layout, TensorMemoryScalesLayout) + + def to_ir(self, builder: GluonOpBuilder) -> None: + return builder.get_tensor_mem_desc_ty( + self.element_ty.to_ir(builder), + self.shape, + self.layout._to_ir(builder), + self.alloc_shape, + ) + + def _unflatten_ir(self, handles: List[ir.Value], cursor: int) -> Tuple[tensor_memory_descriptor, int]: + value = tensor_memory_descriptor(handles[cursor], self.element_ty, self.shape, self.layout, self.alloc_shape) + return value, cursor + 1 + + def _flatten_ir_types(self, builder: GluonOpBuilder, out: List[ir.type]) -> None: + out.append(self.to_ir(builder)) + + def __str__(self) -> str: + return f"tensor_memory_descriptor<{self.element_ty}, {self.shape}, {self.layout}>" + + def __eq__(self, other) -> bool: + return (type(self) is type(other) and self.shape == other.shape and self.layout == other.layout + and self.alloc_shape == other.alloc_shape) + + def __neq__(self, other) -> bool: + return not (self == other) + + def mangle(self) -> str: + shape_str = "_".join([str(s) for s in self.shape]) + return f"MD{self.element_ty.mangle()}S{shape_str}SL{self.layout.mangle()}LAS{self.alloc_shape}ASMD" + + +class tensor_memory_descriptor(base_value): + """ + Represents a tensor memory descriptor handle for Tensor Core Gen5 operations. + """ + + def __init__(self, handle, element_ty, shape, layout, alloc_shape): + self.handle = handle + self.type = tensor_memory_descriptor_type(element_ty, shape, layout, alloc_shape) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + handles.append(self.handle) + + @property + def dtype(self): + return self.type.element_ty + + @property + def shape(self): + return self.type.shape + + @property + def rank(self): + return len(self.shape) + + @property + def layout(self): + return self.type.layout + + def __str__(self) -> str: + return str(self.type) + + @builtin + def load(self, layout, _semantic: GluonSemantic) -> ttgl.tensor: + """ + Load a tensor from tensor memory. + + Args: + layout (DistributedLayout): Destination layout of the tensor. + + Returns: + tensor: A distributed tensor containing the loaded data. + """ + layout = _unwrap_if_constexpr(layout) + ret_ty = ttgl.distributed_type(self.dtype, self.shape, layout) + builder = _semantic.builder + handle = builder.create_tmem_load(ret_ty.to_ir(builder), self.handle) + return ttgl.tensor(handle, ret_ty) + + @builtin + def store(self, value, pred=True, _semantic: GluonSemantic = None) -> None: + """ + Store a tensor into tensor memory. + + Args: + value (tensor): The tensor to store. + pred (bool): Scalar predicate. Operation is skipped if predicate is False. Defaults to True. + """ + pred = _unwrap_if_constexpr(pred) + pred = _semantic.to_tensor(pred) + assert value.shape == self.shape, f"source shape {value.shape} does not match destination shape {self.shape}" + assert value.dtype == self.dtype, f"source dtype {value.dtype} does not match destination dtype {self.dtype}" + _semantic.builder.create_tmem_store(self.handle, value.handle, pred.handle) + + @builtin + def slice(self, start, length, _semantic: GluonSemantic) -> None: + """ + Create a slice of the tensor memory descriptor along the last dimension. + + Args: + start (int): The starting index for subslice. + length (int): The length of the subslice. + + Returns: + tensor_memory_descriptor: Descriptor for the subslice. + """ + start = _unwrap_if_constexpr(start) + length = _unwrap_if_constexpr(length) + _check(isinstance(start, int), lambda: "start must be a constant int") + _check(isinstance(length, int), lambda: "length must be a constant int") + shape = self.shape[:-1] + [length] + layout = self.type.layout + layout = TensorMemoryLayout((layout.block[0], min(layout.block[1], length)), layout.unpacked, + layout.cta_split_num) + ret = tensor_memory_descriptor(None, self.dtype, shape, layout, self.type.alloc_shape) + builder = _semantic.builder + ret.handle = builder.create_tmem_subslice(ret.type.to_ir(builder), self.handle, start) + return ret + + @builtin + def index(self, index, _semantic: GluonSemantic = None) -> tensor_memory_descriptor: + """ + Create a subview of tensor memory by indexing the first dimension. + + Args: + index (tensor): The index tensor for the subview. + + Returns: + tensor_memory_descriptor: Descriptor for the indexed subview. + """ + index = _semantic.to_tensor(index) + builder = _semantic.builder + shape = self.shape[1:] + layout = self.layout + ret = tensor_memory_descriptor(None, self.dtype, shape, layout, self.type.alloc_shape) + ret.handle = builder.create_memdesc_index(ret.type.to_ir(builder), self.handle, index.handle) + return ret + + @builtin + def _reinterpret(self, dtype, shape, layout, _semantic: GluonSemantic = None) -> tensor_memory_descriptor: + """ + Reinterpret tensor memory descriptor with a new dtype, shape, and layout. + + Args: + dtype (dtype): The new data type. + shape (Sequence[int]): The new shape. + layout (TensorMemoryLayout): The new layout. + + Returns: + tensor_memory_descriptor: Descriptor with updated type and layout. + """ + dtype = _unwrap_if_constexpr(dtype) + shape = [_unwrap_if_constexpr(s) for s in shape] + layout = _unwrap_if_constexpr(layout) + + ty = tensor_memory_descriptor_type(dtype, shape, layout, shape) + handle = _semantic.builder.create_memdesc_reinterpret(ty.to_ir(_semantic.builder), self.handle) + return tensor_memory_descriptor(handle, **ty.__dict__) + + +@builtin +def allocate_tensor_memory(element_ty, shape, layout, value=None, _semantic=None): + """ + Allocate tensor memory. + + Args: + element_ty (dtype): The element data type. + shape (Sequence[int]): The descriptor shape. + layout (TensorMemoryLayout): The layout of the tensor memory. + value (tensor, optional): Initial tensor to copy. Defaults to None. + + Returns: + tensor_memory_descriptor: Descriptor for the allocated memory. + """ + element_ty = _unwrap_if_constexpr(element_ty) + shape = _unwrap_if_constexpr(shape) + layout = _unwrap_if_constexpr(layout) + value = value.handle if value is not None else None + + ty = tensor_memory_descriptor_type(element_ty, shape, layout, shape) + builder = _semantic.builder + handle = builder.create_tmem_alloc(ty.to_ir(builder), value) + return tensor_memory_descriptor(handle, element_ty, shape, layout, shape) + + +@builtin +def tcgen05_copy(src, dst, _semantic=None): + """ + Start an asynchronous copy from shared memory to tensor memory. + + WARNING: The current semantics of the instruction are not well defined and + the API will change in the future. Use at your own risk. + + Args: + src (shared_memory_descriptor): Shared memory to copy from. + dst (tensor_memory_descriptor): Tensor memory to copy to. + """ + assert isinstance(src, ttgl.shared_memory_descriptor), "source must be a shared memory descriptor" + assert isinstance(dst, tensor_memory_descriptor), "destination must be a tensor memory descriptor" + _semantic.builder.create_tmem_copy(src.handle, dst.handle) + + +@builtin +def tcgen05_mma(a, b, acc, *, use_acc=True, pred=True, mbarriers=None, mbarrier_preds=None, _semantic=None): + """ + Emit a 5th generation TensorCore MMA instruction. + acc = a * b + (acc if use_acc else 0) + + Args: + a (shared_memory_descriptor): Left hand side operand in shared memory. + b (shared_memory_descriptor or tensor_memory_descriptor): Right hand side operand in shared or tensor memory. + acc (tensor_memory_descriptor): Accumulator value in tensor memory (mutated). + use_acc (bool): Whether to use the initial value of the accumulator. Defaults to True. + pred (bool): Scalar predicate. Operation is skipped if predicate is False. Defaults to True. + mbarriers (Sequence[shared_memory_descriptor], optional): Barriers to signal when the operation is complete. If None, mma is synchronous. Defaults to None. + mbarrier_preds (Sequence[bool], optional): Predicates for barriers. Defaults to None. + """ + use_acc = _semantic.to_tensor(use_acc) + pred = _semantic.to_tensor(pred) + + if mbarriers is None: + assert mbarrier_preds is None + mbarriers = [] + mbarrier_preds = [] + else: + mbarriers = [bar.handle for bar in mbarriers] + if mbarrier_preds is None: + true = _semantic.to_tensor(True) + mbarrier_preds = [true.handle] * len(mbarriers) + else: + mbarrier_preds = _semantic._convert_to_ir_values(mbarrier_preds, require_i64=False) + + _semantic.builder.create_tcgen05_mma(a.handle, b.handle, acc.handle, use_acc.handle, pred.handle, mbarriers, + mbarrier_preds) + + +@builtin +def tcgen05_commit(barrier, _semantic=None): + """ + This instruction causes the provided mbarrier to be arrived-on with a count + of 1 when all async tcgen05 MMA and copy instructions previously issued by + the thread are complete. + + Args: + barrier (shared_memory_descriptor): The barrier to track completion of tcgen05 MMA and copy instructions. + """ + _semantic.builder.create_tcgen05_commit(barrier.handle) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/blackwell/tma.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/blackwell/tma.py new file mode 100644 index 0000000000000000000000000000000000000000..60a0724c55a593d3f8eb714e2c2756053fed2f7c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/blackwell/tma.py @@ -0,0 +1,52 @@ +from triton.experimental.gluon.language._core import builtin +from triton.experimental.gluon.language.nvidia.hopper.tma import ( + async_copy_global_to_shared, + async_copy_shared_to_global, + store_wait, + tensor_descriptor, + tensor_descriptor_type, +) + +__all__ = [ + "async_gather", + "async_scatter", + "async_copy_global_to_shared", + "async_copy_shared_to_global", + "store_wait", + "tensor_descriptor", + "tensor_descriptor_type", +] + + +@builtin +def async_gather(tensor_desc, x_offsets, y_offset, barrier, result, pred=True, _semantic=None): + """ + Asynchronously gather elements from global memory to shared memory using TMA. + + Args: + tensor_desc (tensor_descriptor): The tensor descriptor. + x_offsets (tensor): 1D tensor of X offsets. + y_offset (int): Scalar Y offset. + barrier (shared_memory_descriptor): Barrier that will be signaled when the operation is complete. + result (tensor_memory_descriptor): Result shared memory, must have NVMMASharedLayout. + pred (bool): Scalar predicate. Operation is skipped if predicate is False. Defaults to True. + """ + pred = _semantic.to_tensor(pred) + y_offset = _semantic.to_tensor(y_offset) + _semantic.builder.create_async_tma_gather(tensor_desc.handle, x_offsets.handle, y_offset.handle, barrier.handle, + result.handle, pred.handle) + + +@builtin +def async_scatter(tensor_desc, x_offsets, y_offset, src, _semantic=None): + """ + Asynchronously scatter elements from shared memory to global memory using TMA. + + Args: + tensor_desc (tensor_descriptor): The tensor descriptor. + x_offsets (tensor): 1D tensor of X offsets. + y_offset (int): Scalar Y offset. + src (tensor_memory_descriptor): The source data, must be in NVMMASharedLayout. + """ + y_offset = _semantic.to_tensor(y_offset) + _semantic.builder.create_async_tma_scatter(tensor_desc.handle, x_offsets.handle, y_offset.handle, src.handle) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fc504ad38d31a4bcf2c03136b6764971dd1840de --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/__init__.py @@ -0,0 +1,132 @@ +from __future__ import annotations +from triton.compiler.code_generator import unflatten_ir_values +from ..ampere import async_copy +from . import mbarrier, tma +from ... import _core + +from typing import List, Tuple, TYPE_CHECKING +if TYPE_CHECKING: + from triton._C.libtriton import ir + +__all__ = ["async_copy", "fence_async_shared", "mbarrier", "tma", "warpgroup_mma", "warpgroup_mma_wait"] + + +@_core.builtin +def fence_async_shared(cluster=False, _semantic=None): + """ + Issue a fence to complete asynchronous shared memory operations. + + Args: + cluster (bool): Whether to fence across cluster. Defaults to False. + """ + cluster = _core._unwrap_if_constexpr(cluster) + _semantic.builder.create_fence_async_shared(cluster) + + +class warpgroup_mma_accumulator_type(_core.base_type): + tensor_type: _core.dtype + + def __init__(self, tensor_type: _core.dtype): + self.tensor_type = tensor_type + + def __str__(self) -> str: + return f"warpgroup_mma_accumulator<{self.tensor_type}>" + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[warpgroup_mma_accumulator, int]: + return warpgroup_mma_accumulator(handles[cursor], self.tensor_type), cursor + 1 + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + self.tensor_type._flatten_ir_types(builder, out) + + def __eq__(self, other) -> bool: + return type(self) is type(other) and self.tensor_type == other.tensor_type + + def mangle(self) -> str: + return f"FT{self.tensor_type.mangle()}FT" + + +class warpgroup_mma_accumulator(_core.base_value): + handle: ir.value + type: warpgroup_mma_accumulator_type + + def __init__(self, handle, tensor_type: _core.dtype): + self.handle = handle + self.type = warpgroup_mma_accumulator_type(tensor_type) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + handles.append(self.handle) + + +@_core.builtin +def warpgroup_mma_init(value, _semantic): + assert isinstance(value, _core.tensor) + return warpgroup_mma_accumulator(value.handle, value.type) + + +@_core.builtin +def warpgroup_mma(a, b, acc, *, use_acc=True, precision=None, max_num_imprecise_acc=None, is_async=False, + _semantic=None): + """ + Perform warpgroup MMA (Tensor Core) operations. + acc = a * b + (acc if use_acc else 0) + + Args: + a (tensor or shared_memory_descriptor): Left hand side operand. + b (shared_memory_descriptor): Right hand side operand. + acc (tensor): Accumulator tensor. + use_acc (bool): Whether to use the initial value of the accumulator. Defaults to True. + precision (str, optional): Dot input precision. Defaults to builder default. + max_num_imprecise_acc (int): Max imprecise accumulations. Used for fp8 -> fp32 dot. Determines how many accumulation are done in limited precision. Defaults to None, which means no upcasting is done. + is_async (bool): Whether operation is asynchronous. Defaults to False. + + Returns: + tensor or warpgroup_mma_accumulator: Returns the result if synchronous, or a token to load the value once computed if asynchronous. + """ + use_acc = _semantic.to_tensor(use_acc) + + if precision is None: + precision = _semantic.builder.options.default_dot_input_precision + + precision = _semantic._str_to_dot_input_precision(precision) + + K = a.type.shape[-1] + if max_num_imprecise_acc is None: + if a.dtype.is_fp8() and b.dtype.is_fp8(): + max_num_imprecise_acc = _semantic.builder.options.max_num_imprecise_acc_default + else: + max_num_imprecise_acc = 0 + else: + if a.dtype.is_fp8() and b.dtype.is_fp8() and max_num_imprecise_acc > K: + raise ValueError(f"max_num_imprecise_acc ({max_num_imprecise_acc}) must be <= K ({K})") + + max_num_imprecise_acc = _core._unwrap_if_constexpr(max_num_imprecise_acc) + is_async = _core._unwrap_if_constexpr(is_async) + + handle = _semantic.builder.create_warpgroup_mma(a.handle, b.handle, acc.handle, use_acc.handle, precision, + max_num_imprecise_acc, is_async) + tensor_ty = acc.type.tensor_type if isinstance(acc, warpgroup_mma_accumulator) else acc.type + if is_async: + return warpgroup_mma_accumulator(handle, tensor_ty) + else: + return _core.tensor(handle, tensor_ty) + + +@_core.builtin +def warpgroup_mma_wait(num_outstanding=0, deps=None, _semantic=None): + """ + Wait until `num_outstanding` or less warpgroup MMA operations are in-flight. + + Args: + num_outstanding (int): Number of outstanding warpgroup MMA operations to wait for. Defaults to 0. + deps (Sequence[tensor]): List of dependencies that need to be kept alive while the mma is unfinished. + """ + if deps is None: + raise ValueError("warpgroup_mma_wait deps must be given") + deps_handles = [x.handle for x in deps] if deps is not None else [] + num_outstanding = _core._unwrap_if_constexpr(num_outstanding) + results = _semantic.builder.create_warpgroup_mma_wait(deps_handles, num_outstanding) + result_types = [dep.type.tensor_type if isinstance(dep, warpgroup_mma_accumulator) else dep.type for dep in deps] + results = unflatten_ir_values(results, result_types) + if len(deps) == 1: + return next(results) + return tuple(results) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/mbarrier.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/mbarrier.py new file mode 100644 index 0000000000000000000000000000000000000000..93bf51ebadac0dfeaeb8a4bfec975b61ab35e90c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/mbarrier.py @@ -0,0 +1,34 @@ +from ..ampere.mbarrier import MBarrierLayout, init, invalidate, wait +from ..._core import _unwrap_if_constexpr, builtin + +__all__ = ["arrive", "expect", "init", "invalidate", "MBarrierLayout", "wait"] + + +@builtin +def expect(mbarrier, bytes, pred=True, _semantic=None): + """ + Expect a specific number of bytes being copied. When they are copied, the barrier is signaled. + + Args: + mbarrier (shared_memory_descriptor): Barrier that will be signaled when the operation is complete. + bytes (int): Expected byte count. + pred (bool): Scalar predicate. Operation is skipped if predicate is False. Defaults to True. + """ + bytes = _unwrap_if_constexpr(bytes) + pred = _semantic.to_tensor(pred) + _semantic.builder.create_mbarrier_expect(mbarrier.handle, bytes, pred.handle) + + +@builtin +def arrive(mbarrier, *, count=1, pred=True, _semantic=None): + """ + Arrive at an mbarrier with a specified count. + + Args: + mbarrier (shared_memory_descriptor): Barrier to be signalled. + count (int): Count to arrive with. Defaults to 1. + pred (bool): Scalar predicate. Operation is skipped if predicate is False. Defaults to True. + """ + count = _unwrap_if_constexpr(count) + pred = _semantic.to_tensor(pred) + _semantic.builder.create_mbarrier_arrive(mbarrier.handle, count, pred.handle) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/tma.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/tma.py new file mode 100644 index 0000000000000000000000000000000000000000..ea26e20bd29fc6ad67ac13ef53442577a4917c47 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/tma.py @@ -0,0 +1,97 @@ +from __future__ import annotations +from typing import List, Tuple, TYPE_CHECKING +from dataclasses import dataclass +from triton.language.core import base_type, base_value +import triton.experimental.gluon.language._core as ttgl +from triton.experimental.gluon.language._layouts import NVMMASharedLayout +from triton.experimental.gluon.language._core import builtin, _unwrap_if_constexpr + +if TYPE_CHECKING: + from triton._C import ir + +__all__ = ["async_copy_global_to_shared", "async_copy_shared_to_global", "store_wait"] + + +@dataclass(eq=True) +class tensor_descriptor_type(base_type): + block_type: ttgl.block_type + shape_type: ttgl.tuple_type + strides_type: ttgl.tuple_type + layout: NVMMASharedLayout + + def __str__(self) -> str: + return f"tensor_descriptor<{self.block_type}, {self.layout}>" + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[tensor_descriptor, int]: + handle = handles[cursor] + cursor += 1 + shape, cursor = self.shape_type._unflatten_ir(handles, cursor) + strides, cursor = self.strides_type._unflatten_ir(handles, cursor) + value = tensor_descriptor(handle, shape, strides, self.block_type, layout=self.layout) + return value, cursor + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + is_signed = self.block_type.element_ty.is_int_signed() + ty = builder.get_tensor_descriptor_layout_type( + self.block_type.to_ir(builder), + is_signed, + self.layout._to_ir(builder), + ) + out.append(ty) + self.shape_type._flatten_ir_types(builder, out) + self.strides_type._flatten_ir_types(builder, out) + + def mangle(self) -> str: + return f"TD{self.block_type.mangle()}_{self.layout.mangle()}TD" + + +class tensor_descriptor(base_value): + + def __init__(self, handle, shape: List[ttgl.tensor], strides: List[ttgl.tensor], block_type: ttgl.block_type, + layout: NVMMASharedLayout): + self.handle = handle + self.shape = ttgl.tuple(shape) + self.strides = ttgl.tuple(strides) + self.type = tensor_descriptor_type(block_type, shape_type=self.shape.type, strides_type=self.strides.type, + layout=layout) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + handles.append(self.handle) + self.shape._flatten_ir(handles) + self.strides._flatten_ir(handles) + + @property + def block_type(self): + return self.type.block_type + + @property + def block_shape(self): + return self.type.block_type.shape + + @property + def dtype(self): + return self.type.block_type.element_ty + + @property + def layout(self): + return self.type.layout + + +@builtin +def async_copy_global_to_shared(tensor_desc, coord, barrier, result, pred=True, _semantic=None): + coord = _semantic._convert_to_ir_values(coord, require_i64=False) + pred = _semantic.to_tensor(pred) + _semantic.builder.create_async_tma_copy_global_to_local(tensor_desc.handle, coord, barrier.handle, result.handle, + pred.handle) + + +@builtin +def async_copy_shared_to_global(tensor_desc, coord, src, _semantic=None): + coord = _semantic._convert_to_ir_values(coord, require_i64=False) + _semantic.builder.create_async_tma_copy_local_to_global(tensor_desc.handle, coord, src.handle) + + +@builtin +def store_wait(pendings, _semantic=None): + pendings = _unwrap_if_constexpr(pendings) + _semantic.builder.create_async_tma_store_wait(pendings) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8184c7388eaa11e018905df24982af333a9df6d5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/__init__.py @@ -0,0 +1,4 @@ +from . import hopper +from . import blackwell + +__all__ = ["hopper", "blackwell"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/blackwell.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/blackwell.py new file mode 100644 index 0000000000000000000000000000000000000000..abf919805191d9ebddbf416b3be95187fdf893cb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/blackwell.py @@ -0,0 +1,3 @@ +from .hopper import TensorDescriptor + +__all__ = ["TensorDescriptor"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/hopper.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/hopper.py new file mode 100644 index 0000000000000000000000000000000000000000..81069908eafab95b5d36b1cebea73e44e3c5b716 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/hopper.py @@ -0,0 +1,45 @@ +from dataclasses import dataclass +from typing import List, Any +from triton._utils import validate_block_shape, canonicalize_dtype, get_primitive_bitwidth +from triton.experimental.gluon.language._layouts import NVMMASharedLayout + +__all__ = ["TensorDescriptor"] + + +@dataclass +class TensorDescriptor: + base: Any + shape: List[int] + strides: List[int] + block_shape: List[int] + layout: NVMMASharedLayout + padding: str = "zero" + + def __post_init__(self): + rank = len(self.shape) + assert len(self.strides) == rank, f"rank mismatch: {self}" + assert len(self.block_shape) == rank, f"rank mismatch: {self}" + assert rank > 0, "rank must not be zero" + assert rank <= 5, "rank cannot be more than 5" + assert self.base.data_ptr() % 16 == 0, "base must be 16-byte aligned" + validate_block_shape(self.block_shape) + dtype_str = canonicalize_dtype(self.base.dtype) + elem_bytes = get_primitive_bitwidth(dtype_str) // 8 + for stride in self.strides[:-1]: + assert (stride * elem_bytes) % 16 == 0, "strides must be 16-byte aligned" + assert self.strides[-1] == 1, "Last dimension must be contiguous" + assert isinstance(self.layout, NVMMASharedLayout), "Layout must be NVMMASharedLayout" + assert self.padding == "zero" or self.padding == "nan", "Illegal value for padding" + if self.padding == "nan": + assert self.base.dtype.is_floating_point, "Padding option `nan` is only supported for floating point tensors" + + @staticmethod + def from_tensor(tensor: Any, block_shape: List[int], layout: NVMMASharedLayout, padding="zero"): + return TensorDescriptor( + tensor, + tensor.shape, + tensor.stride(), + block_shape, + layout, + padding, + ) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/knobs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/knobs.py new file mode 100644 index 0000000000000000000000000000000000000000..161f739bd6d6b99c292d91af6bb49f6d0b52d6d6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/knobs.py @@ -0,0 +1,522 @@ +from __future__ import annotations + +import functools +import importlib +import os +import re +import subprocess +import sysconfig + +from dataclasses import dataclass +from contextlib import contextmanager +from typing import cast, Any, Callable, Generator, Generic, Optional, Protocol, Type, TypeVar, TypedDict, TYPE_CHECKING, Union + +from triton._C.libtriton import getenv, getenv_bool # type: ignore + +if TYPE_CHECKING: + from .runtime.cache import CacheManager, RemoteCacheBackend + from .runtime.jit import JitFunctionInfo, KernelParam + from .compiler.compiler import ASTSource, LazyDict, IRSource + + +class Env: + pass + + +env = Env() + +propagate_env: bool = True + + +def setenv(key: str, value: Optional[str]) -> None: + if not propagate_env: + return + + if value is not None: + os.environ[key] = value + elif key in os.environ: + del os.environ[key] + + +def toenv(val: Any) -> Union[None, tuple[Optional[str]]]: + if val is None: + return (None, ) + + t = type(val) + if t is bool: + return ("1" if val else "0", ) + + if t is str: + return (val, ) + + if t is int: + return (str(val), ) + + return None + + +# There's an asymmetry here so that e.g. env_nvidia_tool can be specified with a +# a string but return an NvidiaTool. +SetType = TypeVar("SetType") +GetType = TypeVar("GetType") + +_NOTHING = object() + + +class env_base(Generic[SetType, GetType]): + + def __init__(self, key: str) -> None: + self.key = key + + def __set_name__(self, objclass: Type[object], name: str) -> None: + self.name = name + + def __get__(self, obj: Optional[object], objclass: Optional[Type[object]]) -> GetType: + py_val = obj.__dict__.get(self.name, _NOTHING) + if py_val is _NOTHING: + return self.get() + return self.transform(py_val) + + def get(self) -> GetType: + raise NotImplementedError() + + def __set__(self, obj: object, value: Union[SetType, Env]) -> None: + if isinstance(value, Env): + obj.__dict__.pop(self.name, None) + else: + obj.__dict__[self.name] = value + if env_val := toenv(value): + setenv(self.key, env_val[0]) + + def __delete__(self, obj: object) -> None: + obj.__dict__.pop(self.name, None) + + def transform(self, val: SetType) -> GetType: + # See comment about GetType/SetType in their definition above. Only needed + # if GetType != SetType. + return cast(GetType, val) + + +class env_str(env_base[str, str]): + + def __init__(self, key: str, default: str): + super().__init__(key) + self.default = default + + def get(self) -> str: + return getenv(self.key, self.default) + + +class env_str_callable_default(env_base[str, str]): + + def __init__(self, key: str, default_factory: Callable[[], str]): + super().__init__(key) + self.default_factory = default_factory + + def get(self) -> str: + env_val = getenv(self.key) + if env_val is None: + return self.default_factory() + return env_val + + +class env_bool(env_base[bool, bool]): + + def __init__(self, key: str, default: bool = False) -> None: + super().__init__(key) + self.default = default + + def get(self) -> bool: + return getenv_bool(self.key, self.default) + + +class env_int(env_base[int, int]): + + def __init__(self, key: str, default: int = 0) -> None: + super().__init__(key) + self.default = default + + def get(self) -> int: + val = getenv(self.key) + if val is None: + return self.default + try: + return int(val) + except ValueError as exc: + raise RuntimeError(f"Unable to use {self.key}={val}: expected int") from exc + + +ClassType = TypeVar("ClassType") + + +class env_class(Generic[ClassType], env_base[Optional[Type[ClassType]], Optional[Type[ClassType]]]): + + def __init__(self, key: str, type: str) -> None: + super().__init__(key) + # We can't pass the type directly to avoid import cycles + self.type = type + + def get(self) -> Optional[Type[ClassType]]: + val = getenv(self.key) + if val is None: + return None + comps = val.split(":", 1) + if len(comps) != 2: + raise RuntimeError(f"Unable to read {self.key}: '{val}' isn't of the form MODULE:CLASS") + cls = getattr(importlib.import_module(comps[0]), comps[1]) + + if not any((c.__name__ == self.type for c in cls.mro())): + raise RuntimeError(f"Unable to use '{val}' from {self.key}: not of type '{self.type}'") + + return cast(Type[ClassType], cls) + + +@dataclass +class NvidiaTool: + path: str + version: str + + @staticmethod + @functools.lru_cache + def from_path(path: str) -> Optional[NvidiaTool]: + try: + result = subprocess.check_output([path, "--version"], stderr=subprocess.STDOUT) + version = re.search(r".*release (\d+\.\d+).*", result.decode("utf-8"), flags=re.MULTILINE) + if version is None: + return None + return NvidiaTool(path, version.group(1)) + except (subprocess.CalledProcessError, FileNotFoundError): + return None + + +class env_nvidia_tool(env_base[str, NvidiaTool]): + + def __init__(self, binary: str) -> None: + binary += sysconfig.get_config_var("EXE") + self.binary = binary + self.default_path = os.path.join(os.path.dirname(__file__), "backends", "nvidia", "bin", binary) + super().__init__(f"TRITON_{binary.upper()}_PATH") + + def get(self) -> NvidiaTool: + return self.transform(getenv(self.key)) + + def transform(self, path: str) -> NvidiaTool: + # We still add default as fallback in case the pointed binary isn't + # accessible. + if path is not None: + paths = [path, self.default_path] + else: + paths = [self.default_path] + + for path in paths: + if tool := NvidiaTool.from_path(path): + return tool + + raise RuntimeError(f"Cannot find {self.binary}") + + +# Separate classes so that types are correct +class env_opt_str(env_base[Optional[str], Optional[str]]): + + def get(self) -> Optional[str]: + return getenv(self.key) + + +class env_opt_bool(env_base): + + def get(self) -> Optional[str]: + return getenv_bool(self.key, None) + + +@dataclass(frozen=True) +class CompileTimes: + """ + Model holding timing information for an invocation of the compiler. + + All times in microseconds. + """ + + # Duration of make_ir + ir_initialization: int + + # Ordered mapping from lowering stage to duration spent in that stage. + # Keyed by stage extension, e.g. ttir, ttgir + lowering_stages: list[tuple[str, int]] + + # Duration of saving artifacts/metadata to cache + store_results: int + + @property + def total_lowering(self) -> int: + return sum((stage[1] for stage in self.lowering_stages)) + + @property + def total(self) -> int: + return self.ir_initialization + self.total_lowering + self.store_results + + +class CompilationListener(Protocol): + + def __call__(self, *, src: Union[ASTSource, IRSource], metadata: dict[str, Any], metadata_group: dict[str, str], + times: CompileTimes, cache_hit: bool) -> None: + ... + + +knobs_type = TypeVar("knobs_type", bound='base_knobs') + + +class base_knobs: + + @property + def knob_descriptors(self) -> dict[str, env_base]: + return { + k: v + # data descriptors live on the class object + for k, v in type(self).__dict__.items() + if isinstance(v, env_base) + } + + @property + def knobs(self) -> dict[str, Any]: + return {k: getattr(self, k) for k in self.knob_descriptors.keys()} + + def copy(self: knobs_type) -> knobs_type: + res = type(self)() + res.__dict__.update(self.__dict__) + return res + + def reset(self: knobs_type) -> knobs_type: + for knob in self.knob_descriptors.keys(): + delattr(self, knob) + return self + + @contextmanager + def scope(self) -> Generator[None, None, None]: + try: + initial_env = {knob.key: getenv(knob.key) for knob in self.knob_descriptors.values()} + orig = dict(self.__dict__) + yield + finally: + self.__dict__.clear() + self.__dict__.update(orig) + + for k, v in initial_env.items(): + if v is not None: + os.environ[k] = v + elif k in os.environ: + del os.environ[k] + + +class BuildImpl(Protocol): + + def __call__(self, name: str, src: str, srcdir: str, library_dirs: list[str], include_dirs: list[str], + libraries: list[str], /) -> str: + ... + + +class build_knobs(base_knobs): + """Configuration controlling how the native compiler is invoked""" + cc: env_opt_str = env_opt_str("CC") + + cudacrt_path: env_opt_str = env_opt_str("TRITON_CUDACRT_PATH") + cudart_path: env_opt_str = env_opt_str("TRITON_CUDART_PATH") + + impl: Optional[BuildImpl] = None + + @property + def backend_dirs(self) -> set[str]: + return {path for path in (self.cudacrt_path, self.cudart_path) if path is not None} + + +class redis_knobs(base_knobs): + key_format: env_str = env_str("TRITON_REDIS_KEY_FORMAT", "triton:{key}:{filename}") + host: env_str = env_str("TRITON_REDIS_HOST", "localhost") + port: env_int = env_int("TRITON_REDIS_PORT", 6379) + + +cache: cache_knobs + + +class cache_knobs(base_knobs): + home_dir: env_str = env_str("TRITON_HOME", os.path.expanduser("~/")) + + dump_dir = env_str_callable_default("TRITON_DUMP_DIR", lambda: cache.get_triton_dir("dump")) + override_dir = env_str_callable_default("TRITON_OVERRIDE_DIR", lambda: cache.get_triton_dir("override")) + dir = env_str_callable_default("TRITON_CACHE_DIR", lambda: cache.get_triton_dir("cache")) + + manager_class: env_class[CacheManager] = env_class("TRITON_CACHE_MANAGER", "CacheManager") + remote_manager_class: env_class[RemoteCacheBackend] = env_class("TRITON_REMOTE_CACHE_BACKEND", "RemoteCacheBackend") + + def get_triton_dir(self, dirname: str) -> str: + return os.path.join(self.home_dir, ".triton", dirname) + + +class compilation_knobs(base_knobs): + override: env_bool = env_bool("TRITON_KERNEL_OVERRIDE") + dump_ir: env_bool = env_bool("TRITON_KERNEL_DUMP") + store_binary_only: env_bool = env_bool("TRITON_STORE_BINARY_ONLY") + always_compile: env_bool = env_bool("TRITON_ALWAYS_COMPILE") + # TODO: Use enum to constrain / 'typecheck' the values + use_ir_loc: env_opt_str = env_opt_str("USE_IR_LOC") + enable_asan: env_bool = env_bool("TRITON_ENABLE_ASAN") + disable_line_info: env_bool = env_bool("TRITON_DISABLE_LINE_INFO") + front_end_debugging: env_bool = env_bool("TRITON_FRONT_END_DEBUGGING") + allow_non_constexpr_globals: env_bool = env_bool("TRITON_ALLOW_NON_CONSTEXPR_GLOBALS") + enable_experimental_consan: env_bool = env_bool("TRITON_ENABLE_EXPERIMENTAL_CONSAN") + listener: Union[CompilationListener, None] = None + + +class autotuning_knobs(base_knobs): + cache: env_bool = env_bool("TRITON_CACHE_AUTOTUNING") + print: env_bool = env_bool("TRITON_PRINT_AUTOTUNING") + + +class LaunchHook(Protocol): + """Hook invoked before and after kernel launching + """ + + def __call__(self, metadata: LazyDict) -> None: + ... + + +class InitHandleHook(Protocol): + """Hook invoked around kernel binary/module loading. + module/function can be None for the *start* hook (before loading). + """ + + def __call__( + self, + module: Optional[object], + function: Optional[Callable], + name: str, + metadata_group: dict[str, str], + hash: str, + ) -> None: + ... + + +F = TypeVar("F", bound=Callable) + + +class HookChain(Generic[F]): + """A chain of hooks of the same type F to be called in order. + """ + + def __init__(self, reversed: bool = False): + self.calls: list[F] = [] + self.reversed = reversed + + def add(self, func: F) -> None: + if func not in self.calls: + self.calls.append(func) + + def remove(self, func: F) -> None: + if func in self.calls: + self.calls.remove(func) + + def __call__(self, *args, **kwargs): + for call in self.calls if not self.reversed else reversed(self.calls): + call(*args, **kwargs) + + +# This is of the form [attr_name, attr_val] +# TODO: Use tuple instead of list for better typing. +KernelAttr = list[Union[str, int]] + + +class JITHookCompileInfo(TypedDict): + key: str + signature: dict[KernelParam, str] + device: int + constants: None + num_warps: int + num_ctas: int + num_stages: int + enable_fp_fusion: bool + launch_cooperative_grid: bool + extern_libs: tuple[tuple[str, str], ...] + configs: list[dict[tuple[int, ...], list[KernelAttr]]] + specialization_data: str + is_warmup: bool + + +class JITHook(Protocol): + + def __call__(self, *, key: str, repr: str, fn: JitFunctionInfo, compile: JITHookCompileInfo, is_manual_warmup: bool, + already_compiled: bool) -> Optional[bool]: + ... + + +class runtime_knobs(base_knobs): + interpret: env_bool = env_bool("TRITON_INTERPRET") + # debug is on critical path for kernel launches + # avoid repeated reads from env-var by calling get directly + debug: bool = env_bool("TRITON_DEBUG").get() + override_arch: env_opt_str = env_opt_str("TRITON_OVERRIDE_ARCH") + + launch_enter_hook: HookChain[LaunchHook] = HookChain() + launch_exit_hook: HookChain[LaunchHook] = HookChain(reversed=True) + kernel_load_start_hook: HookChain[InitHandleHook] = HookChain() + kernel_load_end_hook: HookChain[InitHandleHook] = HookChain(reversed=True) + + # Hook for inspecting compiled functions and modules + jit_cache_hook: Optional[JITHook] = None + # Hook to signal that a kernel is done compiling and inspect compiled function. + # jit_cache_hook will always be called before compilation and jit_post_compile_hook after. + jit_post_compile_hook: Optional[JITHook] = None + + +class language_knobs(base_knobs): + fp32_default: env_opt_str = env_opt_str("TRITON_F32_DEFAULT") + default_fp_fusion: env_bool = env_bool("TRITON_DEFAULT_FP_FUSION", True) + + +class nvidia_knobs(base_knobs): + cuobjdump: env_nvidia_tool = env_nvidia_tool("cuobjdump") + nvdisasm: env_nvidia_tool = env_nvidia_tool("nvdisasm") + ptxas: env_nvidia_tool = env_nvidia_tool("ptxas") + + dump_nvptx: env_bool = env_bool("NVPTX_ENABLE_DUMP") + disable_ptxas_opt: env_bool = env_bool("DISABLE_PTXAS_OPT") + mock_ptx_version: env_opt_str = env_opt_str("TRITON_MOCK_PTX_VERSION") + dump_ptxas_log: env_bool = env_bool("TRITON_DUMP_PTXAS_LOG") + + libdevice_path: env_opt_str = env_opt_str("TRITON_LIBDEVICE_PATH") + libcuda_path: env_opt_str = env_opt_str("TRITON_LIBCUDA_PATH") + + +class amd_knobs(base_knobs): + use_buffer_ops: env_bool = env_bool("AMDGCN_USE_BUFFER_OPS") + # Note: This requires use_buffer_ops be true to have any effect + use_buffer_atomics: env_bool = env_bool("AMDGCN_USE_BUFFER_ATOMICS", True) + dump_amdgcn: env_bool = env_bool("AMDGCN_ENABLE_DUMP") + libhip_path: env_opt_str = env_opt_str("TRITON_LIBHIP_PATH") + + # We use strs so that we can have a default value based on other runtime info + use_block_pingpong: env_opt_bool = env_opt_bool("TRITON_HIP_USE_BLOCK_PINGPONG") + use_in_thread_transpose: env_opt_bool = env_opt_bool("TRITON_HIP_USE_IN_THREAD_TRANSPOSE") + + global_prefetch: env_int = env_int("TRITON_HIP_GLOBAL_PREFETCH") + local_prefetch: env_int = env_int("TRITON_HIP_LOCAL_PREFETCH") + use_async_copy: env_bool = env_bool("TRITON_HIP_USE_ASYNC_COPY") + scalarize_packed_fops: env_bool = env_bool("AMDGCN_SCALARIZE_PACKED_FOPS") + + +class proton_knobs(base_knobs): + cupti_dir: env_opt_str = env_opt_str("TRITON_CUPTI_LIB_PATH") + + +build = build_knobs() +redis = redis_knobs() +cache = cache_knobs() +compilation = compilation_knobs() +autotuning = autotuning_knobs() +runtime = runtime_knobs() +language = language_knobs() +nvidia = nvidia_knobs() +amd = amd_knobs() +proton = proton_knobs() + + +def refresh_knobs(): + runtime.debug = env_bool("TRITON_DEBUG").get() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..27430b247190ec041fcaa4a81cd92cfd7a0cb92e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__init__.py @@ -0,0 +1,342 @@ +"""isort:skip_file""" +# Import order is significant here. + +from . import math +from . import extra +from .standard import ( + argmax, + argmin, + bitonic_merge, + cdiv, + cumprod, + cumsum, + flip, + interleave, + max, + min, + ravel, + reduce_or, + sigmoid, + softmax, + sort, + sum, + swizzle2d, + topk, + xor_sum, + zeros, + zeros_like, +) +from .core import ( + PropagateNan, + TRITON_MAX_TENSOR_NUMEL, + load_tensor_descriptor, + store_tensor_descriptor, + make_tensor_descriptor, + tensor_descriptor, + tensor_descriptor_type, + add, + advance, + arange, + associative_scan, + assume, + async_task, + atomic_add, + atomic_and, + atomic_cas, + atomic_max, + atomic_min, + atomic_or, + atomic_xchg, + atomic_xor, + bfloat16, + block_type, + broadcast, + broadcast_to, + cat, + cast, + clamp, + condition, + const, + constexpr, + constexpr_type, + debug_barrier, + device_assert, + device_print, + dot, + dot_scaled, + dtype, + expand_dims, + float16, + float32, + float64, + float8e4b15, + float8e4nv, + float8e4b8, + float8e5, + float8e5b16, + full, + gather, + histogram, + inline_asm_elementwise, + int1, + int16, + int32, + int64, + int8, + join, + load, + make_block_ptr, + map_elementwise, + max_constancy, + max_contiguous, + maximum, + minimum, + multiple_of, + num_programs, + permute, + pi32_t, + pointer_type, + program_id, + range, + reduce, + reshape, + slice, + split, + static_assert, + static_print, + static_range, + store, + tensor, + trans, + tuple, + tuple_type, + uint16, + uint32, + uint64, + uint8, + view, + void, + where, +) +from .math import (umulhi, exp, exp2, fma, log, log2, cos, rsqrt, sin, sqrt, sqrt_rn, abs, fdiv, div_rn, erf, floor, + ceil) +from .random import ( + pair_uniform_to_normal, + philox, + philox_impl, + rand, + rand4x, + randint, + randint4x, + randn, + randn4x, + uint_to_uniform_float, +) +from . import target_info + +__all__ = [ + "PropagateNan", + "TRITON_MAX_TENSOR_NUMEL", + "load_tensor_descriptor", + "store_tensor_descriptor", + "make_tensor_descriptor", + "tensor_descriptor", + "abs", + "add", + "advance", + "arange", + "argmax", + "argmin", + "associative_scan", + "assume", + "async_task", + "atomic_add", + "atomic_and", + "atomic_cas", + "atomic_max", + "atomic_min", + "atomic_or", + "atomic_xchg", + "atomic_xor", + "bfloat16", + "bitonic_merge", + "block_type", + "broadcast", + "broadcast_to", + "cat", + "cast", + "cdiv", + "ceil", + "clamp", + "condition", + "const", + "constexpr", + "constexpr_type", + "cos", + "cumprod", + "cumsum", + "debug_barrier", + "device_assert", + "device_print", + "div_rn", + "dot", + "dot_scaled", + "dtype", + "erf", + "exp", + "exp2", + "expand_dims", + "extra", + "fdiv", + "flip", + "float16", + "float32", + "float64", + "float8e4b15", + "float8e4nv", + "float8e4b8", + "float8e5", + "float8e5b16", + "floor", + "fma", + "full", + "gather", + "histogram", + "inline_asm_elementwise", + "interleave", + "int1", + "int16", + "int32", + "int64", + "int8", + "join", + "load", + "log", + "log2", + "make_block_ptr", + "map_elementwise", + "math", + "max", + "max_constancy", + "max_contiguous", + "maximum", + "min", + "minimum", + "multiple_of", + "num_programs", + "pair_uniform_to_normal", + "permute", + "philox", + "philox_impl", + "pi32_t", + "pointer_type", + "program_id", + "rand", + "rand4x", + "randint", + "randint4x", + "randn", + "randn4x", + "range", + "ravel", + "reduce", + "reduce_or", + "reshape", + "rsqrt", + "slice", + "sigmoid", + "sin", + "softmax", + "sort", + "split", + "sqrt", + "sqrt_rn", + "static_assert", + "static_print", + "static_range", + "store", + "sum", + "swizzle2d", + "target_info", + "tensor", + "topk", + "trans", + "tuple", + "uint16", + "uint32", + "uint64", + "uint8", + "uint_to_uniform_float", + "umulhi", + "view", + "void", + "where", + "xor_sum", + "zeros", + "zeros_like", +] + + +def str_to_ty(name, c): + from builtins import tuple + + if isinstance(name, tuple): + fields = type(name).__dict__.get("_fields", None) + return tuple_type([str_to_ty(x, c) for x in name], fields) + + if name[0] == "*": + name = name[1:] + const = False + if name[0] == "k": + name = name[1:] + const = True + ty = str_to_ty(name, c) + return pointer_type(element_ty=ty, const=const) + + if name.startswith("tensordesc"): + inner = name.split("<")[1].rstrip(">") + dtype, rest = inner.split("[", maxsplit=1) + block_shape, rest = rest.split("]", maxsplit=1) + block_shape = [int(s.strip()) for s in block_shape.rstrip("]").split(",")] + layout = rest.lstrip(",") + is_gluon = len(layout) + dtype = str_to_ty(dtype, None) + ndim = len(block_shape) + shape_type = tuple_type([int32] * ndim) + # FIXME: Last dim stride should be constexpr(1) + stride_type = tuple_type(([int64] * ndim)) + block = block_type(dtype, block_shape) + if is_gluon: + from triton.experimental.gluon.language._layouts import NVMMASharedLayout + from triton.experimental.gluon.language.nvidia.hopper.tma import tensor_descriptor_type as gluon_tensor_descriptor_type + layout = eval(layout, dict(NVMMASharedLayout=NVMMASharedLayout)) + assert isinstance(layout, NVMMASharedLayout) + return gluon_tensor_descriptor_type(block, shape_type, stride_type, layout) + return tensor_descriptor_type(block, shape_type, stride_type) + + if name.startswith("constexpr"): + return constexpr_type(c) + + tys = { + "fp8e4nv": float8e4nv, + "fp8e4b8": float8e4b8, + "fp8e5": float8e5, + "fp8e5b16": float8e5b16, + "fp8e4b15": float8e4b15, + "fp16": float16, + "bf16": bfloat16, + "fp32": float32, + "fp64": float64, + "i1": int1, + "i8": int8, + "i16": int16, + "i32": int32, + "i64": int64, + "u1": int1, + "u8": uint8, + "u16": uint16, + "u32": uint32, + "u64": uint64, + "B": int1, + } + return tys[name] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..046c7528818541a6e76c413f6658a7beeb88dc87 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__pycache__/math.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__pycache__/math.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..177cd54d7b93c0f21b269225b778461e31272c18 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__pycache__/math.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__pycache__/random.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__pycache__/random.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1da7bf14c2b4dca9b7fa06d3cece1b1659e80cf Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__pycache__/random.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__pycache__/standard.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__pycache__/standard.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8776fc168fbcb92691e39ffde96e13eeaab60deb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__pycache__/standard.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__pycache__/target_info.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__pycache__/target_info.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e85f3b647c6c3e642eb33b60aa615b2e5f3bdcf0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/__pycache__/target_info.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/core.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/core.py new file mode 100644 index 0000000000000000000000000000000000000000..2952aed8777be6ed85bc40712be20bb3f3cb2204 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/core.py @@ -0,0 +1,3405 @@ +from __future__ import annotations + +import math +from warnings import warn +from contextlib import contextmanager +from enum import Enum +from functools import partial, wraps +import typing +from typing import Union, Callable, List, Sequence, TypeVar, Optional, Tuple +from dataclasses import dataclass +import builtins +from .. import knobs +from ..runtime.jit import JITCallable +import inspect + +from .._C.libtriton import ir +from .._utils import TRITON_MAX_TENSOR_NUMEL, validate_block_shape, get_primitive_bitwidth + +T = TypeVar('T') + +TRITON_BUILTIN = "__triton_builtin__" + +PropagateNan = ir.PROPAGATE_NAN + + +def must_use_result(x, s=True): + """If the result of this function is unused, throw an error.""" + if isinstance(x, str): + return (lambda fn: must_use_result(fn, x)) + x._must_use_result = s + return x + + +def builtin(fn: T) -> T: + """Mark a function as a builtin.""" + assert callable(fn) + + @wraps(fn) + def wrapper(*args, **kwargs): + if "_semantic" not in kwargs or kwargs["_semantic"] is None: + raise ValueError("Did you forget to add @triton.jit ? " + "(`_semantic` argument must be provided outside of JIT functions.)") + return fn(*args, **kwargs) + + setattr(wrapper, TRITON_BUILTIN, True) + + return wrapper + + +def _tensor_member_fn(fn: T) -> T: + """Decorator that adds this free function as a member fn on class tensor. + + When called as a member function on class tensor, the first argument to `fn` + is `self`, i.e. the tensor object. + + If there are multiple decorators on a function, you probably want this one + to be the highest one (i.e. furthest from the function's `def`), so it's + applied last. + + Unfortunately you still need to add a type stub to the body of class tensor + in order for pytype to know about it. + """ + assert callable(fn) + orig_sig = inspect.signature(fn) + # Does fn take args other than _semantic, _generator, and the tensor itself? + has_args = len(orig_sig.parameters.keys() - {"_semantic", "_generator"}) > 1 + + if not fn.__doc__: + fn.__doc__ = "" + fn.__doc__ += f""" + This function can also be called as a member function on :py:class:`tensor`, + as :code:`x.{fn.__name__}({"..." if has_args else ""})` instead of + :code:`{fn.__name__}(x{", ..." if has_args else ""})`. + """ + + def wrapper(*args, **kwargs): + return fn(*args, **kwargs) + + # Match the signature of `fn`, but change the first arg to `self` so the + # docs are a little less weird. + new_params = list(orig_sig.parameters.values()) + new_params[0] = new_params[0].replace(name='self') + new_sig = orig_sig.replace(parameters=new_params) + wrapper.__signature__ = new_sig + wrapper.__doc__ = f"Forwards to :py:func:`{fn.__name__}` free function" + # If fn is a builtin, mark the wrapper as a builtin too. + if is_builtin(fn): + setattr(wrapper, TRITON_BUILTIN, True) + + setattr(tensor, fn.__name__, fn if isinstance(fn, JITCallable) else wrapper) + return fn + + +def _unwrap_iterable(x): + """Returns x[0] if x has one element and x[0] is iterable.""" + if len(x) == 1: + # Determine whether x[0] is iterable. + # + # You might want to use collections.abc.Iterable instead of this + # try/except block. Unfortunately, this doesn't work with constexpr. + # + # The problem is that abc.Iterable checks for __iter__ on the *class*. + # But we want constexpr to expose an __iter__ method if and only if the + # wrapped *object* (i.e. self.value) is iterable. Therefore there's no + # right answer for whether the class constexpr defines __iter__, and + # abc.Iterable doesn't work (at least not without some metaclass magic). + try: + iter(x[0]) + return x[0] + except TypeError: + pass + + return x + + +def is_builtin(fn) -> bool: + """Is this a registered triton builtin function?""" + return getattr(fn, TRITON_BUILTIN, False) + + +@builtin +def to_tensor(x, _semantic=None): + return _semantic.to_tensor(x) + + +# ----------------------- +# constexpr +# ----------------------- + + +class const: + """ + This class is used as a type annotation to mark pointers to constant data. + The `store` function cannot be called with a pointer to const. Constness + is part of the pointer type and the usual Triton type consistency rules + apply. For example you cannot have a function that returns constant pointer + in one return statement and non-constant pointer in another. + """ + pass + + +class base_value: + """Base class of values that exist in the triton IR (i.e. not constexprs). + """ + type: base_type + + def _flatten_ir(self, handles: List[ir.value]) -> None: + """Flatten frontend value into a sequence of mlir handles, which are appended + to the output list + """ + raise NotImplementedError + + +class base_type: + + def __eq__(self, other) -> bool: + raise NotImplementedError("Types must implement __eq__") + + def __ne__(self, other) -> bool: + return not (self == other) + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[base_value, int]: + """Build a frontend value with the current dtype, wrapping a list of existing handles. + cursor is the index of the first handle relevant to this value, and the function + should return the updated cursor position after any handles consumed by the created value. + """ + raise NotImplementedError + + def mangle(self) -> str: + raise NotImplementedError(f"NYI: Type mangling for type {self.__class__}") + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + raise NotImplementedError + + +class constexpr_type(base_type): + + def __init__(self, value): + self.value = value + + def __eq__(self, other): + return isinstance(other, constexpr_type) and self.value == other.value + + def __repr__(self) -> str: + return f"constexpr_type[{self.value}]" + + def __hash__(self): + return hash(self.value) + + def mangle(self) -> str: + return repr(self) + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + return + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[base_value, int]: + return constexpr(self.value), cursor + + +class constexpr(base_value): + """ + This class is used to store a value that is known at compile-time. + """ + + def __init__(self, value): + while isinstance(value, constexpr): + value = value.value + self.value = value + self.type = constexpr_type(value) + + def __repr__(self) -> str: + return f"constexpr[{self.value}]" + + def __hash__(self): + return hash((self.value, self.type)) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + return + + def __index__(self): + return self.value + + # In interpreter mode, constant values are not wrapped in constexpr, + # and therefore do not have a .value attribute. + # As a result, from here and below, we need to call the _unwrap_if_constexpr + # function to obtain either constexpr.value or the value itself. + def __add__(self, other): + return constexpr(self.value + _unwrap_if_constexpr(other)) + + def __radd__(self, other): + return constexpr(_unwrap_if_constexpr(other) + self.value) + + def __sub__(self, other): + return constexpr(self.value - _unwrap_if_constexpr(other)) + + def __rsub__(self, other): + return constexpr(_unwrap_if_constexpr(other) - self.value) + + def __mul__(self, other): + return constexpr(self.value * _unwrap_if_constexpr(other)) + + def __mod__(self, other): + return constexpr(self.value % _unwrap_if_constexpr(other)) + + def __rmul__(self, other): + return constexpr(_unwrap_if_constexpr(other) * self.value) + + def __truediv__(self, other): + return constexpr(self.value / _unwrap_if_constexpr(other)) + + def __rtruediv__(self, other): + return constexpr(_unwrap_if_constexpr(other) / self.value) + + def __floordiv__(self, other): + return constexpr(self.value // _unwrap_if_constexpr(other)) + + def __rfloordiv__(self, other): + return constexpr(_unwrap_if_constexpr(other) // self.value) + + def __gt__(self, other): + return constexpr(self.value > _unwrap_if_constexpr(other)) + + def __rgt__(self, other): + return constexpr(_unwrap_if_constexpr(other) > self.value) + + def __ge__(self, other): + return constexpr(self.value >= _unwrap_if_constexpr(other)) + + def __rge__(self, other): + return constexpr(_unwrap_if_constexpr(other) >= self.value) + + def __lt__(self, other): + return constexpr(self.value < _unwrap_if_constexpr(other)) + + def __rlt__(self, other): + return constexpr(_unwrap_if_constexpr(other) < self.value) + + def __le__(self, other): + return constexpr(self.value <= _unwrap_if_constexpr(other)) + + def __rle__(self, other): + return constexpr(_unwrap_if_constexpr(other) <= self.value) + + def __eq__(self, other): + return constexpr(self.value == _unwrap_if_constexpr(other)) + + def __ne__(self, other): + return constexpr(self.value != _unwrap_if_constexpr(other)) + + def __bool__(self): + return bool(self.value) + + def __neg__(self): + return constexpr(-self.value) + + def __and__(self, other): + return constexpr(self.value & _unwrap_if_constexpr(other)) + + def logical_and(self, other): + return constexpr(self.value and _unwrap_if_constexpr(other)) + + def __or__(self, other): + return constexpr(self.value | _unwrap_if_constexpr(other)) + + def __xor__(self, other): + return constexpr(self.value ^ _unwrap_if_constexpr(other)) + + def logical_or(self, other): + return constexpr(self.value or _unwrap_if_constexpr(other)) + + def __pos__(self): + return constexpr(+self.value) + + def __invert__(self): + return constexpr(~self.value) + + def __pow__(self, other): + return constexpr(self.value**_unwrap_if_constexpr(other)) + + def __rpow__(self, other): + return constexpr(_unwrap_if_constexpr(other)**self.value) + + def __rshift__(self, other): + return constexpr(self.value >> _unwrap_if_constexpr(other)) + + def __lshift__(self, other): + return constexpr(self.value << _unwrap_if_constexpr(other)) + + def __not__(self): + return constexpr(not self.value) + + def __iter__(self): + return iter(self.value) + + def __call__(self, *args, **kwds): + return self.value(*args, **kwds) + + def __getitem__(self, *args): + args = (_unwrap_if_constexpr(x) for x in _normalize_tuple(args)) + return self.value.__getitem__(*args) + + +CONSTEXPR_0 = constexpr(0) + + +def _unwrap_if_constexpr(o): + if isinstance(o, list): + return [_unwrap_if_constexpr(x) for x in o] + if isinstance(o, builtins.tuple): + return builtins.tuple(_unwrap_if_constexpr(x) for x in o) + if isinstance(o, tuple): + return tuple(_unwrap_if_constexpr(x) for x in o) + return o.value if isinstance(o, constexpr) else o + + +def _normalize_tuple(t): + normalized_tuple = _unwrap_if_constexpr(t) + if isinstance(normalized_tuple, (list, builtins.tuple)): + normalized_tuple = tuple(normalized_tuple) + return normalized_tuple + + +def check_bit_width(value, shift_value): + if isinstance(value, tensor) and isinstance(shift_value, constexpr): + bitwidth = value.type.scalar.primitive_bitwidth + if shift_value.value >= bitwidth: + warn( + f"Value {shift_value.value} exceeds the maximum bitwidth ({bitwidth}) for type '{value.dtype}'. This may result in undefined behavior." + ) + + +# ----------------------- +# dtype +# ----------------------- + + +class dtype(base_type): + SINT_TYPES = ['int8', 'int16', 'int32', 'int64'] + UINT_TYPES = ['int1', 'uint8', 'uint16', 'uint32', 'uint64'] + FP_TYPES = ['fp8e4b15', 'fp8e4nv', 'fp8e4b8', 'fp8e5', 'fp8e5b16', 'fp16', 'bf16', 'fp32', 'fp64'] + STANDARD_FP_TYPES = ['fp16', 'bf16', 'fp32', 'fp64'] + OTHER_TYPES = ['void'] + + class SIGNEDNESS(Enum): + SIGNED = 0 + UNSIGNED = 1 + + class KIND(Enum): + BOOLEAN = 0 + INTEGRAL = 1 + FLOATING = 2 + + def __init__(self, name): + name = _unwrap_if_constexpr(name) + self.name = name + assert name in dtype.SINT_TYPES + dtype.UINT_TYPES + dtype.FP_TYPES + dtype.OTHER_TYPES, name + self.primitive_bitwidth = get_primitive_bitwidth(name) + self.itemsize = self.primitive_bitwidth // 8 + if name in dtype.SINT_TYPES: + self.int_signedness = dtype.SIGNEDNESS.SIGNED + self.int_bitwidth = self.primitive_bitwidth + elif name in dtype.UINT_TYPES: + self.int_signedness = dtype.SIGNEDNESS.UNSIGNED + self.int_bitwidth = self.primitive_bitwidth + elif name in dtype.FP_TYPES: + if name == 'fp8e4b15': + self.fp_mantissa_width = 3 + self.exponent_bias = 15 + elif name == 'fp8e4nv': + self.fp_mantissa_width = 3 + self.exponent_bias = 7 + elif name == 'fp8e4b8': + self.fp_mantissa_width = 3 + self.exponent_bias = 8 + elif name == 'fp8e5': + self.fp_mantissa_width = 2 + self.exponent_bias = 15 + elif name == 'fp8e5b16': + self.fp_mantissa_width = 2 + self.exponent_bias = 16 + elif name == 'fp16': + self.fp_mantissa_width = 10 + self.exponent_bias = 15 + elif name == 'bf16': + self.fp_mantissa_width = 7 + self.exponent_bias = 127 + elif name == 'fp32': + self.fp_mantissa_width = 23 + self.exponent_bias = 127 + elif name == 'fp64': + self.fp_mantissa_width = 52 + self.exponent_bias = 1023 + else: + raise RuntimeError(f'Unsupported floating-point type {name}') + + def is_fp8(self): + return 'fp8' in self.name + + def is_fp8e4nv(self): + return self.name == 'fp8e4nv' + + def is_fp8e4b8(self): + return self.name == 'fp8e4b8' + + def is_fp8e4b15(self): + return self.name == 'fp8e4b15' + + def is_fp8e5(self): + return self.name == 'fp8e5' + + def is_fp8e5b16(self): + return self.name == 'fp8e5b16' + + def is_fp16(self): + return self.name == 'fp16' + + def is_bf16(self): + return self.name == 'bf16' + + def is_fp32(self): + return self.name == 'fp32' + + def is_fp64(self): + return self.name == 'fp64' + + def is_int1(self): + return self.name == 'int1' + + def is_int8(self): + return self.name == 'int8' + + def is_int16(self): + return self.name == 'int16' + + def is_int32(self): + return self.name == 'int32' + + def is_int64(self): + return self.name == 'int64' + + def is_uint8(self): + return self.name == 'uint8' + + def is_uint16(self): + return self.name == 'uint16' + + def is_uint32(self): + return self.name == 'uint32' + + def is_uint64(self): + return self.name == 'uint64' + + def is_floating(self): + return self.name in dtype.FP_TYPES + + def is_standard_floating(self): + return self.name in dtype.STANDARD_FP_TYPES + + def is_int_signed(self): + return self.name in dtype.SINT_TYPES + + def is_int_unsigned(self): + return self.name in dtype.UINT_TYPES + + def is_int(self): + return self.name in dtype.SINT_TYPES + dtype.UINT_TYPES + + def is_bool(self): + return self.is_int1() + + def kind(self): + # Return int value following the type ordering bool < integer < fp + if self.is_bool(): + return dtype.KIND.BOOLEAN + elif self.is_int(): + return dtype.KIND.INTEGRAL + else: + assert self.is_floating() + return dtype.KIND.FLOATING + + def get_int_max_value(self): + if self.is_int_signed(): + return 2**(self.int_bitwidth - 1) - 1 + if self.is_int_unsigned(): + return 2**self.int_bitwidth - 1 + assert False + + def get_int_min_value(self): + if self.is_int_signed(): + return -2**(self.int_bitwidth - 1) + if self.is_int_unsigned(): + return 0 + assert False + + @staticmethod + def is_dtype(type_str): + return type_str in dtype.SINT_TYPES + dtype.UINT_TYPES + dtype.FP_TYPES + dtype.OTHER_TYPES + + @staticmethod + def is_void(): + raise RuntimeError("Not implemented") + + @staticmethod + def is_block(): + return False + + @staticmethod + def is_ptr(): + return False + + @staticmethod + def is_const(): + return False + + def __eq__(self, other) -> bool: + other = _unwrap_if_constexpr(other) + if not isinstance(other, dtype): + return False + return self.name == other.name + + def __hash__(self): + return hash((self.name, )) + + @property + def scalar(self): + return self + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + out.append(self.to_ir(builder)) + + def to_ir(self, builder: ir.builder) -> ir.type: + if self.name.startswith("fp8"): + if self.name not in builder.options.supported_fp8_dtypes: + raise ValueError(f'type {self} not supported in this architecture. ' + f'The supported fp8 dtypes are {builder.options.supported_fp8_dtypes}') + + if self.name == 'void': + return builder.get_void_ty() + elif self.name == 'int1': + return builder.get_int1_ty() + elif self.name in ('int8', 'uint8'): + return builder.get_int8_ty() + elif self.name in ('int16', 'uint16'): + return builder.get_int16_ty() + elif self.name in ('int32', 'uint32'): + return builder.get_int32_ty() + elif self.name in ('int64', 'uint64'): + return builder.get_int64_ty() + elif self.name == 'fp8e5': + return builder.get_fp8e5_ty() + elif self.name == 'fp8e5b16': + return builder.get_fp8e5b16_ty() + elif self.name == 'fp8e4nv': + return builder.get_fp8e4nv_ty() + elif self.name == 'fp8e4b8': + return builder.get_fp8e4b8_ty() + elif self.name == 'fp8e4b15': + return builder.get_fp8e4b15_ty() + elif self.name == 'fp16': + return builder.get_half_ty() + elif self.name == 'bf16': + return builder.get_bf16_ty() + elif self.name == 'fp32': + return builder.get_float_ty() + elif self.name == 'fp64': + return builder.get_double_ty() + raise ValueError(f'fail to convert {self} to ir type') + + def __str__(self): + return self.name + + def codegen_name(self): + if self.name.startswith("fp"): + return "float" + self.name[2:] + elif self.name.startswith("bf"): + return "bfloat" + self.name[2:] + else: + return self.name + + @property + def cache_key_part(self) -> str: + """See cache_key_part() in triton.cc.""" + return self.name + + def __repr__(self): + """Output of repr needs to be an evaluatable expression""" + return f'triton.language.{self.codegen_name()}' + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[base_value, int]: + return tensor(handles[cursor], self), cursor + 1 + + def mangle(self) -> str: + if self.is_int(): + SIGNED = dtype.SIGNEDNESS.SIGNED + prefix = 'i' if self.int_signedness == SIGNED else 'u' + return prefix + str(self.int_bitwidth) + if self.is_floating(): + return str(self) + if self.is_void(): + return 'V' + return super().mangle() + + def with_element_ty(self, element_ty: dtype): + assert not self.is_block() + return element_ty + + +# Some functions have a param named `dtype`, which shadows the `dtype` class. +# We can't change the param name because it is part of function's public API. +# Declare an alias so those functions can still reference the dtype class. +_DtypeClass = dtype + + +class pointer_type(dtype): + + def __init__(self, element_ty: dtype, address_space: int = 1, const: bool = False): + element_ty = _unwrap_if_constexpr(element_ty) + if not isinstance(element_ty, dtype): + raise TypeError(f'element_ty has type `{type(element_ty).__name__}`; expected `dtype`.') + self.element_ty = element_ty + self.address_space = address_space + self.const = const + self.name = f'pointer<{element_ty}>' if not const else f'const_pointer<{element_ty}>' + + def to_ir(self, builder: ir.builder) -> ir.pointer_type: + return builder.get_ptr_ty(self.element_ty.to_ir(builder), self.address_space) + + def __str__(self): + return self.name + + def __repr__(self): + return self.__str__() + + def is_ptr(self): + return True + + def is_const(self): + return self.const + + def __eq__(self, other) -> bool: + other = _unwrap_if_constexpr(other) + if not isinstance(other, pointer_type): + return False + return self.element_ty == other.element_ty and self.address_space == other.address_space and self.const == other.const + + @property + def scalar(self): + return self + + def mangle(self) -> str: + return f"P{self.element_ty.mangle()}" + + +class block_type(dtype): + + def __init__(self, element_ty: dtype, shape: List): + self.element_ty = element_ty + + # Note that block_type's shape is a list of int + # while tensor's shape is a list of constexpr. + assert (isinstance(shape, (list, tuple))) + + # shape can be empty ([]) when an input is a 0D tensor. + self.shape = tuple(_unwrap_shape(shape)) + if not self.shape: + raise TypeError('0d block_type is forbidden') + + self.numel = validate_block_shape(self.shape) + self.name = f'<{self.shape}, {self.element_ty}>' + + def to_ir(self, builder: ir.builder) -> ir.block_type: + return builder.get_block_ty(self.element_ty.to_ir(builder), self.shape) + + def __str__(self): + return self.name + + def __repr__(self): + return self.__str__() + + def is_block(self): + return True + + def get_block_shapes(self) -> Tuple[int]: + return self.shape + + def with_element_ty(self, scalar_ty: dtype) -> block_type: + return block_type(scalar_ty, self.shape) + + def __eq__(self, other) -> bool: + if not isinstance(other, block_type): + return False + return self.element_ty == other.element_ty and self.shape == other.shape + + @property + def scalar(self): + return self.element_ty + + @property + def nbytes(self): + return self.numel * (self.element_ty.primitive_bitwidth // 8) + + def mangle(self) -> str: + elt = self.scalar.mangle() + shape = '_'.join(map(str, self.shape)) + return f'{elt}S{shape}S' + + +class tuple_type(base_type): + + def __init__(self, types, fields=None): + self.types = types + self.fields = fields or [''] * len(types) + self.name = '[' + ','.join([f"{k}:{v}" for k, v in zip(self.fields, self.types)]) + ']' + + def __str__(self): + return self.name + + def __iter__(self): + return iter(self.types) + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]): + for ty in self.types: + if not isinstance(ty, constexpr): + ty._flatten_ir_types(builder, out) + + def __getitem__(self, index: int) -> dtype: + return self.types[index] + + def __eq__(self, other): + return type(self) is type(other) and self.types == other.types and self.fields == other.fields + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[tuple, int]: + values = [] + for ty in self.types: + value, cursor = ty._unflatten_ir(handles, cursor) + values.append(value) + return tuple(values, self), cursor + + def mangle(self): + return 'T' + '_'.join(ty.mangle for ty in self.types) + 'T' + + +class slice_type(dtype): + + def __init__(self): + self.name = 'slice_type' + + +# scalar types +void = dtype('void') +int1 = dtype('int1') +int8 = dtype('int8') +int16 = dtype('int16') +int32 = dtype('int32') +int64 = dtype('int64') +uint8 = dtype('uint8') +uint16 = dtype('uint16') +uint32 = dtype('uint32') +uint64 = dtype('uint64') +float8e5 = dtype('fp8e5') +float8e5b16 = dtype('fp8e5b16') +float8e4nv = dtype('fp8e4nv') +float8e4b8 = dtype('fp8e4b8') +float8e4b15 = dtype('fp8e4b15') +float16 = dtype('fp16') +bfloat16 = dtype('bf16') +float32 = dtype('fp32') +float64 = dtype('fp64') +# pointer types +pi32_t = pointer_type(int32) + + +def get_int_dtype(bitwidth: int, signed: bool) -> dtype: + if bitwidth == 1: + return int1 + elif bitwidth == 8 and signed: + return int8 + elif bitwidth == 8 and not signed: + return uint8 + elif bitwidth == 16 and signed: + return int16 + elif bitwidth == 16 and not signed: + return uint16 + elif bitwidth == 32 and signed: + return int32 + elif bitwidth == 32 and not signed: + return uint32 + elif bitwidth == 64 and signed: + return int64 + elif bitwidth == 64 and not signed: + return uint64 + else: + raise ValueError(f'Unsupported bitwidth {bitwidth} and signedness {signed}') + + +# ----------------------- +# tensor +# ----------------------- + + +class tensor(base_value): + """Represents an N-dimensional array of values or pointers. + + :code:`tensor` is the fundamental data structure in Triton programs. Most + functions in :py:mod:`triton.language` operate on and return tensors. + + Most of the named member functions here are duplicates of the free functions + in :code:`triton.language`. For example, :code:`triton.language.sqrt(x)` is + equivalent to :code:`x.sqrt()`. + + :code:`tensor` also defines most of the magic/dunder methods, so you can + write :code:`x+y`, :code:`x << 2`, etc. + + .. rubric:: Constructors + .. + For some reason Sphinx includes __init__ before printing the full table + of methods. Not what I want, but I can't figure out how to fix it. Give + it its own section so it looks intentional. :) + """ + + def __init__(self, handle, type: dtype): + """Not called by user code.""" + super().__init__() + # IR handle + self.handle = handle + # Block shape + self.shape = type.shape if type.is_block() else () + self.numel = constexpr(math.prod(self.shape)) + self.type = type # Tensor type (can be block_type) + # Following the practice in pytorch, dtype is scalar type + self.dtype = type.scalar + self.shape = tuple([constexpr(s) for s in self.shape]) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + handles.append(self.handle) + + def __str__(self) -> str: + # ex. "float32[16, 32]" + return str(self.dtype) + '[' + ', '.join(str(s) for s in self.shape) + ']' + + @builtin + def __add__(self, other, _semantic=None): + return add(self, other, sanitize_overflow=True, _semantic=_semantic) + + @builtin + def __radd__(self, other, _semantic=None): + return add(other, self, sanitize_overflow=True, _semantic=_semantic) + + @builtin + def __sub__(self, other, _semantic=None): + return sub(self, other, sanitize_overflow=True, _semantic=_semantic) + + @builtin + def __rsub__(self, other, _semantic=None): + return sub(other, self, sanitize_overflow=True, _semantic=_semantic) + + @builtin + def __mul__(self, other, _semantic=None): + return mul(self, other, sanitize_overflow=True, _semantic=_semantic) + + @builtin + def __rmul__(self, other, _semantic=None): + return mul(other, self, sanitize_overflow=True, _semantic=_semantic) + + @builtin + def __truediv__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.truediv(self, other) + + @builtin + def __rtruediv__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.truediv(other, self) + + @builtin + def __floordiv__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.floordiv(self, other) + + @builtin + def __rfloordiv__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.floordiv(other, self) + + @builtin + def __mod__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.mod(self, other) + + @builtin + def __rmod__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.mod(other, self) + + # unary operators + @builtin + def __neg__(self, _semantic=None): + return _semantic.minus(self) + + @builtin + def __invert__(self, _semantic=None): + return _semantic.invert(self) + + # bitwise operators + + @builtin + def __and__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.and_(self, other) + + @builtin + def __rand__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.and_(other, self) + + @builtin + def __or__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.or_(self, other) + + @builtin + def __ror__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.or_(other, self) + + @builtin + def __xor__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.xor_(self, other) + + @builtin + def __rxor__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.xor_(other, self) + + @builtin + def __lshift__(self, other, _semantic=None): + check_bit_width(self, other) + other = _unwrap_if_constexpr(other) + return _semantic.shl(self, other) + + @builtin + def __rlshift__(self, other, _semantic=None): + check_bit_width(other, self) + other = _unwrap_if_constexpr(other) + return _semantic.shl(other, self) + + @builtin + def __rshift__(self, other, _semantic=None): + check_bit_width(self, other) + other = _unwrap_if_constexpr(other) + if self.dtype.is_int_signed(): + return _semantic.ashr(self, other) + else: + return _semantic.lshr(self, other) + + @builtin + def __rrshift__(self, other, _semantic=None): + check_bit_width(other, self) + other = _unwrap_if_constexpr(other) + if self.dtype.is_int_signed(): + return _semantic.ashr(other, self) + else: + return _semantic.lshr(other, self) + + # > + @builtin + def __gt__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.greater_than(self, other) + + @builtin + def __rgt__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.greater_than(other, self) + + # >= + @builtin + def __ge__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.greater_equal(self, other) + + @builtin + def __rge__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.greater_equal(other, self) + + # < + @builtin + def __lt__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.less_than(self, other) + + @builtin + def __rlt__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.less_than(other, self) + + # <= + @builtin + def __le__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.less_equal(self, other) + + @builtin + def __rle__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.less_equal(other, self) + + # == + @builtin + def __eq__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.equal(self, other) + + @builtin + def __req__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.equal(other, self) + + @builtin + def __ne__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.not_equal(self, other) + + @builtin + def __rne__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.not_equal(other, self) + + @builtin + def logical_and(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.logical_and(self, other) + + @builtin + def logical_or(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.logical_or(self, other) + + # note: __not__ isn't actually a magic method in python + # but it's ok because our ASTVisitor handles it + @builtin + def __not__(self, _semantic=None): + return _semantic.not_(self) + + @builtin + def __getitem__(self, slices, _semantic=None): + if isinstance(slices, (builtins.slice, slice, constexpr)) or slices is None: + slices = [slices] + if isinstance(slices, tuple): + slices = slices.values + ret = self + for dim, sl in enumerate(slices): + if _unwrap_if_constexpr(sl) is None: + ret = _semantic.expand_dims(ret, dim) + elif isinstance(sl, (builtins.slice, slice)) and all( + _unwrap_if_constexpr(arg) is None for arg in (sl.start, sl.stop, sl.step)): + pass # an unsqueeze + else: + raise ValueError(f"unsupported tensor index: {sl}") + return ret + + @property + def T(self): + """Transposes a 2D tensor.""" + assert False, "Transposition must be created by the AST Visitor" + + @builtin + def to(self, dtype: dtype, fp_downcast_rounding: Optional[str] = None, bitcast: bool = False, _semantic=None): + """ + Alias for :py:func:`tensor.cast`. + """ + return cast(self, dtype, fp_downcast_rounding, bitcast, _semantic=_semantic) + + # Type stubs for functions added by the _tensor_member_fn decorator. + # (Unfortunately these can't be created automatically.) + # + # We couldn't write these definitions out even if we wanted to, because some + # of these functions are defined in standard.py. + def broadcast_to(self, *shape) -> tensor: + ... + + def trans(self, *dims) -> tensor: + ... + + def permute(self, *dims) -> tensor: + ... + + def split(self) -> tuple[tensor, tensor]: + ... + + def view(self, *shape) -> tensor: + ... + + def reshape(self, *shape) -> tensor: + ... + + def expand_dims(self, axis) -> tensor: + ... + + def cast(self, dtype, fp_downcast_rounding=None, bitcast=False) -> tensor: + ... + + def store(self, value, mask=None, boundary_check=(), cache_modifier="", eviction_policy="") -> tensor: + ... + + def advance(self, offsets) -> tensor: + ... + + def atomic_cas(self, cmp, val, sem=None, scope=None) -> tensor: + ... + + def atomic_xchg(self, val, mask=None, sem=None, scope=None) -> tensor: + ... + + def atomic_add(self, val, mask=None, sem=None, scope=None) -> tensor: + ... + + def atomic_max(self, val, mask=None, sem=None, scope=None) -> tensor: + ... + + def atomic_min(self, val, mask=None, sem=None, scope=None) -> tensor: + ... + + def atomic_and(self, val, mask=None, sem=None, scope=None) -> tensor: + ... + + def atomic_or(self, val, mask=None, sem=None, scope=None) -> tensor: + ... + + def atomic_xor(self, val, mask=None, sem=None, scope=None) -> tensor: + ... + + def exp(self) -> tensor: + ... + + def log(self) -> tensor: + ... + + def cos(self) -> tensor: + ... + + def sin(self) -> tensor: + ... + + def sqrt(self) -> tensor: + ... + + def rsqrt(self) -> tensor: + ... + + def abs(self) -> tensor: + ... + + def reduce(self, axis, combine_fn, keep_dims=False) -> tensor: + ... + + def associative_scan(self, axis, combine_fn, reverse=False) -> tensor: + ... + + def gather(self, indices, axis) -> tensor: + ... + + def histogram(self, num_bins) -> tensor: + ... + + def cdiv(self, div) -> tensor: + ... + + def sigmoid(self) -> tensor: + ... + + def softmax(self, dim=None, keep_dims=False, ieee_rounding=False) -> tensor: + ... + + def ravel(self) -> tensor: + ... + + def max(self, axis=None, return_indices=False, return_indices_tie_break_left=True, keep_dims=False) -> tensor: + ... + + def argmax(self, axis, tie_break_left=True, keep_dims=False) -> tensor: + ... + + def min(self, axis=None, return_indices=False, return_indices_tie_break_left=True, keep_dims=False) -> tensor: + ... + + def argmin(self, axis, tie_break_left=True, keep_dims=False) -> tensor: + ... + + def sum(self, axis=None, keep_dims=False, dtype=None) -> tensor: + ... + + def xor_sum(self, axis=None, keep_dims=False) -> tensor: + ... + + def reduce_or(self, axis=None, keep_dims=False) -> tensor: + ... + + def cumsum(self, axis=0, reverse=False) -> tensor: + ... + + def cumprod(self, axis=0, reverse=False) -> tensor: + ... + + def sort(self, dim: constexpr = None, descending: constexpr = CONSTEXPR_0) -> tensor: + ... + + def flip(self, dim=None) -> tensor: + ... + + +def _type_for_tuple_values(values, fields=None): + return tuple_type([constexpr_type(x) if isinstance(x, (int, float, dtype)) else x.type for x in values], fields) + + +class tuple(base_value): + + def __init__(self, args: Sequence, type: Optional[tuple_type] = None): + self.values = [i for i in args] + if isinstance(type, tuple_type): + self.type = type + elif type is not None: # make_template in ASTFunction.deserialize may pass us a list/tuple + self.type = tuple_type(type) + else: + self.type = _type_for_tuple_values(self.values) + + def __getitem__(self, idx: constexpr): + if isinstance(idx, int): + idx = constexpr(idx) + if isinstance(idx, constexpr): + return self.values[idx] + else: + assert isinstance(idx, (slice, builtins.slice)) + return tuple(self.values[idx.start:idx.stop:idx.step]) + + def __getattr__(self, name): + return self.values[self.type.fields.index(name)] + + # TODO: remove + def _setitem(self, idx, value): + idx = _unwrap_if_constexpr(idx) + assert isinstance(idx, int) + self.values[idx] = value + self.type = _type_for_tuple_values(self.values, self.type.fields) + + def __add__(self, other): + other = _normalize_tuple(other) + return tuple(self.values + other.values) + # return tuple(a + b for a, b in zip(self.values, other.values)) + + def __mul__(self, other): + assert isinstance(other, constexpr) + return tuple(self.values * other.value) + + def __eq__(self, other): + other = _normalize_tuple(other) + return constexpr(self.values == other.values) + + def __hash__(self): + return hash(builtins.tuple(self.values)) + + def __str__(self): + return str([str(x) for x in self.values]) + + def __iter__(self): + return iter(self.values) + + def __len__(self): + return len(self.values) + + def _flatten_ir(self, handles: List[ir.value]): + for v in self.values: + v._flatten_ir(handles) + + def __repr__(self): + return f"({' ,'.join(repr(x) for x in self.values)})" + + +class slice: + + def __init__(self, start, stop, step): + self.start = start + self.stop = stop + self.step = step + self.type = slice_type() + + +class tensor_descriptor_base_type(base_type): + + def __init__(self, block_type: block_type): + self.block_type = block_type + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[tensor_descriptor_base, int]: + value = tensor_descriptor_base(handles[cursor], self.block_type) + return value, cursor + 1 + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + is_signed = self.block_type.element_ty.is_int_signed() + out.append(builder.create_tensor_descriptor_type(self.block_type.to_ir(builder), is_signed)) + + def __str__(self) -> str: + # ex. "tensor_descriptor" + return f"tensor_descriptor<{self.block_type}>" + + def __eq__(self, other) -> bool: + if type(other) is not type(self): + return False + return self.block_type == other.block_type + + def __neq__(self, other) -> bool: + return not (self == other) + + def mangle(self) -> str: + return f"TD{self.block_type.mangle()}" + + +class tensor_descriptor_base(base_value): + """" + A tensor descriptor with unknown shape and strides + """ + + def __init__(self, handle, block_type: block_type): + """Not called by user code.""" + super().__init__() + + self.handle = handle # IR handle + self.type = tensor_descriptor_base_type(block_type) # Tensor type (block_type) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + handles.append(self.handle) + + @property + def block_type(self): + return self.type.block_type + + @property + def block_shape(self): + return self.type.block_type.shape + + @property + def dtype(self): + return self.type.block_type.element_ty + + def __str__(self) -> str: + return str(self.type) + + @builtin + def load(self, offsets: Sequence[constexpr | tensor], _semantic=None) -> tensor: + """Load a block from the descriptor starting at the given element offsets. + + Values outside of the tensor bounds will be filled with zeros. + + :note: Offset must be a multiple of 16-bytes + """ + return _semantic.descriptor_load(self, offsets, "", "") + + @builtin + def store(self, offsets: Sequence[constexpr | tensor], value: tensor, _semantic=None) -> tensor: + """Store a block from the descriptor starting at the given element offsets. + + Values outside of the tensor bounds will be ignored. + + :note: Offset must be a multiple of 16-bytes + """ + return _semantic.descriptor_store(self, value, offsets) + + @builtin + def atomic_add(self, offsets: Sequence[constexpr | tensor], value: tensor, _semantic=None) -> tensor: + return _semantic.descriptor_atomic_add(self, value, offsets) + + @builtin + def atomic_min(self, offsets: Sequence[constexpr | tensor], value: tensor, _semantic=None) -> tensor: + return _semantic.descriptor_atomic_min(self, value, offsets) + + @builtin + def atomic_max(self, offsets: Sequence[constexpr | tensor], value: tensor, _semantic=None) -> tensor: + return _semantic.descriptor_atomic_max(self, value, offsets) + + @builtin + def atomic_and(self, offsets: Sequence[constexpr | tensor], value: tensor, _semantic=None) -> tensor: + return _semantic.descriptor_atomic_and(self, value, offsets) + + @builtin + def atomic_or(self, offsets: Sequence[constexpr | tensor], value: tensor, _semantic=None) -> tensor: + return _semantic.descriptor_atomic_or(self, value, offsets) + + @builtin + def atomic_xor(self, offsets: Sequence[constexpr | tensor], value: tensor, _semantic=None) -> tensor: + return _semantic.descriptor_atomic_xor(self, value, offsets) + + @builtin + def gather(self, *args, _semantic=None) -> tensor: + """Gather multiple descriptors worth of data""" + assert len(args) == 2, f"descriptor gather only supports 2D indexing, but got {len(args)}" + x_offsets = args[0] + y_offset = args[1] + return _semantic.descriptor_gather(self, x_offsets, y_offset, "", "") + + @builtin + def scatter(self, value, *args, _semantic=None) -> tensor: + """Scatter multiple descriptors worth of data""" + assert len(args) == 2, f"descriptor scatter only supports 2D indexing, but got {len(args)}" + x_offsets = args[0] + y_offset = args[1] + return _semantic.descriptor_scatter(self, value, x_offsets, y_offset) + + +class tensor_descriptor_type(tensor_descriptor_base_type): + + def __init__(self, block_type: block_type, shape_type: tuple_type, strides_type: tuple_type): + self.block_type = block_type + self.shape_type = shape_type + self.strides_type = strides_type + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[tensor_descriptor_base, int]: + handle = handles[cursor] + cursor += 1 + shape, cursor = self.shape_type._unflatten_ir(handles, cursor) + strides, cursor = self.strides_type._unflatten_ir(handles, cursor) + shape = shape.values + strides = strides.values + value = tensor_descriptor(handle, shape, strides, self.block_type) + return value, cursor + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + super()._flatten_ir_types(builder, out) + self.shape_type._flatten_ir_types(builder, out) + self.strides_type._flatten_ir_types(builder, out) + + def __eq__(self, other): + return super().__eq__(other) and (self.shape_type == other.shape_type) and (self.strides_type + == other.strides_type) + + +class tensor_descriptor(tensor_descriptor_base): + """A descriptor representing a tensor in global memory. + """ + + def __init__(self, handle, shape: List[tensor], strides: List[tensor], block_type: block_type): + """Not called by user code.""" + # IR handle + super().__init__(handle, block_type) + # Global shape + self.shape = tuple(shape) + self.strides = tuple(strides) + self.type = tensor_descriptor_type( + block_type, + shape_type=self.shape.type, + strides_type=self.strides.type, + ) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + handles.append(self.handle) + self.shape._flatten_ir(handles) + self.strides._flatten_ir(handles) + + +# ----------------------- +# aggregate +# ----------------------- + + +@dataclass(frozen=True) +class _aggregate_type(base_type): + """A generic base type for all Triton aggregate types. + + This class contains a reference to the original user-defined Python class + and a list of class fields with their Triton types. + """ + + base_cls: type + fields: List[Tuple[str, base_type]] + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[ir.value, int]: + instance = self.base_cls._get_instance() + for name, ty in self.fields: + value, cursor = ty._unflatten_ir(handles, cursor) + setattr(instance, name, value) + return instance, cursor + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + for name, ty in self.fields: + ty._flatten_ir_types(builder, out) + + def mangle(self) -> str: + name = f"{self.base_cls.__module__}.{self.base_cls.__qualname__}" + fields = [ty.mangle() for (name, ty) in self.fields] + return f"{name}<{', '.join(fields)}>" + + +def _aggregate(cls): + + # Define the wrapped Triton value type. + class aggregate_value(base_value): + __triton_builtin__ = True + __triton_aggregate__ = True + + @classmethod + def _get_instance(this_cls): + return super().__new__(this_cls) + + def __new__(this_cls, *args, _semantic=None, _generator=None, **kwargs): + # Call into the user-defined constructor. + instance = this_cls._get_instance() + if isinstance(cls.__init__, JITCallable): + raise ValueError(f"{cls.__name__}.__init__ cannot be a @triton.jit function") + extra_kwargs = {} + if "_semantic" in inspect.signature(cls.__init__).parameters: + extra_kwargs["_semantic"] = _semantic + if "_generator" in inspect.signature(cls.__init__).parameters: + extra_kwargs["_generator"] = _generator + cls.__init__(instance, *args, **extra_kwargs, **kwargs) + + # Require that the user-defined constructor initialized all fields. + for name in cls.__annotations__.keys(): + if not hasattr(instance, name): + raise AttributeError(f"constructor for {cls.__name__} did not initialize attribute '{name}'") + + return instance + + # Only allow setting attributes defined in the class annotations. + def __setattr__(self, name, value): + if name not in cls.__annotations__: + raise AttributeError(f"{cls.__name__} has no attribute '{name}'") + if not isinstance(value, cls.__annotations__[name]): + raise TypeError(f"Expected {cls.__annotations__[name]} for attribute '{name}', got {type(value)}") + super().__setattr__(name, value) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + for name in cls.__annotations__.keys(): + getattr(self, name)._flatten_ir(handles) + + @property + def type(self): + return _aggregate_type(aggregate_value, + [(name, getattr(self, name).type) for name in cls.__annotations__.keys()]) + + for (name, member) in inspect.getmembers(cls): + if inspect.isfunction(member) or inspect.ismethod(member) or isinstance(member, JITCallable): + if name != "__init__": + setattr(aggregate_value, name, member) + + aggregate_value.__name__ = cls.__name__ + aggregate_value.__module__ = cls.__module__ + aggregate_value.__qualname__ = cls.__qualname__ + aggregate_value.__doc__ = cls.__doc__ + + return aggregate_value + + +# ----------------------- +# SPMD Programming Model +# ----------------------- + + +@builtin +def program_id(axis, _semantic=None): + """ + Returns the id of the current program instance along the given :code:`axis`. + + :param axis: The axis of the 3D launch grid. Must be 0, 1 or 2. + :type axis: int + """ + # if axis == -1: + # pid0 = _semantic.program_id(0) + # pid1 = _semantic.program_id(1) + # pid2 = _semantic.program_id(2) + # npg0 = _semantic.num_programs(0) + # npg1 = _semantic.num_programs(1) + # return pid0 + pid1*npg0 + pid2*npg0*npg1 + axis = _unwrap_if_constexpr(axis) + return _semantic.program_id(axis) + + +@builtin +def num_programs(axis, _semantic=None): + """ + Returns the number of program instances launched along the given :code:`axis`. + + :param axis: The axis of the 3D launch grid. Must be 0, 1 or 2. + :type axis: int + """ + axis = _unwrap_if_constexpr(axis) + return _semantic.num_programs(axis) + + +# ----------------------- +# Block Initialization +# ----------------------- + + +@builtin +def arange(start, end, _semantic=None): + start = _unwrap_if_constexpr(start) + end = _unwrap_if_constexpr(end) + return _semantic.arange(start, end) + + +arange.__doc__ = f""" + Returns contiguous values within the half-open interval :code:`[start, + end)`. :code:`end - start` must be less than or equal to + :code:`TRITON_MAX_TENSOR_NUMEL = {TRITON_MAX_TENSOR_NUMEL}` + + :param start: Start of the interval. Must be a power of two. + :type start: int32 + :param end: End of the interval. Must be a power of two greater than + :code:`start`. + :type end: int32 +""" + + +def _unwrap_shape(shape): + shape = _unwrap_if_constexpr(shape) + return [_unwrap_if_constexpr(s) for s in shape] + + +def _shape_check_impl(shape): + shape = _unwrap_shape(shape) + validate_block_shape(shape) + return shape + + +@builtin +def full(shape, value, dtype, _semantic=None): + """ + Returns a tensor filled with the scalar value for the given :code:`shape` and :code:`dtype`. + + :param shape: Shape of the new array, e.g., (8, 16) or (8, ) + :type shape: tuple of ints + :param value: A scalar value to fill the array with + :type value: scalar + :param dtype: Data type of the new array, e.g., :code:`tl.float16` + :type dtype: tl.dtype + """ + shape = _shape_check_impl(shape) + value = _unwrap_if_constexpr(value) + dtype = _unwrap_if_constexpr(dtype) + return _semantic.full(shape, value, dtype) + + +# ----------------------- +# Shape Manipulation +# ----------------------- + + +@builtin +def broadcast(input, other, _semantic=None): + """ + Tries to broadcast the two given blocks to a common compatible shape. + + :param input: The first input tensor. + :type input: Block + :param other: The second input tensor. + :type other: Block + """ + return _semantic.broadcast_impl_value(input, other) + + +@_tensor_member_fn +@builtin +def broadcast_to(input, *shape, _semantic=None): + """ + Tries to broadcast the given tensor to a new :code:`shape`. + + :param input: The input tensor. + :type input: Block + :param shape: The desired shape. + :type shape: + + :code:`shape` can be passed as a tuple or as individual parameters: :: + + # These are equivalent + broadcast_to(x, (32, 32)) + broadcast_to(x, 32, 32) + """ + shape = _shape_check_impl(_unwrap_iterable(shape)) + return _semantic.broadcast_impl_shape(input, shape) + + +@_tensor_member_fn +@builtin +def trans(input: tensor, *dims, _semantic=None): + """ + Permutes the dimensions of a tensor. + + If the parameter :code:`dims` is not specified, the function defaults to a (1,0) permutation, + effectively transposing a 2D tensor. + + :param input: The input tensor. + :param dims: The desired ordering of dimensions. For example, + :code:`(2, 1, 0)` reverses the order dims in a 3D tensor. + + :code:`dims` can be passed as a tuple or as individual parameters: :: + + # These are equivalent + trans(x, (2, 1, 0)) + trans(x, 2, 1, 0) + + :py:func:`permute` is equivalent to this function, except it doesn't + have the special case when no permutation is specified. + """ + dims = _unwrap_iterable(dims) + if not dims: + dims = (1, 0) + return _semantic.permute(input, dims) + + +@_tensor_member_fn +@builtin +def permute(input, *dims, _semantic=None): + """ + Permutes the dimensions of a tensor. + + :param input: The input tensor. + :type input: Block + :param dims: The desired ordering of dimensions. For example, + :code:`(2, 1, 0)` reverses the order dims in a 3D tensor. + + :code:`dims` can be passed as a tuple or as individual parameters: :: + + # These are equivalent + permute(x, (2, 1, 0)) + permute(x, 2, 1, 0) + + :py:func:`trans` is equivalent to this function, except when + :code:`dims` is empty, it tries to do a (1,0) permutation. + """ + dims = _unwrap_iterable(dims) + return _semantic.permute(input, dims) + + +@builtin +def cat(input, other, can_reorder=False, _semantic=None): + """ + Concatenate the given blocks + + :param input: The first input tensor. + :type input: Tensor + :param other: The second input tensor. + :type other: Tensor + :param reorder: Compiler hint. If true, the compiler is + allowed to reorder elements while concatenating inputs. Only use if the + order does not matter (e.g., result is only used in reduction ops). + Current implementation of `cat` supports only can_reorder=True. + """ + return _semantic.cat(input, other, can_reorder) + + +@builtin +def join(a, b, _semantic=None): + """ + Join the given tensors in a new, minor dimension. + + For example, given two tensors of shape (4,8), produces a new tensor of + shape (4,8,2). Given two scalars, returns a tensor of shape (2). + + The two inputs are broadcasted to be the same shape. + + If you want to join more than two elements, you can use multiple calls to + this function. This reflects the constraint in Triton that tensors must + have power-of-two sizes. + + join is the inverse of split. + + :param a: The first input tensor. + :type a: Tensor + :param b: The second input tensor. + :type b: Tensor + """ + return _semantic.join(a, b) + + +def _unsplat(x, _semantic=None, _generator=None): + """ + Convert a single-element tensor to a scalar. + """ + if len(x.shape) == 0: + return x + numel = 1 + for d in x.shape: + numel *= d + assert numel == 1, "can only unsplat single-element tensors" + return _semantic.unsplat(x) + + +@_tensor_member_fn +@builtin +def split(a, _semantic=None, _generator=None) -> tuple[tensor, tensor]: + """ + Split a tensor in two along its last dim, which must have size 2. + + For example, given a tensor of shape (4,8,2), produces two tensors of shape + (4,8). Given a tensor of shape (2), returns two scalars. + + If you want to split into more than two pieces, you can use multiple calls + to this function (probably plus calling reshape). This reflects the + constraint in Triton that tensors must have power-of-two sizes. + + split is the inverse of join. + + :param a: The tensor to split. + :type a: Tensor + """ + # If len(a.shape) == 1, i.e. a.shape == [2], we should return two scalars. + # But _semantic.split can only handle returning tensors. Work around this by + # expanding the input to shape [1,2] and then reducing the result. + was_rank_1 = len(a.shape) == 1 + if was_rank_1: + a = _semantic.expand_dims(a, 0) + + out_lhs, out_rhs = _semantic.split(a) + + if was_rank_1: + # Currently `reduce` is the best way to convert a tensor of shape [1] to a scalar. + out_lhs = _unsplat(out_lhs, _semantic=_semantic, _generator=_generator) + out_rhs = _unsplat(out_rhs, _semantic=_semantic, _generator=_generator) + + return out_lhs, out_rhs + + +@_tensor_member_fn +@builtin +def view(input, *shape, _semantic=None): + """ + Returns a tensor with the same elements as `input` but a different shape. + The order of the elements may not be preserved. + + :param input: The input tensor. + :type input: Block + :param shape: The desired shape. + + :code:`shape` can be passed as a tuple or as individual parameters: :: + + # These are equivalent + view(x, (32, 32)) + view(x, 32, 32) + """ + warn("view is deprecated, please use reshape with can_reorder being true.") + shape = _shape_check_impl(_unwrap_iterable(shape)) + return _semantic.reshape(input, shape, can_reorder=True) + + +@_tensor_member_fn +@builtin +def item(input, _semantic=None, _generator=None): + """ + Converts a single-element tensor into a scalar. + """ + return _unsplat(input, _semantic=_semantic, _generator=_generator) + + +@_tensor_member_fn +@builtin +def reshape(input, *shape, can_reorder=False, _semantic=None, _generator=None): + """ + Returns a tensor with the same number of elements as input but with the + provided shape. + + :param input: The input tensor. + :type input: Block + :param shape: The new shape. + + :code:`shape` can be passed as a tuple or as individual parameters: :: + + # These are equivalent + reshape(x, (32, 32)) + reshape(x, 32, 32) + """ + shape = _shape_check_impl(_unwrap_iterable(shape)) + if len(shape) == 0: + return _unsplat(input, _semantic=_semantic, _generator=_generator) + return _semantic.reshape(input, shape, can_reorder) + + +def _wrap_axis(axis, ndim): + if not (-ndim <= axis < ndim): + raise ValueError(f"invalid axis {axis}. Expected {-ndim} <= axis < {ndim}") + + return axis if axis >= 0 else axis + ndim + + +@_tensor_member_fn +@builtin +def expand_dims(input, axis, _semantic=None): + """ + Expand the shape of a tensor, by inserting new length-1 dimensions. + + Axis indices are with respect to the resulting tensor, so + ``result.shape[axis]`` will be 1 for each axis. + + :param input: The input tensor. + :type input: tl.tensor + :param axis: The indices to add new axes + :type axis: int | Sequence[int] + + """ + input = _semantic.to_tensor(input) + axis = _unwrap_if_constexpr(axis) + axes = list(axis) if isinstance(axis, (Sequence, tuple)) else [axis] + new_ndim = len(input.shape) + len(axes) + axes = [_wrap_axis(_unwrap_if_constexpr(d), new_ndim) for d in axes] + + if len(set(axes)) != len(axes): + raise ValueError(f"expand_dims received duplicate axes, normalized axes = {axes}") + + ret = input + for a in sorted(axes): + ret = _semantic.expand_dims(ret, a) + return ret + + +@_tensor_member_fn +@builtin +def cast(input, dtype: dtype, fp_downcast_rounding: Optional[str] = None, bitcast: bool = False, _semantic=None): + """ + Casts a tensor to the given :code:`dtype`. + + :param dtype: The target data type. + :type dtype: tl.dtype + :param fp_downcast_rounding: The rounding mode for downcasting + floating-point values. This parameter is only used when self is a + floating-point tensor and dtype is a floating-point type with a + smaller bitwidth. Supported values are :code:`"rtne"` (round to + nearest, ties to even) and :code:`"rtz"` (round towards zero). + :type fp_downcast_rounding: str, optional + :param bitcast: If true, the tensor is bitcasted to the given + :code:`dtype`, instead of being numerically casted. + :type bitcast: bool, optional + """ + input = _semantic.to_tensor(input) + dtype = _unwrap_if_constexpr(dtype) + fp_downcast_rounding = _unwrap_if_constexpr(fp_downcast_rounding) + bitcast = _unwrap_if_constexpr(bitcast) + if bitcast: + return _semantic.bitcast(input, dtype) + return _semantic.cast(input, dtype, fp_downcast_rounding) + + +# ----------------------- +# Linear Algebra +# ----------------------- + + +@builtin +def dot(input, other, acc=None, input_precision=None, allow_tf32=None, max_num_imprecise_acc=None, out_dtype=float32, + _semantic=None): + """ + Returns the matrix product of two blocks. + + The two blocks must both be two-dimensional or three-dimensional and have compatible inner dimensions. + For three-dimensional blocks, `tl.dot` performs the batched matrix product, + where the first dimension of each block represents the batch dimension. + + :param input: The first tensor to be multiplied. + :type input: 2D or 3D tensor of scalar-type in {:code:`int8`, :code:`float8_e5m2`, :code:`float16`, :code:`bfloat16`, :code:`float32`} + :param other: The second tensor to be multiplied. + :type other: 2D or 3D tensor of scalar-type in {:code:`int8`, :code:`float8_e5m2`, :code:`float16`, :code:`bfloat16`, :code:`float32`} + :param acc: The accumulator tensor. If not None, the result is added to this tensor. + :type acc: 2D or 3D tensor of scalar-type in {:code:`float16`, :code:`float32`, :code:`int32`} + :param input_precision: How to exercise the Tensor Cores for f32 x f32. If + the device does not have Tensor Cores or the inputs are not of dtype f32, + this option is ignored. For devices that do have tensor cores, the + default precision is tf32. + :type input_precision: string. Available options for nvidia: :code:`"tf32"`, :code:`"tf32x3"`, :code:`"ieee"`. Default: :code:`"tf32"`. Available options for amd: :code:`"ieee"`, (CDNA3 only) :code:`"tf32"`. + :param allow_tf32: *Deprecated.* If true, input_precision is set to "tf32". + Only one of :code:`input_precision` and :code:`allow_tf32` can be + specified (i.e. at least one must be :code:`None`). + """ + assert input_precision is None or allow_tf32 is None, "Only one of input_precision and allow_tf32 can be specified" + if input_precision is None: + supports_tf32 = "tf32" in _semantic.builder.options.allowed_dot_input_precisions + input_precision = knobs.language.fp32_default or ("tf32" if (supports_tf32 and + (allow_tf32 or allow_tf32 is None)) else "ieee") + + input_precision = _unwrap_if_constexpr(input_precision) + out_dtype = _unwrap_if_constexpr(out_dtype) + max_num_imprecise_acc = _unwrap_if_constexpr(max_num_imprecise_acc) + acc = _unwrap_if_constexpr(acc) + return _semantic.dot(input, other, acc, input_precision, max_num_imprecise_acc, out_dtype) + + +@builtin +def dot_scaled(lhs, lhs_scale, lhs_format, rhs, rhs_scale, rhs_format, acc=None, fast_math=False, lhs_k_pack=True, + rhs_k_pack=True, out_dtype=float32, _semantic=None): + """ + Returns the matrix product of two blocks in microscaling format. + + lhs and rhs use microscaling formats described here: + https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf + + Software emulation enables targeting hardware architectures without native microscaling + operation support. Right now for such case, microscaled lhs/rhs are upcasted to + :code:`bf16` element type beforehand for dot computation, with one exception: + for AMD CDNA3 specifically, if one of the inputs is of :code:`fp16` element type, + the other input is also upcasted to :code:`fp16` element type instead. + This behavior is experimental and may be subject to change in the future. + + :param lhs: The first tensor to be multiplied. + :type lhs: 2D tensor representing fp4, fp8 or bf16 elements. Fp4 elements are packed into uint8 inputs with the first element in lower bits. Fp8 are stored as uint8 or the corresponding fp8 type. + :param lhs_scale: Scale factor for lhs tensor. + :type lhs_scale: e8m0 type represented as an uint8 tensor. + :param lhs_format: format of the lhs tensor. Available formats: {:code:`e2m1`, :code:`e4m3`, :code:`e5m2`, :code:`bf16`, :code:`fp16`}. + :type lhs_format: str + :param rhs: The second tensor to be multiplied. + :type rhs: 2D tensor representing fp4, fp8 or bf16 elements. Fp4 elements are packed into uint8 inputs with the first element in lower bits. Fp8 are stored as uint8 or the corresponding fp8 type. + :param rhs_scale: Scale factor for rhs tensor. + :type rhs_scale: e8m0 type represented as an uint8 tensor. + :param rhs_format: format of the rhs tensor. Available formats: {:code:`e2m1`, :code:`e4m3`, :code:`e5m2`, :code:`bf16`, :code:`fp16`}. + :type rhs_format: str + :param acc: The accumulator tensor. If not None, the result is added to this tensor. + :param lhs_k_pack: If false, the lhs tensor is packed into uint8 along M dimension. + :type lhs_k_pack: bool, optional + :param rhs_k_pack: If false, the rhs tensor is packed into uint8 along N dimension. + :type rhs_k_pack: bool, optional + """ + out_dtype = _unwrap_if_constexpr(out_dtype) + assert out_dtype == float32, "Only float32 is supported for out_dtype at the moment" + return _semantic.dot_scaled(lhs, lhs_scale, lhs_format, rhs, rhs_scale, rhs_format, acc, fast_math, lhs_k_pack, + rhs_k_pack, out_dtype) + + +# ----------------------- +# Non-Atomic Memory Operations +# ----------------------- + + +@builtin +def load(pointer, mask=None, other=None, boundary_check=(), padding_option="", cache_modifier="", eviction_policy="", + volatile=False, _semantic=None): + """ + Return a tensor of data whose values are loaded from memory at location defined by `pointer`: + + (1) If `pointer` is a single element pointer, a scalar is be loaded. In + this case: + + - `mask` and `other` must also be scalars, + - `other` is implicitly typecast to `pointer.dtype.element_ty`, and + - `boundary_check` and `padding_option` must be empty. + + (2) If `pointer` is an N-dimensional tensor of pointers, an + N-dimensional tensor is loaded. In this case: + + - `mask` and `other` are implicitly broadcast to `pointer.shape`, + - `other` is implicitly typecast to `pointer.dtype.element_ty`, and + - `boundary_check` and `padding_option` must be empty. + + (3) If `pointer` is a block pointer defined by `make_block_ptr`, a + tensor is loaded. In this case: + + - `mask` and `other` must be `None`, and + - `boundary_check` and `padding_option` can be specified to control the behavior of out-of-bound access. + + :param pointer: Pointer to the data to be loaded + :type pointer: `triton.PointerType`, or block of `dtype=triton.PointerType` + :param mask: if `mask[idx]` is false, do not load the data at address `pointer[idx]` + (must be `None` with block pointers) + :type mask: Block of `triton.int1`, optional + :param other: if `mask[idx]` is false, return `other[idx]` + :type other: Block, optional + :param boundary_check: tuple of integers, indicating the dimensions which should do the boundary check + :type boundary_check: tuple of ints, optional + :param padding_option: should be one of {"", "zero", "nan"}, the padding value to use while out of bounds. "" means an undefined value. + :param cache_modifier: changes cache option in NVIDIA PTX + :type cache_modifier: str, optional, should be one of {"", ".ca", ".cg", ".cv"}, where ".ca" stands for + cache at all levels, ".cg" stands for cache at global level (cache in L2 and below, not L1), + and ".cv" means don’t cache and fetch again. see + `cache operator `_ for more details. + :param eviction_policy: changes eviction policy in NVIDIA PTX + :type eviction_policy: str, optional + :param volatile: changes volatile option in NVIDIA PTX + :type volatile: bool, optional + """ + # `mask` and `other` can be constexpr + mask = _unwrap_if_constexpr(mask) + other = _unwrap_if_constexpr(other) + if mask is not None: + mask = _semantic.to_tensor(mask) + if other is not None: + other = _semantic.to_tensor(other) + padding_option = _unwrap_if_constexpr(padding_option) + cache_modifier = _unwrap_if_constexpr(cache_modifier) + eviction_policy = _unwrap_if_constexpr(eviction_policy) + volatile = _unwrap_if_constexpr(volatile) + return _semantic.load(pointer, mask, other, boundary_check, padding_option, cache_modifier, eviction_policy, + volatile) + + +@builtin +def load_tensor_descriptor(desc: tensor_descriptor_base, offsets: Sequence[constexpr | tensor], + _semantic=None) -> tensor: + """Load a block of data from a tensor descriptor.""" + return desc.load(offsets, _semantic=_semantic) + + +@builtin +def store_tensor_descriptor(desc: tensor_descriptor_base, offsets: Sequence[constexpr | tensor], value: tensor, + _semantic=None) -> tensor: + """Store a block of data to a tensor descriptor.""" + return desc.store(offsets, value, _semantic=_semantic) + + +@_tensor_member_fn +@builtin +def store(pointer, value, mask=None, boundary_check=(), cache_modifier="", eviction_policy="", _semantic=None): + """ + Store a tensor of data into memory locations defined by `pointer`. + + (1) If `pointer` is a single element pointer, a scalar is stored. In + this case: + + - `mask` must also be scalar, and + - `boundary_check` and `padding_option` must be empty. + + (2) If `pointer` is an N-dimensional tensor of pointers, an + N-dimensional block is stored. In this case: + + - `mask` is implicitly broadcast to `pointer.shape`, and + - `boundary_check` must be empty. + + (3) If `pointer` is a block pointer defined by `make_block_ptr`, a block + of data is stored. In this case: + + - `mask` must be None, and + - `boundary_check` can be specified to control the behavior of out-of-bound access. + + `value` is implicitly broadcast to `pointer.shape` and typecast to `pointer.dtype.element_ty`. + + :param pointer: The memory location where the elements of `value` are stored + :type pointer: `triton.PointerType`, or block of `dtype=triton.PointerType` + :param value: The tensor of elements to be stored + :type value: Block + :param mask: If `mask[idx]` is false, do not store `value[idx]` at `pointer[idx]` + :type mask: Block of triton.int1, optional + :param boundary_check: tuple of integers, indicating the dimensions which should do the boundary check + :type boundary_check: tuple of ints, optional + :param cache_modifier: changes cache option in NVIDIA PTX + :type cache_modifier: str, optional, should be one of {"", ".wb", ".cg", ".cs", ".wt"}, where ".wb" stands for + cache write-back all coherent levels, ".cg" stands for cache global, ".cs" stands for cache streaming, ".wt" + stands for cache write-through, see `cache operator `_ for more details. + :param eviction_policy: changes eviction policy in NVIDIA PTX + :type eviction_policy: str, optional, should be one of {"", "evict_first", "evict_last"} + """ + # `value` can be constexpr + value = _semantic.to_tensor(value) + mask = _unwrap_if_constexpr(mask) + if mask is not None: + mask = _semantic.to_tensor(mask) + cache_modifier = _unwrap_if_constexpr(cache_modifier) + eviction_policy = _unwrap_if_constexpr(eviction_policy) + return _semantic.store(pointer, value, mask, boundary_check, cache_modifier, eviction_policy) + + +@builtin +def make_block_ptr(base: tensor, shape, strides, offsets, block_shape, order, _semantic=None): + """ + Returns a pointer to a block in a parent tensor + + :param base: The base pointer to the parent tensor + :param shape: The shape of the parent tensor + :param strides: The strides of the parent tensor + :param offsets: The offsets to the block + :param block_shape: The shape of the block + :param order: The order of the original data format + """ + return _semantic.make_block_ptr(base, shape, strides, offsets, block_shape, order) + + +@must_use_result( + "Note that tl.advance does not have any side effects. To move the block pointer, you need to assign the result of tl.advance to a variable." +) +@_tensor_member_fn +@builtin +def advance(base, offsets, _semantic=None): + """ + Advance a block pointer + + :param base: the block pointer to advance + :param offsets: the offsets to advance, a tuple by dimension + """ + return _semantic.advance(base, offsets) + + +@builtin +def make_tensor_descriptor( + base: tensor, + shape: List[tensor], + strides: List[tensor], + block_shape: List[constexpr], + padding_option="zero", + _semantic=None, +) -> tensor_descriptor: + """Make a tensor descriptor object + + :param base: the base pointer of the tensor, must be 16-byte aligned + :param shape: A list of non-negative integers representing the tensor shape + :param strides: A list of tensor strides. Leading dimensions must be multiples + of 16-byte strides and the last dimension must be contiguous. + :param block_shape: The shape of block to be loaded/stored from global memory + + Notes + ***** + On NVIDIA GPUs with TMA support, this will result in a TMA descriptor object + and loads and stores from the descriptor will be backed by the TMA hardware. + + Currently only 2-5 dimensional tensors are supported. + + Example + ******* + .. code-block:: python + + @triton.jit + def inplace_abs(in_out_ptr, M, N, M_BLOCK: tl.constexpr, N_BLOCK: tl.constexpr): + desc = tl.make_tensor_descriptor( + in_out_ptr, + shape=[M, N], + strides=[N, 1], + block_shape=[M_BLOCK, N_BLOCK], + ) + + moffset = tl.program_id(0) * M_BLOCK + noffset = tl.program_id(1) * N_BLOCK + + value = desc.load([moffset, noffset]) + desc.store([moffset, noffset], tl.abs(value)) + + # TMA descriptors require a global memory allocation + def alloc_fn(size: int, alignment: int, stream: Optional[int]): + return torch.empty(size, device="cuda", dtype=torch.int8) + + triton.set_allocator(alloc_fn) + + M, N = 256, 256 + x = torch.randn(M, N, device="cuda") + M_BLOCK, N_BLOCK = 32, 32 + grid = (M / M_BLOCK, N / N_BLOCK) + inplace_abs[grid](x, M, N, M_BLOCK, N_BLOCK) + + """ + + padding_option = _unwrap_if_constexpr(padding_option) + return _semantic.make_tensor_descriptor(base, shape, strides, block_shape, padding_option) + + +# ----------------------- +# Atomic Memory Operations +# ----------------------- + + +def _add_atomic_docstr(name: str, has_cmp: bool = False) -> Callable[[T], T]: + + def _decorator(func: T) -> T: + docstr = f""" + Performs an atomic {name} at the memory location specified by :code:`pointer`. + + Return the data stored at :code:`pointer` before the atomic operation. + + :param pointer: The memory locations to operate on + :type pointer: Block of dtype=triton.PointerDType""" + if has_cmp: + docstr += """ + :param cmp: The values expected to be found in the atomic object + :type cmp: Block of dtype=pointer.dtype.element_ty""" + docstr += """ + :param val: The values with which to perform the atomic operation + :type val: Block of dtype=pointer.dtype.element_ty + :param sem: Specifies the memory semantics for the operation. Acceptable values are "acquire", + "release", "acq_rel" (stands for "ACQUIRE_RELEASE"), and "relaxed". If not provided, + the function defaults to using "acq_rel" semantics. + :type sem: str, optional + :param scope: Defines the scope of threads that observe the synchronizing effect of the atomic operation. + Acceptable values are "gpu" (default), "cta" (cooperative thread array, thread block), or "sys" (stands for "SYSTEM"). The default value is "gpu". + :type scope: str, optional + """ + func.__doc__ = docstr + return func + + return _decorator + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("compare-and-swap", has_cmp=True) +def atomic_cas(pointer, cmp, val, sem=None, scope=None, _semantic=None): + cmp = _semantic.to_tensor(cmp) + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + return _semantic.atomic_cas(pointer, cmp, val, sem, scope) + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("exchange") +def atomic_xchg(pointer, val, mask=None, sem=None, scope=None, _semantic=None): + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + mask = _unwrap_if_constexpr(mask) + return _semantic.atomic_xchg(pointer, val, mask, sem, scope) + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("add") +def atomic_add(pointer, val, mask=None, sem=None, scope=None, _semantic=None): + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + mask = _unwrap_if_constexpr(mask) + return _semantic.atomic_add(pointer, val, mask, sem, scope) + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("max") +def atomic_max(pointer, val, mask=None, sem=None, scope=None, _semantic=None): + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + mask = _unwrap_if_constexpr(mask) + return _semantic.atomic_max(pointer, val, mask, sem, scope) + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("min") +def atomic_min(pointer, val, mask=None, sem=None, scope=None, _semantic=None): + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + mask = _unwrap_if_constexpr(mask) + return _semantic.atomic_min(pointer, val, mask, sem, scope) + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("logical and") +def atomic_and(pointer, val, mask=None, sem=None, scope=None, _semantic=None): + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + mask = _unwrap_if_constexpr(mask) + return _semantic.atomic_and(pointer, val, mask, sem, scope) + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("logical or") +def atomic_or(pointer, val, mask=None, sem=None, scope=None, _semantic=None): + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + mask = _unwrap_if_constexpr(mask) + return _semantic.atomic_or(pointer, val, mask, sem, scope) + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("logical xor") +def atomic_xor(pointer, val, mask=None, sem=None, scope=None, _semantic=None): + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + mask = _unwrap_if_constexpr(mask) + return _semantic.atomic_xor(pointer, val, mask, sem, scope) + + +# ----------------------- +# Conditioning +# ----------------------- + + +@builtin +def where(condition, x, y, _semantic=None): + """ + Returns a tensor of elements from either :code:`x` or :code:`y`, depending on :code:`condition`. + + Note that :code:`x` and :code:`y` are always evaluated regardless of the value of :code:`condition`. + + If you want to avoid unintended memory operations, use the :code:`mask` arguments in `triton.load` and `triton.store` instead. + + The shape of :code:`x` and :code:`y` are both broadcast to the shape of :code:`condition`. + :code:`x` and :code:`y` must have the same data type. + + :param condition: When True (nonzero), yield x, otherwise yield y. + :type condition: Block of triton.bool + :param x: values selected at indices where condition is True. + :param y: values selected at indices where condition is False. + """ + condition = _semantic.to_tensor(condition) + x = _unwrap_if_constexpr(x) + y = _unwrap_if_constexpr(y) + return _semantic.where(condition, x, y) + + +# ----------------------- +# Math +# ----------------------- + + +@builtin +def add(x, y, sanitize_overflow: constexpr = True, _semantic=None): + x = _unwrap_if_constexpr(x) + y = _unwrap_if_constexpr(y) + return _semantic.add(x, y, sanitize_overflow) + + +@builtin +def sub(x, y, sanitize_overflow: constexpr = True, _semantic=None): + x = _unwrap_if_constexpr(x) + y = _unwrap_if_constexpr(y) + return _semantic.sub(x, y, sanitize_overflow) + + +@builtin +def mul(x, y, sanitize_overflow: constexpr = True, _semantic=None): + x = _unwrap_if_constexpr(x) + y = _unwrap_if_constexpr(y) + return _semantic.mul(x, y, sanitize_overflow) + + +@builtin +def minimum(x, y, propagate_nan: constexpr = PropagateNan.NONE, _semantic=None): + """ + Computes the element-wise minimum of :code:`x` and :code:`y`. + + :param x: the first input tensor + :type x: Block + :param y: the second input tensor + :type y: Block + :param propagate_nan: whether to propagate NaN values. + :type propagate_nan: tl.PropagateNan + + .. seealso:: :class:`tl.PropagateNan` + """ + x = _semantic.to_tensor(x) + y = _semantic.to_tensor(y) + x = _promote_bfloat16_to_float32(x, _semantic=_semantic) + y = _promote_bfloat16_to_float32(y, _semantic=_semantic) + propagate_nan = _unwrap_if_constexpr(propagate_nan) + return _semantic.minimum(x, y, propagate_nan) + + +@builtin +def maximum(x, y, propagate_nan: constexpr = PropagateNan.NONE, _semantic=None): + """ + Computes the element-wise maximum of :code:`x` and :code:`y`. + + :param x: the first input tensor + :type x: Block + :param y: the second input tensor + :type y: Block + :param propagate_nan: whether to propagate NaN values. + :type propagate_nan: tl.PropagateNan + + .. seealso:: :class:`tl.PropagateNan` + """ + x = _semantic.to_tensor(x) + y = _semantic.to_tensor(y) + x = _promote_bfloat16_to_float32(x, _semantic=_semantic) + y = _promote_bfloat16_to_float32(y, _semantic=_semantic) + propagate_nan = _unwrap_if_constexpr(propagate_nan) + return _semantic.maximum(x, y, propagate_nan) + + +@builtin +def clamp(x, min, max, propagate_nan: constexpr = PropagateNan.NONE, _semantic=None): + """ + Clamps the input tensor :code:`x` within the range [min, max]. + Behavior when :code:`min` > :code:`max` is undefined. + + :param x: the input tensor + :type x: Block + :param min: the lower bound for clamping + :type min: Block + :param max: the upper bound for clamping + :type max: Block + :param propagate_nan: whether to propagate NaN values. Applies only to the :code:`x` tensor. + If either :code:`min` or :code:`max` is NaN, the result is undefined. + :type propagate_nan: tl.PropagateNan + + .. seealso:: :class:`tl.PropagateNan` + """ + x = _semantic.to_tensor(x) + min = _semantic.to_tensor(min) + max = _semantic.to_tensor(max) + x = _promote_bfloat16_to_float32(x, _semantic=_semantic) + min = _promote_bfloat16_to_float32(min, _semantic=_semantic) + max = _promote_bfloat16_to_float32(max, _semantic=_semantic) + + propagate_nan = _unwrap_if_constexpr(propagate_nan) + + return _semantic.clamp(x, min, max, propagate_nan) + + +# ----------------------- +# Reductions +# ----------------------- + + +def _add_reduction_docstr(name: str, return_indices_arg: str = None, tie_break_arg: str = None, + dtype_arg: str = None) -> Callable[[T], T]: + + def _decorator(func: T) -> T: + docstr = """ + Returns the {name} of all elements in the :code:`input` tensor along the provided :code:`axis` + + :param input: the input values + :type input: Tensor + :param axis: the dimension along which the reduction should be done. If None, reduce all dimensions + :type axis: int + :param keep_dims: if true, keep the reduced dimensions with length 1 + :type keep_dims: bool""" + if return_indices_arg is not None: + docstr += f""" + :param {return_indices_arg}: if true, return index corresponding to the {name} value + :type {return_indices_arg}: bool""" + if tie_break_arg is not None: + docstr += f""" + :param {tie_break_arg}: if true, in case of a tie (i.e., multiple elements have the same {name} value), return the left-most index for values that aren't NaN + :type {tie_break_arg}: bool""" + if dtype_arg is not None: + docstr += f""" + :param {dtype_arg}: the desired data type of the returned tensor. If specified, the input tensor is casted to :code:`{dtype_arg}` before the operation is performed. This is useful for preventing data overflows. If not specified, integer and bool dtypes are upcasted to :code:`tl.int32` and float dtypes are upcasted to at least :code:`tl.float32`. + :type {dtype_arg}: tl.dtype""" + + func.__doc__ = docstr.format(name=name) + return func + + return _decorator + + +@contextmanager +def _insertion_guard(builder): + ip = builder.get_insertion_point() + yield + builder.restore_insertion_point(ip) + + +@_tensor_member_fn +@builtin +def reduce(input, axis, combine_fn, keep_dims=False, _semantic=None, _generator=None): + """Applies the combine_fn to all elements in :code:`input` tensors along the provided :code:`axis` + + :param input: the input tensor, or tuple of tensors + :type input: Tensor + :param axis: the dimension along which the reduction should be done. If None, reduce all dimensions + :type axis: int | None + :param combine_fn: a function to combine two groups of scalar tensors (must be marked with @triton.jit) + :type combine_fn: Callable + :param keep_dims: if true, keep the reduced dimensions with length 1 + :type keep_dims: bool + + """ + if isinstance(input, tensor): + return reduce((input, ), axis, combine_fn, keep_dims=keep_dims, _semantic=_semantic, _generator=_generator)[0] + + def make_combine_region(reduce_op): + param_types = [t.type.scalar for t in input] * 2 + region = reduce_op.get_region(0) + builder = _semantic.builder + with _insertion_guard(builder): + to_ir = lambda T: T.to_ir(builder) + block = builder.create_block_with_parent(region, list(map(to_ir, param_types))) + args = [tensor(block.arg(i), ty) for i, ty in enumerate(param_types)] + results = _generator.call_JitFunction(combine_fn, args, kwargs={}) + if isinstance(results, tensor): + handles = [results.handle] + else: + handles = [r.handle for r in results] + builder.create_reduce_ret(*handles) + + def expand_ndims(t, ndims): + for _ in builtins.range(ndims): + t = expand_dims(t, 0, _semantic=_semantic) + return t + + axis = _unwrap_if_constexpr(axis) + keep_dims = _unwrap_if_constexpr(keep_dims) + if axis is not None: + axis = _wrap_axis(axis, len(input[0].shape)) + ret = _semantic.reduction(input, axis, make_combine_region) + if keep_dims: + if axis is not None: + ret = tuple(expand_dims(t, axis, _semantic=_semantic) for t in ret) + else: + ret = tuple(expand_ndims(t, len(input[0].shape)) for t in ret) + return ret + + +@builtin +def _promote_bfloat16_to_float32(t, _semantic=None): + scalar_ty = t.type.scalar + + # hardware doesn't support FMAX, FMIN, CMP for bfloat16 + if scalar_ty is bfloat16: + return t.to(float32, _semantic=_semantic) + return t + + +@builtin +def _reduce_with_indices(input, axis, combine_fn, keep_dims=False, _semantic=None, _generator=None): + axis = _unwrap_if_constexpr(axis) + n = input.shape[axis] + index = arange(0, n, _semantic=_semantic) + + if len(input.shape) > 1: + # Broadcast index across the non-reduced axes + axes_to_expand = [constexpr(d) for d in builtins.range(len(input.shape))] + del axes_to_expand[axis] + index = expand_dims(index, axes_to_expand, _semantic=_semantic) + index = broadcast_to(index, input.shape, _semantic=_semantic) + + rvalue, rindices = reduce((input, index), axis, combine_fn, keep_dims=keep_dims, _semantic=_semantic, + _generator=_generator) + return rvalue, rindices + + +# ----------------------- +# Scans +# ----------------------- + + +def _add_scan_docstr(name: str, dtype_arg: str = None) -> Callable[[T], T]: + + def _decorator(func: T) -> T: + docstr = """ + Returns the {name} of all elements in the :code:`input` tensor along the provided :code:`axis` + + :param input: the input values + :type input: Tensor + :param axis: the dimension along which the scan should be done + :type axis: int + :param reverse: if true, the scan is performed in the reverse direction + :type reverse: bool""" + + if dtype_arg is not None: + docstr += f""" + :param {dtype_arg}: the desired data type of the returned tensor. If specified, the input tensor is casted to :code:`{dtype_arg}` before the operation is performed. If not specified, small integer types (< 32 bits) are upcasted to prevent overflow. Note that :code:`tl.bfloat16` inputs are automatically promoted to :code:`tl.float32`. + :type {dtype_arg}: tl.dtype""" + + func.__doc__ = docstr.format(name=name) + return func + + return _decorator + + +@_tensor_member_fn +@builtin +def associative_scan(input, axis, combine_fn, reverse=False, _semantic=None, _generator=None): + """Applies the combine_fn to each elements with a carry in :code:`input` tensors along the provided :code:`axis` and update the carry + + :param input: the input tensor, or tuple of tensors + :type input: Tensor + :param axis: the dimension along which the reduction should be done + :type axis: int + :param combine_fn: a function to combine two groups of scalar tensors (must be marked with @triton.jit) + :type combine_fn: Callable + :param reverse: whether to apply the associative scan in the reverse direction along axis + :type reverse: bool + + """ + if isinstance(input, tensor): + return associative_scan((input, ), axis, combine_fn, reverse, _semantic=_semantic, _generator=_generator)[0] + + def make_combine_region(scan_op): + param_types = [t.type.scalar for t in input] * 2 + region = scan_op.get_region(0) + builder = _semantic.builder + with _insertion_guard(builder): + to_ir = lambda T: T.to_ir(builder) + block = builder.create_block_with_parent(region, list(map(to_ir, param_types))) + args = [tensor(block.arg(i), ty) for i, ty in enumerate(param_types)] + results = _generator.call_JitFunction(combine_fn, args, kwargs={}) + if isinstance(results, tensor): + handles = [results.handle] + else: + handles = [r.handle for r in results] + builder.create_scan_ret(*handles) + + axis = _unwrap_if_constexpr(axis) + if axis is not None: + axis = _wrap_axis(axis, len(input[0].shape)) + return _semantic.associative_scan(input, axis, make_combine_region, reverse) + + +@_tensor_member_fn +@builtin +def histogram(input, num_bins, mask=None, _semantic=None, _generator=None): + """computes an histogram based on input tensor with num_bins bins, the bins have a width of 1 and start at 0. + + :param input: the input tensor + :type input: Tensor + :param num_bins: number of histogram bins + :type num_bins: int + :param mask: if `mask[idx]` is false, exclude `input[idx]` from histogram + :type mask: Block of `triton.int1`, optional + + """ + num_bins = _unwrap_if_constexpr(num_bins) + mask = _unwrap_if_constexpr(mask) + if mask is not None: + mask = _semantic.to_tensor(mask) + return _semantic.histogram(input, num_bins, mask) + + +@_tensor_member_fn +@builtin +def gather(src, index, axis, _semantic=None): + """Gather from a tensor along a given dimension. + + :param src: the source tensor + :type src: Tensor + :param index: the index tensor + :type index: Tensor + :param axis: the dimension to gather along + :type axis: int + + """ + axis = _unwrap_if_constexpr(axis) + return _semantic.gather(src, index, axis) + + +@builtin +def map_elementwise( + scalar_fn: Callable[..., Tuple[tensor, ...]], + *args: tensor, + pack=1, + _semantic=None, + _generator=None, +): + ''' + Map a scalar function over a tensor. + + The input tensors :code:`args` are implicitly broadcasted to the same shape. + + This may be useful in allowing control flow over single elements in a tensor, + for example a multi-branch function where one branch is more expensive. With + :code:`tl.where` you are forced to calculate both sides of the branch, but + with an if we only execute one side. + + .. highlight:: python + .. code-block:: python + + @triton.jit + def selu_scalar(x, alpha): + if x > 0: + return a + else: + return alpha * (tl.exp(x) - 1) + + @triton.jit + def selu(x, alpha): + return tl.map_elementwise(selu_scalar, x, alpha) + + :param scalar_fn: the function to map over. + :param pack: the number of elements to be processed by one function call. + :return: one tensor or a tuple of tensors, depending on the mapped function. + ''' + # Build the block for the nested region first to discover the return types + assert pack >= 1 + in_scalar_tys = [t.type.scalar for t in args] + builder = _semantic.builder + block = builder.new_block() + scalar_args = [] + for i, ty in enumerate(in_scalar_tys): + for j in builtins.range(pack): + block.add_argument(ty.to_ir(builder)) + scalar_args.append(tensor(block.arg(i * pack + j), ty)) + + with _insertion_guard(builder): + builder.set_insertion_point_to_start(block) + scalar_results = _generator.call_JitFunction(scalar_fn, scalar_args, kwargs={}) + + is_single = isinstance(scalar_results, tensor) + if is_single: + scalar_results = scalar_results, + + handles = [r.handle for r in scalar_results] + builder.create_map_elementwise_ret(handles) + + fn_result_types = [x.type for x in scalar_results] + scalar_result_types = fn_result_types + if pack > 1: + scalar_result_types = fn_result_types[::pack] + for offset in builtins.range(1, pack): + assert scalar_result_types == fn_result_types[offset::pack], "type mismatch in unpacked results" + + def make_elementwise_region(elementwise_op): + region = elementwise_op.get_region(0) + region.push_back(block) + + result = _semantic.map_elementwise(args, scalar_result_types, pack, make_elementwise_region) + return result[0] if is_single else result + + +# ----------------------- +# Compiler Hint Ops +# ----------------------- + + +@builtin +def debug_barrier(_semantic=None): + ''' + Insert a barrier to synchronize all threads in a block. + ''' + return _semantic.debug_barrier() + + +@builtin +def multiple_of(input, values, _semantic=None): + """ + Let the compiler know that the values in :code:`input` are all multiples of :code:`value`. + """ + if isinstance(values, constexpr): + values = [values] + for i, d in enumerate(values): + if not isinstance(d, constexpr): + raise TypeError(f"values element {i} must have type `constexpr`") + if not isinstance(d.value, int): + raise TypeError(f"values element {i} must have type `constexpr[int]`, got `constexpr[{type(d.value)}]") + values = [x.value for x in values] + return _semantic.multiple_of(input, values) + + +@builtin +def max_contiguous(input, values, _semantic=None): + """ + Let the compiler know that the `value` first values in :code:`input` are contiguous. + """ + if isinstance(values, constexpr): + values = [values] + for i, d in enumerate(values): + if not isinstance(d, constexpr): + raise TypeError(f"values element {i} must have type `constexpr`") + if not isinstance(d.value, int): + raise TypeError(f"values element {i} must have type `constexpr[int]`, got `constexpr[{type(d.value)}]") + values = [x.value for x in values] + return _semantic.max_contiguous(input, values) + + +@builtin +def max_constancy(input, values, _semantic=None): + """ + Let the compiler know that the `value` first values in :code:`input` are constant. + + e.g. if :code:`values` is [4], then each group of 4 values in :code:`input` should all be equal, + for example [0, 0, 0, 0, 1, 1, 1, 1]. + """ + if isinstance(values, constexpr): + values = [values] + for i, d in enumerate(values): + if not isinstance(d, constexpr): + raise TypeError(f"values element {i} must have type `constexpr`") + if not isinstance(d.value, int): + raise TypeError(f"values element {i} must have type `constexpr[int]`, got `constexpr[{type(d.value)}]") + values = [x.value for x in values] + return _semantic.max_constancy(input, values) + + +@builtin +def assume(cond, _semantic=None): + ''' + Allow compiler to assume the :code:`cond` is True. + ''' + return _semantic.assume(_semantic.to_tensor(cond)) + + +# ----------------------- +# Debugging functions +# ----------------------- + + +@builtin +def static_print(*values, sep: str = " ", end: str = "\n", file=None, flush=False, _semantic=None): + ''' + Print the values at compile time. The parameters are the same as the builtin :code:`print`. + + NOTE: Calling the Python builtin :code:`print` is not the same as calling this, it instead maps to :code:`device_print`, + which has special requirements for the arguments. + + .. highlight:: python + .. code-block:: python + + tl.static_print(f"BLOCK_SIZE={BLOCK_SIZE}") + ''' + pass + + +@builtin +def static_assert(cond, msg="", _semantic=None): + ''' + Assert the condition at compile time. Does not require that the :code:`TRITON_DEBUG` environment variable + is set. + + .. highlight:: python + .. code-block:: python + + tl.static_assert(BLOCK_SIZE == 1024) + ''' + pass + + +@builtin +def device_print(prefix, *args, hex=False, _semantic=None): + ''' + Print the values at runtime from the device. String formatting does not work for runtime values, so you should + provide the values you want to print as arguments. The first value must be a string, all following values must + be scalars or tensors. + + Calling the Python builtin :code:`print` is the same as calling this function, and the requirements for the arguments will match + this function (not the normal requirements for :code:`print`). + + .. highlight:: python + .. code-block:: python + + tl.device_print("pid", pid) + print("pid", pid) + + On CUDA, printfs are streamed through a buffer of limited size (on one host, + we measured the default as 6912 KiB, but this may not be consistent across + GPUs and CUDA versions). If you notice some printfs are being dropped, you + can increase the buffer size by calling + + .. highlight:: python + .. code-block:: python + + triton.runtime.driver.active.utils.set_printf_fifo_size(size_bytes) + + CUDA may raise an error if you try to change this value after running a + kernel that uses printfs. The value set here may only affect the current + device (so if you have multiple GPUs, you'd need to call it multiple times). + + :param prefix: a prefix to print before the values. This is required to be a string literal. + :param args: the values to print. They can be any tensor or scalar. + :param hex: print all values as hex instead of decimal + ''' + import string + prefix = _unwrap_if_constexpr(prefix) + assert isinstance(prefix, str), f"{prefix} is not string" + b_ascii = True + for ch in prefix: + if ch not in string.printable: + b_ascii = False + break + assert b_ascii, f"{prefix} is not an ascii string" + new_args = [] + for arg in args: + new_args.append(_semantic.to_tensor(arg)) + return _semantic.device_print(prefix, new_args, hex) + + +@builtin +def device_assert(cond, msg="", mask=None, _semantic=None): + ''' + Assert the condition at runtime from the device. Requires that the environment variable :code:`TRITON_DEBUG` + is set to a value besides :code:`0` in order for this to have any effect. + + Using the Python :code:`assert` statement is the same as calling this function, except that the second argument + must be provided and must be a string, e.g. :code:`assert pid == 0, "pid != 0"`. The environment variable must + be set for this :code:`assert` statement to have any effect. + + .. highlight:: python + .. code-block:: python + + tl.device_assert(pid == 0) + assert pid == 0, f"pid != 0" + + :param cond: the condition to assert. This is required to be a boolean tensor. + :param msg: the message to print if the assertion fails. This is required to be a string literal. + ''' + msg = _unwrap_if_constexpr(msg) + mask = _unwrap_if_constexpr(mask) + if mask is not None: + mask = _semantic.to_tensor(mask) + return _semantic.device_assert(_semantic.to_tensor(cond), msg, mask) + + +@builtin +def inline_asm_elementwise(asm: str, constraints: str, args: Sequence, dtype: Union[dtype, Sequence[dtype]], + is_pure: bool, pack: int, _semantic=None): + ''' + Execute inline assembly over a tensor. Essentially, this is :code:`map` + where the function is inline assembly. + + The input tensors :code:`args` are implicitly broadcasted to the same shape. + + :code:`dtype` can be a tuple of types, in which case the output is a + tuple of tensors. + + Each invocation of the inline asm processes :code:`pack` elements at a + time. Exactly which set of inputs a block receives is unspecified. + Input elements of size less than 4 bytes are packed into 4-byte + registers. + + This op does not support empty :code:`dtype` -- the inline asm must + return at least one tensor, even if you don't need it. You can work + around this by returning a dummy tensor of arbitrary type; it shouldn't + cost you anything if you don't use it. + + Example using + `PTX `_ + assembly: + + .. highlight:: python + .. code-block:: python + + @triton.jit + def kernel(A, B, C, D, BLOCK: tl.constexpr): + a = tl.load(A + tl.arange(0, BLOCK)) # uint8 tensor + b = tl.load(B + tl.arange(0, BLOCK)) # float32 tensor + + # For each (a,b) in zip(a,b), perform the following: + # - Let ai be `a` converted to int32. + # - Let af be `a` converted to float. + # - Let m be the max of ai and b. + # - Return ai and mi. + # Do the above 4 elements at a time. + (c, d) = tl.inline_asm_elementwise( + asm=""" + { + // Unpack `a` into `ai`. + .reg .b8 tmp<4>; + mov.b32 {tmp0, tmp1, tmp2, tmp3}, $8; + cvt.u32.u8 $0, tmp0; + cvt.u32.u8 $1, tmp1; + cvt.u32.u8 $2, tmp2; + cvt.u32.u8 $3, tmp3; + } + // Convert `ai` to float. + cvt.rn.f32.s32 $4, $0; + cvt.rn.f32.s32 $5, $1; + cvt.rn.f32.s32 $6, $2; + cvt.rn.f32.s32 $7, $3; + // Take max of `ai` and `b`. + max.f32 $4, $4, $9; + max.f32 $5, $5, $10; + max.f32 $6, $6, $11; + max.f32 $7, $7, $12; + """, + constraints=( + # 8 output registers, namely + # $0=ai0, $1=ai1, $2=ai2, $3=ai3, + # $4=m0, $5=m1, $6=m2, $7=m3. + "=r,=r,=r,=r,=r,=r,=r,=r," + # 5 input registers, namely + # $8=ai, + # $9=b0, $10=b1, $11=b2, $12=b3. + # The four elements from `a` are all packed into one register. + "r,r,r,r,r"), + args=[a, b], + dtype=(tl.int32, tl.float32), + is_pure=True, + pack=4, + ) + tl.store(C + tl.arange(0, BLOCK), c) + tl.store(D + tl.arange(0, BLOCK), d) + + :param asm: assembly to run. Must match target's assembly format. + :param constraints: asm constraints in + `LLVM format `_ + :param args: the input tensors, whose values are passed to the asm block + :param dtype: the element type(s) of the returned tensor(s) + :param is_pure: if true, the compiler assumes the asm block has no side-effects + :param pack: the number of elements to be processed by one instance of inline assembly + :return: one tensor or a tuple of tensors of the given dtypes + ''' + asm = _unwrap_if_constexpr(asm) + constraints = _unwrap_if_constexpr(constraints) + pack = _unwrap_if_constexpr(pack) + is_pure = _unwrap_if_constexpr(is_pure) + + # Wrap `dtype` in a tuple if it's not already. + try: + iter(dtype) # type: ignore + has_multiple_outputs = True + except TypeError: + has_multiple_outputs = False + dtype = (dtype, ) # type: ignore + + dtype = typing.cast(Sequence[_DtypeClass], dtype) + + res_tys = dtype + if dispatch_args := [_semantic.to_tensor(arg) for arg in args]: + bin_op_type_checking = partial( + _semantic.binary_op_type_checking_impl, + arithmetic_check=False, + allow_lhs_ptr=True, + allow_rhs_ptr=True, + ) + broadcast_arg = dispatch_args[0] + # Get the broadcast shape over all the arguments + for item in dispatch_args: + _, broadcast_arg = bin_op_type_checking(item, broadcast_arg) + if broadcast_arg.shape: + # Change the shape of each argument based on the broadcast shape + for i, item in enumerate(dispatch_args): + dispatch_args[i], _ = bin_op_type_checking(item, broadcast_arg) + res_tys = [broadcast_arg.type.with_element_ty(dt) for dt in dtype] + handles = [t.handle for t in dispatch_args] + builder = _semantic.builder + call = builder.create_inline_asm(asm, constraints, handles, [ty.to_ir(builder) for ty in res_tys], is_pure, pack) + + if not has_multiple_outputs: + return tensor(call.get_result(0), res_tys[0]) + return tuple(tensor(call.get_result(i), ty) for i, ty in enumerate(res_tys)) + + +# ----------------------- +# Iterators +# ----------------------- + + +class static_range(base_value): + """ + Iterator that counts upward forever. + + .. highlight:: python + .. code-block:: python + + @triton.jit + def kernel(...): + for i in tl.static_range(10): + ... + :note: This is a special iterator used to implement similar semantics to Python's :code:`range` in the context of + :code:`triton.jit` functions. In addition, it also guides the compiler to unroll the loop aggressively. + :param arg1: the start value. + :param arg2: the end value. + :param step: the step value. + """ + + def __init__(self, arg1, arg2=None, step=None): + assert isinstance(arg1, constexpr), f"{arg1} used as tl.static_range start value is not a constexpr" + if step is None: + self.step = constexpr(1) + else: + assert isinstance(step, constexpr), f"{step} used as tl.static_range step value is not a constexpr" + self.step = step + if arg2 is None: + self.start = constexpr(0) + self.end = arg1 + else: + assert isinstance(arg2, constexpr), f"{arg2} used as tl.static_range end value is not a constexpr" + self.start = arg1 + self.end = arg2 + + def __iter__(self): + raise RuntimeError("static_range can only be used in @triton.jit'd functions") + + def __next__(self): + raise RuntimeError("static_range can only be used in @triton.jit'd functions") + + +class async_task: + """ + Context manager to run code fragments asynchronously. + """ + + def __init__(self, task_ids, _builder=None): + self.task_ids = list({_unwrap_if_constexpr(tid) for tid in task_ids}) + self.builder = _builder + + def __enter__(self): + self.builder.set_async_task_ids(self.task_ids) + + def __exit__(self, exc_type, exc_value, traceback): + self.builder.unset_async_task_ids() + + +class range(base_value): + """ + Iterator that counts upward forever. + + .. highlight:: python + .. code-block:: python + + @triton.jit + def kernel(...): + for i in tl.range(10, num_stages=3): + ... + :note: This is a special iterator used to implement similar semantics to Python's :code:`range` in the context of + :code:`triton.jit` functions. In addition, it allows user to pass extra attributes to the compiler. + :param arg1: the start value. + :param arg2: the end value. + :param step: the step value. + :param num_stages: pipeline the loop into this many stages (so there are + :code:`num_stages` iterations of the loop in flight at once). + + Note this is subtly different than passing :code:`num_stages` as a + kernel argument. The kernel argument only pipelines loads that feed + into :code:`dot` operations, while this attribute tries to pipeline most + (though not all) loads in this loop. + :param loop_unroll_factor: Tells the Triton IR level loop unroller how many + times to unroll a for loop that this range is used with. Less than 2 for + this value implies no unrolling. + :param disallow_acc_multi_buffer: If true, prevent the accumulator of the dot + operation in the loop to be multi-buffered, if applicable. + :param flatten: automatically flatten the loop nest starting at this loop to + create a single flattened loop. The compiler will try to pipeline the + flattened loop which can avoid stage stalling. + :param warp_specialize: Enable automatic warp specialization on the loop. + The compiler will attempt to partition memory, MMA, and vector + operations in the loop into separate async partitions. This will + increase the total number of warps required by the kernel. + :param disable_licm: Tells the compiler it shouldn't hoist loop invariant + code outside the loop. This is often useful to avoid creating long liveranges + within a loop. + + Note that warp specialization is only supported on Blackwell GPUs and + only works on simple matmul loops. Support for arbitrary loops will be + expanded over time. + """ + + def __init__(self, arg1, arg2=None, step=None, num_stages=None, loop_unroll_factor=None, + disallow_acc_multi_buffer=False, flatten=False, warp_specialize=False, disable_licm=False): + if step is None: + self.step = constexpr(1) + else: + self.step = step + if arg2 is None: + self.start = constexpr(0) + self.end = arg1 + else: + self.start = arg1 + self.end = arg2 + self.num_stages = num_stages + self.loop_unroll_factor = loop_unroll_factor + self.disallow_acc_multi_buffer = disallow_acc_multi_buffer + self.flatten = flatten + self.warp_specialize = warp_specialize + self.disable_licm = disable_licm + + def __iter__(self): + raise RuntimeError("tl.range can only be used in @triton.jit'd functions") + + def __next__(self): + raise RuntimeError("tl.range can only be used in @triton.jit'd functions") + + +class condition(base_value): + """ + While loop condition wrapper. + + .. highlight:: python + .. code-block:: python + + @triton.jit + def kernel(...): + while tl.condition(c, disable_licm) + ... + :note: This is a special wrapper used to annotate while loops in the context of + :code:`triton.jit` functions. It allows user to pass extra attributes to the compiler. + :param disable_licm: Tells the compiler it shouldn't hoist loop invariant + code outside the loop. This is often useful to avoid creating long liveranges + within a loop. + """ + + def __init__(self, arg1, disable_licm=False): + self.condition = arg1 + self.disable_licm = disable_licm + + +# ----------------------- +# Extern functions +# ----------------------- + + +def dispatch(func, lib_name: str, lib_path: str, args: list, arg_type_symbol_dict: dict, ret_type: dtype, is_pure: bool, + _semantic): + ''' + Dispatch a function to a library + :param func: the function to dispatch + :param lib_name: the name of the library + :param lib_path: the path of the library + :param args: the arguments of the function + :param arg_type_symbol_dict: the type of the arguments + :param ret_type: the type of the return value + :return: the return value of the function + ''' + if len(arg_type_symbol_dict) == 0: + raise ValueError("arg_type_symbol_dict is empty") + + num_args = len(list(arg_type_symbol_dict.keys())[0]) + if len(args) != num_args: + raise ValueError(f"length of input args does not match." + f"Expect {len(args)}, got {num_args}") + + arg_types = [] + arg_list = [] + for arg in args: + if isinstance(arg, tensor): + arg_types.append(arg.dtype) + arg_list.append(arg.handle) + else: + arg_types.append(type(arg)) + arg_list.append(arg) + arg_types = tuple(arg_types) + + if arg_types not in arg_type_symbol_dict: + raise ValueError(f"input arg type does not match." + f"Expect one of {arg_type_symbol_dict.keys()}, got {arg_types}") + else: + symbol = arg_type_symbol_dict[arg_types][0] + builder = _semantic.builder + return tensor(func(lib_name, lib_path, symbol, arg_list, ret_type.to_ir(builder), is_pure), ret_type) + + +@builtin +def extern_elementwise(lib_name: str, lib_path: str, args: list, arg_type_symbol_dict: dict, is_pure: bool, + _semantic=None): + ''' + Dispatch an elementwise function to a library + :param lib_name: the name of the library + :param lib_path: the path of the library + :param args: the arguments of the function + :param arg_type_symbol_dict: the type of the arguments + :param is_pure: whether the function is pure + :return: the return value of the function + ''' + dispatch_args = args.copy() + all_scalar = True + arg_types = [] + for i in builtins.range(len(dispatch_args)): + dispatch_args[i] = _semantic.to_tensor(dispatch_args[i]) + arg_types.append(dispatch_args[i].dtype) + if dispatch_args[i].type.is_block(): + all_scalar = False + + arg_types = tuple(arg_types) + ret_type = arg_type_symbol_dict[arg_types][1] + if len(arg_types) > 0: + arithmetic_check = True + # If there's a type tuple that is not supported by the library, we will do arithmetic check + if arg_types in arg_type_symbol_dict: + arithmetic_check = False + broadcast_arg = dispatch_args[0] + # Get the broadcast shape over all the arguments + for item in dispatch_args: + _, broadcast_arg = _semantic.binary_op_type_checking_impl(item, broadcast_arg, + arithmetic_check=arithmetic_check) + # Change the shape of each argument based on the broadcast shape + for i in builtins.range(len(dispatch_args)): + dispatch_args[i], _ = _semantic.binary_op_type_checking_impl(dispatch_args[i], broadcast_arg, + arithmetic_check=arithmetic_check) + if not all_scalar: + ret_type = broadcast_arg.type.with_element_ty(ret_type) + func = _semantic.builder.create_extern_elementwise + return dispatch(func, lib_name, lib_path, dispatch_args, arg_type_symbol_dict, ret_type, is_pure, _semantic) + + +def binary_op_type_legalization(lhs, rhs, semantic): + ''' + Convert both operands to a single common type + :param lhs: the left operand + :param rhs: the right operand + :param builder: the builder + ''' + return semantic.binary_op_type_checking_impl(lhs, rhs) + + +def extern(fn): + """A decorator for external functions.""" + return builtin(fn) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3f8c70a716a3da3473a4906b44aec7d35fcc35a5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/__init__.py @@ -0,0 +1,26 @@ +import pkgutil +from importlib.util import module_from_spec +from sys import modules + +_backends = [] +for module_finder, module_name, is_pkg in pkgutil.iter_modules( + __path__, + prefix=__name__ + ".", +): + # skip .py files (like libdevice.py) + if not is_pkg: + continue + + # import backends (like cuda and hip) that are included during setup.py + spec = module_finder.find_spec(module_name) + if spec is None or spec.loader is None: + continue + module = module_from_spec(spec) + spec.loader.exec_module(module) + + _backends.append(module_name) + modules[module_name] = module + +__all__ = _backends + +del _backends diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a5218cc6fb7ef1affebb8f741e8e14184fdd084 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fbececf1defce4a9493a9e75cc7cb39571465175 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/__init__.py @@ -0,0 +1,16 @@ +from . import libdevice + +from .utils import (globaltimer, num_threads, num_warps, smid, convert_custom_float8_sm70, convert_custom_float8_sm80) +from .gdc import (gdc_launch_dependents, gdc_wait) + +__all__ = [ + "libdevice", + "globaltimer", + "num_threads", + "num_warps", + "smid", + "convert_custom_float8_sm70", + "convert_custom_float8_sm80", + "gdc_launch_dependents", + "gdc_wait", +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..543f768ede4c4fd3b1085d7baba9f1048fe90088 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/__pycache__/gdc.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/__pycache__/gdc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..539409523067629b9494fa5b0d9595b4a2c1fe33 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/__pycache__/gdc.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/__pycache__/libdevice.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/__pycache__/libdevice.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce38c211cf70b5fee4627f4d503818d7286e2647 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/__pycache__/libdevice.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/__pycache__/utils.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..226e6f0c1b642714622a36f4f18f657f8d022289 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/__pycache__/utils.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/gdc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/gdc.py new file mode 100644 index 0000000000000000000000000000000000000000..4376719e3dbe63ac2dfe65bfc6bf936116056676 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/gdc.py @@ -0,0 +1,42 @@ +""" +Grid Dependency Control (GDC) is a mechanism used when enabling programmatic dependent launch to launch and +synchronize grids. These APIs expose GDC to the programmer. + +Programmatic dependent launch is supported on SM90 (Hopper) and beyond. +For PTX reference on grid dependency control see https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#parallel-synchronization-and-communication-instructions-griddepcontrol. +""" + +from triton.language import core + + +@core.extern +def gdc_wait(_semantic=None): + """ + GDC wait is a blocking instruction that waits for all instructions in a prior kernel to complete before continuing. + This ensures all memory operations happening before the wait is visible to instructions after it, + e.g. if the prior kernel writes to address "x" the new values will be visible in this kernel after the wait. + + This instruction is also safe to execute when programmatic dependent launch is disabled. + + See https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#parallel-synchronization-and-communication-instructions-griddepcontrol for more details. + """ + core.inline_asm_elementwise("griddepcontrol.wait; // dummy $0", "=r", [], dtype=core.int32, is_pure=False, pack=1, + _semantic=_semantic) + + +@core.extern +def gdc_launch_dependents(_semantic=None): + """ + This operation when launched with programmatic dependent launch signals that + the next program may launch once all programs in the current kernel + call this function or complete. + + Repeated calls to this function have no effect past the first call, and the first call should be + treated by the programmer as a hint to the runtime system to launch the next kernel. + + This instruction is also safe to execute when programmatic dependent launch is disabled. + + See https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#parallel-synchronization-and-communication-instructions-griddepcontrol for more details. + """ + core.inline_asm_elementwise("griddepcontrol.launch_dependents; // dummy $0", "=r", [], dtype=core.int32, + is_pure=False, pack=1, _semantic=_semantic) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/libdevice.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/libdevice.py new file mode 100644 index 0000000000000000000000000000000000000000..08661f5414a68f43b1fe35a2de945ed30322d73f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/libdevice.py @@ -0,0 +1,1629 @@ +from triton.language import core + + +@core.extern +def clz(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("int32"), ): ("__nv_clz", core.dtype("int32")), + (core.dtype("int64"), ): ("__nv_clzll", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def popc(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("int32"), ): ("__nv_popc", core.dtype("int32")), + (core.dtype("int64"), ): ("__nv_popcll", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def byte_perm(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise("", "", [arg0, arg1, arg2], { + (core.dtype("int32"), core.dtype("int32"), core.dtype("int32")): ("__nv_byte_perm", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def mulhi(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("int32"), core.dtype("int32")): ("__nv_mulhi", core.dtype("int32")), + (core.dtype("uint32"), core.dtype("uint32")): ("__nv_umulhi", core.dtype("uint32")), + (core.dtype("int64"), core.dtype("int64")): ("__nv_mul64hi", core.dtype("int64")), + (core.dtype("uint64"), core.dtype("uint64")): ("__nv_umul64hi", core.dtype("uint64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def mul24(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("int32"), core.dtype("int32")): ("__nv_mul24", core.dtype("int32")), + (core.dtype("uint32"), core.dtype("uint32")): ("__nv_umul24", core.dtype("uint32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def brev(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("int32"), ): ("__nv_brev", core.dtype("int32")), + (core.dtype("int64"), ): ("__nv_brevll", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sad(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("int32"), core.dtype("int32"), core.dtype("uint32")): ("__nv_sad", core.dtype("int32")), + (core.dtype("uint32"), core.dtype("uint32"), core.dtype("uint32")): ("__nv_usad", core.dtype("uint32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def abs(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("int32"), ): ("__nv_abs", core.dtype("int32")), + (core.dtype("int64"), ): ("__nv_llabs", core.dtype("int64")), + (core.dtype("fp32"), ): ("__nv_fabsf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_fabs", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def floor(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_floorf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_floor", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rcp64h(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_rcp64h", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rsqrt(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_rsqrtf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_rsqrt", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ceil(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_ceil", core.dtype("fp64")), + (core.dtype("fp32"), ): ("__nv_ceilf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def trunc(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_trunc", core.dtype("fp64")), + (core.dtype("fp32"), ): ("__nv_truncf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def exp2(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_exp2f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_exp2", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def saturatef(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_saturatef", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fma_rn(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmaf_rn", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__nv_fma_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fma_rz(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmaf_rz", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__nv_fma_rz", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fma_rd(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmaf_rd", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__nv_fma_rd", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fma_ru(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmaf_ru", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__nv_fma_ru", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_dividef(arg0, arg1, _semantic=None): + return core.extern_elementwise("", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fast_fdividef", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def div_rn(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fdiv_rn", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_ddiv_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def div_rz(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fdiv_rz", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_ddiv_rz", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def div_rd(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fdiv_rd", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_ddiv_rd", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def div_ru(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fdiv_ru", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_ddiv_ru", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rcp_rn(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_frcp_rn", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_drcp_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rcp_rz(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_frcp_rz", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_drcp_rz", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rcp_rd(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_frcp_rd", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_drcp_rd", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rcp_ru(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_frcp_ru", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_drcp_ru", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sqrt_rn(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fsqrt_rn", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_dsqrt_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sqrt_rz(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fsqrt_rz", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_dsqrt_rz", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sqrt_rd(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fsqrt_rd", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_dsqrt_rd", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sqrt_ru(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fsqrt_ru", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_dsqrt_ru", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sqrt(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_sqrtf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_sqrt", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def add_rn(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dadd_rn", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fadd_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def add_rz(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dadd_rz", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fadd_rz", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def add_rd(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dadd_rd", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fadd_rd", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def add_ru(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dadd_ru", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fadd_ru", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def mul_rn(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dmul_rn", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmul_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def mul_rz(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dmul_rz", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmul_rz", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def mul_rd(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dmul_rd", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmul_rd", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def mul_ru(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + arg1, + ], { + ( + core.dtype("fp64"), + core.dtype("fp64"), + ): ("__nv_dmul_ru", core.dtype("fp64")), + ( + core.dtype("fp32"), + core.dtype("fp32"), + ): ("__nv_fmul_ru", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2float_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2float_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2float_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2float_rz", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2float_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2float_rd", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2float_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2float_ru", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2int_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2int_rn", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2int_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2int_rz", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2int_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2int_rd", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2int_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2int_ru", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2uint_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2uint_rn", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2uint_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2uint_rz", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2uint_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2uint_rd", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2uint_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2uint_ru", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def int2double_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int32"), ): ("__nv_int2double_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def uint2double_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint32"), ): ("__nv_uint2double_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2int_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2int_rn", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2int_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2int_rz", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2int_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2int_rd", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2int_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2int_ru", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2uint_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2uint_rn", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2uint_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2uint_rz", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2uint_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2uint_rd", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2uint_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2uint_ru", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def int2float_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int32"), ): ("__nv_int2float_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def int2float_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int32"), ): ("__nv_int2float_rz", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def int2float_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int32"), ): ("__nv_int2float_rd", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def int2float_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int32"), ): ("__nv_int2float_ru", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def uint2float_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint32"), ): ("__nv_uint2float_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def uint2float_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint32"), ): ("__nv_uint2float_rz", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def uint2float_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint32"), ): ("__nv_uint2float_rd", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def uint2float_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint32"), ): ("__nv_uint2float_ru", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def hiloint2double(arg0, arg1, _semantic=None): + return core.extern_elementwise("", "", [arg0, arg1], { + (core.dtype("int32"), core.dtype("int32")): ("__nv_hiloint2double", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2loint(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2loint", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2hiint(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2hiint", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ll_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ll_rn", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ll_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ll_rz", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ll_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ll_rd", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ll_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ll_ru", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ull_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ull_rn", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ull_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ull_rz", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ull_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ull_rd", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ull_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ull_ru", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ll_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ll_rn", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ll_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ll_rz", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ll_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ll_rd", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ll_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ll_ru", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ull_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ull_rn", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ull_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ull_rz", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ull_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ull_rd", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ull_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ull_ru", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2float_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2float_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2float_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2float_rz", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2float_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2float_rd", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2float_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2float_ru", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2float_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2float_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2float_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2float_rz", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2float_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2float_rd", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2float_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2float_ru", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2double_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2double_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2double_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2double_rz", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2double_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2double_rd", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2double_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2double_ru", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2double_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2double_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2double_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2double_rz", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2double_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2double_rd", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2double_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2double_ru", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def int_as_float(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int32"), ): ("__nv_int_as_float", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float_as_int(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float_as_int", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def uint_as_float(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint32"), ): ("__nv_uint_as_float", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float_as_uint(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float_as_uint", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def longlong_as_double(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_longlong_as_double", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double_as_longlong(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double_as_longlong", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_sinf(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_sinf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_cosf(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_cosf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_log2f(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_log2f", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_logf(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_logf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_expf(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_expf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_tanf(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_tanf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_exp10f(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_exp10f", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_log10f(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_log10f", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_powf(arg0, arg1, _semantic=None): + return core.extern_elementwise("", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fast_powf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def hadd(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("int32"), core.dtype("int32")): ("__nv_hadd", core.dtype("int32")), + (core.dtype("uint32"), core.dtype("uint32")): ("__nv_uhadd", core.dtype("uint32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rhadd(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("int32"), core.dtype("int32")): ("__nv_rhadd", core.dtype("int32")), + (core.dtype("uint32"), core.dtype("uint32")): ("__nv_urhadd", core.dtype("uint32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sub_rn(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fsub_rn", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dsub_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sub_rz(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fsub_rz", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dsub_rz", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sub_rd(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fsub_rd", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dsub_rd", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sub_ru(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fsub_ru", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dsub_ru", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rsqrt_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__nv_frsqrt_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ffs(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("int32"), ): ("__nv_ffs", core.dtype("int32")), + (core.dtype("int64"), ): ("__nv_ffsll", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rint(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__nv_rintf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_rint", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def llrint(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__nv_llrintf", core.dtype("int64")), + (core.dtype("fp64"), ): ("__nv_llrint", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def nearbyint(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__nv_nearbyintf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_nearbyint", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def isnan(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__nv_isnanf", core.dtype("int32")), + (core.dtype("fp64"), ): ("__nv_isnand", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic).to(core.int1, _semantic=_semantic) + + +@core.extern +def signbit(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__nv_signbitf", core.dtype("int32")), + (core.dtype("fp64"), ): ("__nv_signbitd", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def copysign(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_copysignf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_copysign", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def finitef(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_finitef", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic).to(core.int1, _semantic=_semantic) + + +@core.extern +def isinf(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_isinff", core.dtype("int32")), + (core.dtype("fp64"), ): ("__nv_isinfd", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic).to(core.int1, _semantic=_semantic) + + +@core.extern +def nextafter(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_nextafterf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_nextafter", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sin(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_sinf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_sin", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cos(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_cosf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_cos", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sinpi(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_sinpif", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_sinpi", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cospi(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_cospif", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_cospi", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def tan(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_tanf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_tan", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log2(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_log2f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_log2", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def exp(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_expf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_exp", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def exp10(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_exp10f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_exp10", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cosh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_coshf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_cosh", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sinh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_sinhf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_sinh", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def tanh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_tanhf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_tanh", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def atan2(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_atan2f", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_atan2", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def atan(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_atanf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_atan", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def asin(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_asinf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_asin", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def acos(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_acosf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_acos", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_logf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_log", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log10(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_log10f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_log10", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log1p(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_log1pf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_log1p", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def acosh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_acoshf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_acosh", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def asinh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_asinhf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_asinh", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def atanh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_atanhf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_atanh", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def expm1(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_expm1f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_expm1", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def hypot(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_hypotf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_hypot", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rhypot(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_rhypotf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_rhypot", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def norm3d(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__nv_norm3df", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__nv_norm3d", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rnorm3d(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__nv_rnorm3df", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__nv_rnorm3d", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def norm4d(arg0, arg1, arg2, arg3, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2, arg3], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): + ("__nv_norm4df", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): + ("__nv_norm4d", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rnorm4d(arg0, arg1, arg2, arg3, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2, arg3], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): + ("__nv_rnorm4df", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): + ("__nv_rnorm4d", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cbrt(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_cbrtf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_cbrt", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rcbrt(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_rcbrtf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_rcbrt", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def j0(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_j0f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_j0", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def j1(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_j1f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_j1", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def y0(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_y0f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_y0", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def y1(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_y1f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_y1", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def yn(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("int32"), core.dtype("fp32")): ("__nv_ynf", core.dtype("fp32")), + (core.dtype("int32"), core.dtype("fp64")): ("__nv_yn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def jn(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("int32"), core.dtype("fp32")): ("__nv_jnf", core.dtype("fp32")), + (core.dtype("int32"), core.dtype("fp64")): ("__nv_jn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cyl_bessel_i0(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_cyl_bessel_i0f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_cyl_bessel_i0", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cyl_bessel_i1(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_cyl_bessel_i1f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_cyl_bessel_i1", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erf(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_erff", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_erf", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erfinv(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_erfinvf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_erfinv", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erfc(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_erfcf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_erfc", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erfcx(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_erfcxf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_erfcx", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erfcinv(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_erfcinvf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_erfcinv", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def normcdfinv(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_normcdfinvf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_normcdfinv", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def normcdf(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_normcdff", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_normcdf", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def lgamma(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_lgammaf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_lgamma", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ldexp(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("int32")): ("__nv_ldexpf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("int32")): ("__nv_ldexp", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def scalbn(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("int32")): ("__nv_scalbnf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("int32")): ("__nv_scalbn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fmod(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmodf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_fmod", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def remainder(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_remainderf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_remainder", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fma(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmaf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__nv_fma", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def pow(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("int32")): ("__nv_powif", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("int32")): ("__nv_powi", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_powf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_pow", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def tgamma(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_tgammaf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_tgamma", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def round(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_roundf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_round", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def llround(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_llroundf", core.dtype("int64")), + (core.dtype("fp64"), ): ("__nv_llround", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fdim(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fdimf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_fdim", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ilogb(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_ilogbf", core.dtype("int32")), + (core.dtype("fp64"), ): ("__nv_ilogb", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def logb(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_logbf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_logb", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def isfinited(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_isfinited", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic).to(core.int1, _semantic=_semantic) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/utils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bb67b573a381156e7713a3359db859409701d7d7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/cuda/utils.py @@ -0,0 +1,109 @@ +from triton.language import core + + +@core.extern +def globaltimer(_semantic=None): + return core.inline_asm_elementwise("mov.u64 $0, %globaltimer;", "=l", [], dtype=core.int64, is_pure=False, pack=1, + _semantic=_semantic) + + +@core.extern +def smid(_semantic=None): + return core.inline_asm_elementwise("mov.u32 $0, %smid;", "=r", [], dtype=core.int32, is_pure=True, pack=1, + _semantic=_semantic) + + +@core.builtin +def num_threads(_semantic=None): + return core.constexpr(_semantic.builder.options.num_warps * 32) + + +@core.builtin +def num_warps(_semantic=None): + return core.constexpr(_semantic.builder.options.num_warps) + + +# ----- FP8E4M3B15 ------ +# This data-type is a variant of the standard FP8E4M3 format. +# It was designed for fast software conversion to FP16 on +# nvidia GPUs that do not support it natively. +# This is the same format as FP8E4M3Nv, but: +# - the exponent bias is 15 instead of 7 +# - 0xff and 0x7f are mapped to +-1.750 instead of +-nan +@core.builtin +def convert_fp8e4b15_to_float16(arg, _semantic=None): + return core.inline_asm_elementwise( + "{ \n" + ".reg .b32 a<2>, b<2>; \n" + "prmt.b32 a0, 0, $2, 0x5746; \n" + "and.b32 b0, a0, 0x7f007f00; \n" + "and.b32 b1, a0, 0x00ff00ff; \n" + "and.b32 a1, a0, 0x00800080; \n" + "shr.b32 b0, b0, 1; \n" + "add.u32 b1, b1, a1; \n" + "lop3.b32 $0, b0, 0x80008000, a0, 0xf8; \n" + "shl.b32 $1, b1, 7; \n" + "} \n", "=r,=r,r", [arg], dtype=core.float16, is_pure=True, pack=4, + _semantic=_semantic) + + +@core.builtin +def convert_float16_to_fp8e4b15(arg, has_minx2, _semantic=None): + asm = """{ + .reg .pred p<4>; + .reg .b32 a<2>, b<2>; + .reg .b16 c<4>; + .reg .b16 max_val_f16; + .reg .b32 max_val_f16x2; + mov.b16 max_val_f16, 0x3F00; + mov.b32 max_val_f16x2, 0x3F003F00; + and.b32 a0, $1, 0x7fff7fff; + and.b32 a1, $2, 0x7fff7fff;""" + if has_minx2: + asm += """min.f16x2 a0, a0, max_val_f16x2; + min.f16x2 a1, a1, max_val_f16x2;""" + else: + asm += """setp.lt.f16x2 p0|p1, a0, max_val_f16x2; + setp.lt.f16x2 p2|p3, a1, max_val_f16x2; + mov.b32 {c0, c1}, a0; + mov.b32 {c2, c3}, a1; + selp.b16 c0, c0, max_val_f16, p0; + selp.b16 c1, c1, max_val_f16, p1; + selp.b16 c2, c2, max_val_f16, p2; + selp.b16 c3, c3, max_val_f16, p3; + mov.b32 a0, {c0, c1}; + mov.b32 a1, {c2, c3};""" + asm += """mad.lo.u32 a0, a0, 2, 0x00800080; + mad.lo.u32 a1, a1, 2, 0x00800080; + lop3.b32 b0, $1, 0x80008000, a0, 0xea; + lop3.b32 b1, $2, 0x80008000, a1, 0xea; + prmt.b32 $0, b0, b1, 0x7531; + }""" + return core.inline_asm_elementwise(asm, "=r,r,r", [arg], dtype=core.float8e4b15, is_pure=True, pack=4, + _semantic=_semantic) + + +@core.builtin +def convert_custom_float8(arg, dst_ty, fp_downcast_rounding, has_minx2, _semantic=None): + if arg.type.scalar.is_fp8e4b15(): + upcast_val = convert_fp8e4b15_to_float16(arg, _semantic=_semantic) + if dst_ty.scalar.is_fp32(): + upcast_val = upcast_val.to(core.float32, _semantic=_semantic) + return upcast_val + + assert arg.type.scalar.is_fp16() or arg.type.scalar.is_fp32() + downcast_val = arg + if arg.type.scalar.is_fp32(): + downcast_val = downcast_val.to(core.float16, fp_downcast_rounding="rtz", _semantic=_semantic) + downcast_val = convert_float16_to_fp8e4b15(downcast_val, has_minx2=has_minx2, _semantic=_semantic) + return downcast_val + + +@core.builtin +def convert_custom_float8_sm80(arg, dst_ty, fp_downcast_rounding=None, _semantic=None): + return convert_custom_float8(arg, dst_ty, fp_downcast_rounding, has_minx2=True, _semantic=_semantic) + + +@core.builtin +def convert_custom_float8_sm70(arg, dst_ty, fp_downcast_rounding=None, _semantic=None): + return convert_custom_float8(arg, dst_ty, fp_downcast_rounding, has_minx2=False, _semantic=_semantic) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9b571ddfacbd15b1e8258cce592313f7d45a3e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/__init__.py @@ -0,0 +1,5 @@ +from . import libdevice + +from .utils import memrealtime + +__all__ = ["libdevice", "memrealtime"] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d0e18f6ff9c55dede381aac5e48fbeba3ed34c1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/__pycache__/libdevice.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/__pycache__/libdevice.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e13c91b478d7f2ccf19f5e0507fdf48bee2a6e46 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/__pycache__/libdevice.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/__pycache__/utils.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8de95539c3380e26266dd85a759f6c3d6f6c8531 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/__pycache__/utils.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/libdevice.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/libdevice.py new file mode 100644 index 0000000000000000000000000000000000000000..fc8d1b11a80299ae9f203bc48f039020faa80353 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/libdevice.py @@ -0,0 +1,491 @@ +from triton.language import core + + +@core.extern +def abs(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("int32"), ): ("__triton_hip_iabs", core.dtype("int32")), + (core.dtype("int64"), ): ("__triton_hip_iabs", core.dtype("int64")), + (core.dtype("fp32"), ): ("__triton_hip_fabs", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__triton_hip_fabs", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def floor(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_floor_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_floor_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rsqrt(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_rsqrt_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_rsqrt_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ceil(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_ceil_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_ceil_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def trunc(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_trunc_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_trunc_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def exp2(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_exp2_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_exp2_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def exp(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_exp_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_exp_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_expf(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__triton_hip_fast_expf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_tanhf(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__triton_hip_fast_tanhf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_dividef(arg0, arg1, _semantic=None): + return core.extern_elementwise("", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__triton_hip_fast_fdividef", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sqrt(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_sqrt_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_sqrt_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def llrint(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__triton_hip_llrint", core.dtype("int64")), + (core.dtype("fp64"), ): ("__triton_hip_llrint", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def nearbyint(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__ocml_nearbyint_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_nearbyint_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def isnan(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__ocml_isnan_f32", core.dtype("int32")), + (core.dtype("fp64"), ): ("__ocml_isnan_f64", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic).to(core.int1, _semantic=_semantic) + + +@core.extern +def signbit(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__ocml_signbit_f32", core.dtype("int32")), + (core.dtype("fp64"), ): ("__ocml_signbit_f64", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def copysign(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__ocml_copysign_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__ocml_copysign_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def isinf(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_isinf_f32", core.dtype("int32")), + (core.dtype("fp64"), ): ("__ocml_isinf_f64", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic).to(core.int1, _semantic=_semantic) + + +@core.extern +def nextafter(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__ocml_nextafter_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__ocml_nextafter_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sin(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_sin_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_sin_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cos(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_cos_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_cos_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def tan(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_tan_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_tan_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log2(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_log2_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_log2_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cosh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_cosh_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_cosh_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sinh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_sinh_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_sinh_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def tanh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_tanh_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_tanh_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def atan2(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__ocml_atan2_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__ocml_atan2_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def atan(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_atan_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_atan_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def asin(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_asin_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_asin_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def acos(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_acos_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_acos_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_log_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_log_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log10(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_log10_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_log10_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log1p(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_log1p_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_log1p_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def acosh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_acosh_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_acosh_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def asinh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_asinh_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_asinh_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def atanh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_atanh_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_atanh_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def expm1(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_expm1_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_expm1_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def hypot(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__ocml_hypot_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__ocml_hypot_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def j0(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_j0_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_j0_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def j1(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_j1_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_j1_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def y0(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_y0_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_y0_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def y1(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_y1_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_y1_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cyl_bessel_i0(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_i0_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_i0_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cyl_bessel_i1(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_i1_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_i1_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erf(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_erf_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_erf_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erfinv(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_erfinv_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_erfinv_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erfc(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_erfc_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_erfc_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erfcx(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_erfcx_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_erfcx_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def lgamma(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_lgamma_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_lgamma_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ldexp(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("int32")): ("__ocml_ldexp_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("int32")): ("__ocml_ldexp_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fmod(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__ocml_fmod_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__ocml_fmod_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fma(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__ocml_fma_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__ocml_fma_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def pow(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("int32")): ("__ocml_pown_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("int32")): ("__ocml_pown_f64", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__ocml_pow_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__ocml_pow_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ilogb(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_ilogb_f32", core.dtype("int32")), + (core.dtype("fp64"), ): ("__ocml_ilogb_f64", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def round(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_round_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_round_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/utils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c9dbabc4d3cfdbd5ee91b38ef3be969b9f187046 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/hip/utils.py @@ -0,0 +1,35 @@ +from triton.language import core + + +@core.extern +def memrealtime(_semantic=None): + """ + Returns a 64-bit real time-counter value + """ + target_arch = _semantic.builder.options.arch + if 'gfx11' in target_arch or 'gfx12' in target_arch: + return core.inline_asm_elementwise( + """ + s_sendmsg_rtn_b64 $0, sendmsg(MSG_RTN_GET_REALTIME) + s_waitcnt lgkmcnt(0) + """, + "=r", + [], + dtype=core.int64, + is_pure=False, + pack=1, + _semantic=_semantic, + ) + else: + return core.inline_asm_elementwise( + """ + s_memrealtime $0 + s_waitcnt vmcnt(0) + """, + "=r", + [], + dtype=core.int64, + is_pure=False, + pack=1, + _semantic=_semantic, + ) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/libdevice.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/libdevice.py new file mode 100644 index 0000000000000000000000000000000000000000..e29810bfbabdcc09d6a28f062c18ee6af3fe7575 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/extra/libdevice.py @@ -0,0 +1,790 @@ +def clz(arg0): + ... + + +def popc(arg0): + ... + + +def byte_perm(arg0, arg1, arg2): + ... + + +def mulhi(arg0, arg1): + ... + + +def mul24(arg0, arg1): + ... + + +def brev(arg0): + ... + + +def sad(arg0, arg1, arg2): + ... + + +def abs(arg0): + ... + + +def floor(arg0): + ... + + +def rcp64h(arg0): + ... + + +def rsqrt(arg0): + ... + + +def ceil(arg0): + ... + + +def trunc(arg0): + ... + + +def exp2(arg0): + ... + + +def saturatef(arg0): + ... + + +def fma_rn(arg0, arg1, arg2): + ... + + +def fma_rz(arg0, arg1, arg2): + ... + + +def fma_rd(arg0, arg1, arg2): + ... + + +def fma_ru(arg0, arg1, arg2): + ... + + +def fast_dividef(arg0, arg1): + ... + + +def div_rn(arg0, arg1): + ... + + +def div_rz(arg0, arg1): + ... + + +def div_rd(arg0, arg1): + ... + + +def div_ru(arg0, arg1): + ... + + +def rcp_rn(arg0): + ... + + +def rcp_rz(arg0): + ... + + +def rcp_rd(arg0): + ... + + +def rcp_ru(arg0): + ... + + +def sqrt_rn(arg0): + ... + + +def sqrt_rz(arg0): + ... + + +def sqrt_rd(arg0): + ... + + +def sqrt_ru(arg0): + ... + + +def sqrt(arg0): + ... + + +def add_rn(arg0, arg1): + ... + + +def add_rz(arg0, arg1): + ... + + +def add_rd(arg0, arg1): + ... + + +def add_ru(arg0, arg1): + ... + + +def mul_rn(arg0, arg1): + ... + + +def mul_rz(arg0, arg1): + ... + + +def mul_rd(arg0, arg1): + ... + + +def mul_ru(arg0, arg1): + ... + + +def double2float_rn(arg0): + ... + + +def double2float_rz(arg0): + ... + + +def double2float_rd(arg0): + ... + + +def double2float_ru(arg0): + ... + + +def double2int_rn(arg0): + ... + + +def double2int_rz(arg0): + ... + + +def double2int_rd(arg0): + ... + + +def double2int_ru(arg0): + ... + + +def double2uint_rn(arg0): + ... + + +def double2uint_rz(arg0): + ... + + +def double2uint_rd(arg0): + ... + + +def double2uint_ru(arg0): + ... + + +def int2double_rn(arg0): + ... + + +def uint2double_rn(arg0): + ... + + +def float2int_rn(arg0): + ... + + +def float2int_rz(arg0): + ... + + +def float2int_rd(arg0): + ... + + +def float2int_ru(arg0): + ... + + +def float2uint_rn(arg0): + ... + + +def float2uint_rz(arg0): + ... + + +def float2uint_rd(arg0): + ... + + +def float2uint_ru(arg0): + ... + + +def int2float_rn(arg0): + ... + + +def int2float_rz(arg0): + ... + + +def int2float_rd(arg0): + ... + + +def int2float_ru(arg0): + ... + + +def uint2float_rn(arg0): + ... + + +def uint2float_rz(arg0): + ... + + +def uint2float_rd(arg0): + ... + + +def uint2float_ru(arg0): + ... + + +def hiloint2double(arg0, arg1): + ... + + +def double2loint(arg0): + ... + + +def double2hiint(arg0): + ... + + +def float2ll_rn(arg0): + ... + + +def float2ll_rz(arg0): + ... + + +def float2ll_rd(arg0): + ... + + +def float2ll_ru(arg0): + ... + + +def float2ull_rn(arg0): + ... + + +def float2ull_rz(arg0): + ... + + +def float2ull_rd(arg0): + ... + + +def float2ull_ru(arg0): + ... + + +def double2ll_rn(arg0): + ... + + +def double2ll_rz(arg0): + ... + + +def double2ll_rd(arg0): + ... + + +def double2ll_ru(arg0): + ... + + +def double2ull_rn(arg0): + ... + + +def double2ull_rz(arg0): + ... + + +def double2ull_rd(arg0): + ... + + +def double2ull_ru(arg0): + ... + + +def ll2float_rn(arg0): + ... + + +def ll2float_rz(arg0): + ... + + +def ll2float_rd(arg0): + ... + + +def ll2float_ru(arg0): + ... + + +def ull2float_rn(arg0): + ... + + +def ull2float_rz(arg0): + ... + + +def ull2float_rd(arg0): + ... + + +def ull2float_ru(arg0): + ... + + +def ll2double_rn(arg0): + ... + + +def ll2double_rz(arg0): + ... + + +def ll2double_rd(arg0): + ... + + +def ll2double_ru(arg0): + ... + + +def ull2double_rn(arg0): + ... + + +def ull2double_rz(arg0): + ... + + +def ull2double_rd(arg0): + ... + + +def ull2double_ru(arg0): + ... + + +def int_as_float(arg0): + ... + + +def float_as_int(arg0): + ... + + +def uint_as_float(arg0): + ... + + +def float_as_uint(arg0): + ... + + +def longlong_as_double(arg0): + ... + + +def double_as_longlong(arg0): + ... + + +def fast_sinf(arg0): + ... + + +def fast_cosf(arg0): + ... + + +def fast_log2f(arg0): + ... + + +def fast_logf(arg0): + ... + + +def fast_expf(arg0): + ... + + +def fast_tanhf(arg0): + ... + + +def fast_tanf(arg0): + ... + + +def fast_exp10f(arg0): + ... + + +def fast_log10f(arg0): + ... + + +def fast_powf(arg0, arg1): + ... + + +def hadd(arg0, arg1): + ... + + +def rhadd(arg0, arg1): + ... + + +def sub_rn(arg0, arg1): + ... + + +def sub_rz(arg0, arg1): + ... + + +def sub_rd(arg0, arg1): + ... + + +def sub_ru(arg0, arg1): + ... + + +def rsqrt_rn(arg0): + ... + + +def ffs(arg0): + ... + + +def rint(arg0): + ... + + +def llrint(arg0): + ... + + +def nearbyint(arg0): + ... + + +def isnan(arg0): + ... + + +def signbit(arg0): + ... + + +def copysign(arg0, arg1): + ... + + +def finitef(arg0): + ... + + +def isinf(arg0): + ... + + +def nextafter(arg0, arg1): + ... + + +def sin(arg0): + ... + + +def cos(arg0): + ... + + +def sinpi(arg0): + ... + + +def cospi(arg0): + ... + + +def tan(arg0): + ... + + +def log2(arg0): + ... + + +def exp(arg0): + ... + + +def exp10(arg0): + ... + + +def cosh(arg0): + ... + + +def sinh(arg0): + ... + + +def tanh(arg0): + ... + + +def atan2(arg0, arg1): + ... + + +def atan(arg0): + ... + + +def asin(arg0): + ... + + +def acos(arg0): + ... + + +def log(arg0): + ... + + +def log10(arg0): + ... + + +def log1p(arg0): + ... + + +def acosh(arg0): + ... + + +def asinh(arg0): + ... + + +def atanh(arg0): + ... + + +def expm1(arg0): + ... + + +def hypot(arg0, arg1): + ... + + +def rhypot(arg0, arg1): + ... + + +def norm3d(arg0, arg1, arg2): + ... + + +def rnorm3d(arg0, arg1, arg2): + ... + + +def norm4d(arg0, arg1, arg2, arg3): + ... + + +def rnorm4d(arg0, arg1, arg2, arg3): + ... + + +def cbrt(arg0): + ... + + +def rcbrt(arg0): + ... + + +def j0(arg0): + ... + + +def j1(arg0): + ... + + +def y0(arg0): + ... + + +def y1(arg0): + ... + + +def yn(arg0, arg1): + ... + + +def jn(arg0, arg1): + ... + + +def cyl_bessel_i0(arg0): + ... + + +def cyl_bessel_i1(arg0): + ... + + +def erf(arg0): + ... + + +def erfinv(arg0): + ... + + +def erfc(arg0): + ... + + +def erfcx(arg0): + ... + + +def erfcinv(arg0): + ... + + +def normcdfinv(arg0): + ... + + +def normcdf(arg0): + ... + + +def lgamma(arg0): + ... + + +def ldexp(arg0, arg1): + ... + + +def scalbn(arg0, arg1): + ... + + +def fmod(arg0, arg1): + ... + + +def remainder(arg0, arg1): + ... + + +def fma(arg0, arg1, arg2): + ... + + +def pow(arg0, arg1): + ... + + +def tgamma(arg0): + ... + + +def round(arg0): + ... + + +def llround(arg0): + ... + + +def fdim(arg0, arg1): + ... + + +def ilogb(arg0): + ... + + +def logb(arg0): + ... + + +def isfinited(arg0): + ... diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/math.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/math.py new file mode 100644 index 0000000000000000000000000000000000000000..582cd876cb13374a0d31e8c783e4fea1a1003c4a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/math.py @@ -0,0 +1,249 @@ +from . import core +from functools import wraps +from typing import List + +T = core.TypeVar('T') + + +def _check_dtype(dtypes: List[str]) -> T: + """ + We're following libdevice's convention to check accepted data types for math functions. + It is not a good practice to support all data types as accelerators/GPUs don't support + many float16 and bfloat16 math operations. + We should let the users know that they are using and invoke explicit cast to convert + the data type to the supported one. + """ + + def wrapper(fn): + + @wraps(fn) + def check(*args, **kwargs): + # concatenate args and kwargs + all_args = list(args) + list(kwargs.values()) + for arg in [a for a in all_args if isinstance(a, core.tensor)]: + if arg.type.scalar.name not in dtypes: + raise ValueError(f"Expected dtype {dtypes} but got {arg.type.scalar.name}") + return fn(*args, **kwargs) + + return check + + return wrapper + + +def _add_math_1arg_docstr(name: str) -> core.Callable[[T], T]: + + def _decorator(func: T) -> T: + docstr = """ + Computes the element-wise {name} of :code:`x`. + + :param x: the input values + :type x: Block + """ + func.__doc__ = docstr.format(name=name) + return func + + return _decorator + + +def _add_math_2arg_docstr(name: str) -> core.Callable[[T], T]: + + def _decorator(func: T) -> T: + docstr = """ + Computes the element-wise {name} of :code:`x` and :code:`y`. + + :param x: the input values + :type x: Block + :param y: the input values + :type y: Block + """ + func.__doc__ = docstr.format(name=name) + return func + + return _decorator + + +def _add_math_3arg_docstr(name: str) -> core.Callable[[T], T]: + + def _decorator(func: T) -> T: + docstr = """ + Computes the element-wise {name} of :code:`x`, :code:`y`, and :code:`z`. + + :param x: the input values + :type x: Block + :param y: the input values + :type y: Block + :param z: the input values + :type z: Block + """ + func.__doc__ = docstr.format(name=name) + return func + + return _decorator + + +@core.builtin +@_check_dtype(dtypes=["int32", "int64", "uint32", "uint64"]) +@_add_math_2arg_docstr("most significant N bits of the 2N-bit product") +def umulhi(x, y, _semantic=None): + x = _semantic.to_tensor(x) + y = _semantic.to_tensor(y) + x, y = core.binary_op_type_legalization(x, y, _semantic) + return core.tensor(_semantic.builder.create_umulhi(x.handle, y.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("exponential") +@core._tensor_member_fn +def exp(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_exp(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("exponential (base 2)") +@core._tensor_member_fn +def exp2(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_exp2(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("natural logarithm") +@core._tensor_member_fn +def log(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_log(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("logarithm (base 2)") +@core._tensor_member_fn +def log2(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_log2(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("cosine") +@core._tensor_member_fn +def cos(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_cos(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("sine") +@core._tensor_member_fn +def sin(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_sin(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("fast square root") +@core._tensor_member_fn +def sqrt(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_sqrt(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32"]) +@_add_math_1arg_docstr("precise square root (rounding to nearest wrt the IEEE standard)") +@core._tensor_member_fn +def sqrt_rn(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_precise_sqrt(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("inverse square root") +@core._tensor_member_fn +def rsqrt(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_rsqrt(x.handle), x.type) + + +@core._tensor_member_fn +@core.builtin +@_add_math_1arg_docstr("absolute value") +def abs(x, _semantic=None): + x = _semantic.to_tensor(x) + dtype = x.dtype + if dtype.is_fp8e4b15(): + mask = core.full(x.shape, 0x7F, core.int8, _semantic=_semantic) + return core.tensor(_semantic.builder.create_and(x.handle, mask.handle), x.type) + elif dtype.is_floating(): + return core.tensor(_semantic.builder.create_fabs(x.handle), x.type) + elif dtype.is_int_signed(): + return core.tensor(_semantic.builder.create_iabs(x.handle), x.type) + elif dtype.is_int_unsigned(): + return x # no-op + else: + assert False, f"Unexpected dtype {dtype}" + + +@core.builtin +@_add_math_2arg_docstr("fast division") +def fdiv(x, y, ieee_rounding=False, _semantic=None): + ieee_rounding = core._unwrap_if_constexpr(ieee_rounding) + x = _semantic.to_tensor(x) + y = _semantic.to_tensor(y) + return _semantic.fdiv(x, y, ieee_rounding) + + +@core.builtin +@_check_dtype(dtypes=["fp32"]) +@_add_math_2arg_docstr("precise division (rounding to nearest wrt the IEEE standard)") +def div_rn(x, y, _semantic=None): + x = _semantic.to_tensor(x) + y = _semantic.to_tensor(y) + x, y = core.binary_op_type_legalization(x, y, _semantic) + return core.tensor(_semantic.builder.create_precise_divf(x.handle, y.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("error function") +@core._tensor_member_fn +def erf(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_erf(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("floor") +@core._tensor_member_fn +def floor(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_floor(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("ceil") +@core._tensor_member_fn +def ceil(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_ceil(x.handle), x.type) + + +@core.builtin +@_add_math_3arg_docstr("fused multiply-add") +def fma(x, y, z, _semantic=None): + x = _semantic.to_tensor(x) + y = _semantic.to_tensor(y) + z = _semantic.to_tensor(z) + x, y = core.binary_op_type_legalization(x, y, _semantic) + z, x = core.binary_op_type_legalization(z, x, _semantic) + z, y = core.binary_op_type_legalization(z, y, _semantic) + return core.tensor(_semantic.builder.create_fma(x.handle, y.handle, z.handle), x.type) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/random.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/random.py new file mode 100644 index 0000000000000000000000000000000000000000..1f6c192dd4864c599f51cfd5cee78165b5bc86e8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/random.py @@ -0,0 +1,218 @@ +from ..runtime.jit import jit +from . import core as tl +from . import math + +N_ROUNDS_DEFAULT = 10 # Default number of rounds for philox + +# ------------------- +# randint +# ------------------- + + +@jit +def philox_impl(c0, c1, c2, c3, k0, k1, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + """ + Run `n_rounds` rounds of Philox for state (c0, c1, c2, c3) and key (k0, k1). + """ + if c0.dtype == tl.uint32: + PHILOX_KEY_A: tl.constexpr = 0x9E3779B9 + PHILOX_KEY_B: tl.constexpr = 0xBB67AE85 + PHILOX_ROUND_A: tl.constexpr = 0xD2511F53 + PHILOX_ROUND_B: tl.constexpr = 0xCD9E8D57 + else: + tl.static_assert(c0.dtype == tl.uint64, "dtype not supported in philox_impl") + PHILOX_KEY_A: tl.constexpr = 0x9E3779B97F4A7C15 + PHILOX_KEY_B: tl.constexpr = 0xBB67AE8584CAA73B + PHILOX_ROUND_A: tl.constexpr = 0xD2E7470EE14C6C93 + PHILOX_ROUND_B: tl.constexpr = 0xCA5A826395121157 + + for _ in tl.static_range(n_rounds): + # for _ in range(n_rounds): + # update random state + A = PHILOX_ROUND_A + B = PHILOX_ROUND_B + _c0, _c2 = c0, c2 + c0 = math.umulhi(B, _c2) ^ c1 ^ k0 + c2 = math.umulhi(A, _c0) ^ c3 ^ k1 + c1 = tl.mul(B, _c2, sanitize_overflow=False) + c3 = tl.mul(A, _c0, sanitize_overflow=False) + # raise key + k0 = tl.add(k0, PHILOX_KEY_A, sanitize_overflow=False) + k1 = tl.add(k1, PHILOX_KEY_B, sanitize_overflow=False) + return c0, c1, c2, c3 + + +@jit +def philox(seed, c0, c1, c2, c3, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + seed = tl.to_tensor(seed) + tl.static_assert(seed.dtype.is_int()) + seed = seed.to(tl.uint64) + c0 = tl.to_tensor(c0) + c1 = tl.to_tensor(c1) + c2 = tl.to_tensor(c2) + c3 = tl.to_tensor(c3) + + if tl.constexpr(c0.dtype.primitive_bitwidth) == 32: + int_dtype = tl.uint32 + seed_hi = ((seed >> 32) & 0xffffffff).to(tl.uint32) + seed_lo = (seed & 0xffffffff).to(tl.uint32) + else: + tl.static_assert(tl.constexpr(c0.dtype.primitive_bitwidth) == 64, "bitwidth not supported in philox") + int_dtype = tl.uint64 + seed_hi = tl.full((1, ), 0, dtype=int_dtype) + seed_lo = seed + + c0 = c0.to(int_dtype, bitcast=True) + c1 = c1.to(int_dtype, bitcast=True) + c2 = c2.to(int_dtype, bitcast=True) + c3 = c3.to(int_dtype, bitcast=True) + return philox_impl(c0, c1, c2, c3, seed_lo, seed_hi, n_rounds) + + +@jit +def randint(seed, offset, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + """ + Given a :code:`seed` scalar and an :code:`offset` block, returns a single + block of random :code:`int32`. + + If you need multiple streams of random numbers, + using `randint4x` is likely to be faster than calling `randint` 4 times. + + :param seed: The seed for generating random numbers. + :param offset: The offsets to generate random numbers for. + """ + ret, _, _, _ = randint4x(seed, offset, n_rounds) + return ret + + +@jit +def randint4x(seed, offset, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + """ + Given a :code:`seed` scalar and an :code:`offset` block, returns four + blocks of random :code:`int32`. + + This is the maximally efficient entry point + to Triton's Philox pseudo-random number generator. + + :param seed: The seed for generating random numbers. + :param offsets: The offsets to generate random numbers for. + """ + # _0 = tl.zeros(offset.shape, offset.dtype) + + offset_lo = offset.to(tl.uint32) + _0 = offset_lo * 0 + + if tl.constexpr(offset.dtype.primitive_bitwidth) > 32: + offset_hi = (offset >> 32).to(tl.uint32) + else: + offset_hi = _0 + + return philox(seed, offset_lo, offset_hi, _0, _0, n_rounds) + + +# ------------------- +# rand +# ------------------- + +# @jit +# def uint32_to_uniform_float(x): +# """ +# Numerically stable function to convert a random uint32 into a random float uniformly sampled in [0, 1). +# """ +# two_to_the_minus_32: tl.constexpr = 2.328306e-10 +# return x * two_to_the_minus_32 + + +@jit +def uint_to_uniform_float(x): + """ + Numerically stable function to convert a random uint into a random float uniformly sampled in [0, 1). + """ + # TODO: fix frontend issues and cleanup + # conditions can be simplified + # scale is ((2**23 - 1) / 2**23) * 2**(N_BITS - 1) + if tl.constexpr(x.dtype == tl.uint32) or tl.constexpr(x.dtype == tl.int32): + # maximum value such that `MAX_INT * scale < 1.0` (with float rounding) + x = x.to(tl.int32, bitcast=True) + scale = 4.6566127342e-10 + else: + tl.static_assert(tl.constexpr(x.dtype == tl.uint64) or tl.constexpr(x.dtype == tl.int64)) + x = x.to(tl.int64, bitcast=True) + scale = 1.0842020432385337e-19 + x = tl.where(x < 0, -x - 1, x) + return x * scale + + +@jit +def rand(seed, offset, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + """ + Given a :code:`seed` scalar and an :code:`offset` block, + returns a block of random :code:`float32` in :math:`U(0, 1)`. + + :param seed: The seed for generating random numbers. + :param offsets: The offsets to generate random numbers for. + """ + source = randint(seed, offset, n_rounds) + return uint_to_uniform_float(source) + + +@jit +def rand4x(seed, offsets, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + """ + Given a :code:`seed` scalar and an :code:`offsets` block, + returns 4 blocks of random :code:`float32` in :math:`U(0, 1)`. + + :param seed: The seed for generating random numbers. + :param offsets: The offsets to generate random numbers for. + """ + i1, i2, i3, i4 = randint4x(seed, offsets, n_rounds) + u1 = uint_to_uniform_float(i1) + u2 = uint_to_uniform_float(i2) + u3 = uint_to_uniform_float(i3) + u4 = uint_to_uniform_float(i4) + return u1, u2, u3, u4 + + +# ------------------- +# randn +# ------------------- + + +@jit +def pair_uniform_to_normal(u1, u2): + """Box-Muller transform""" + u1 = tl.maximum(1.0e-7, u1) + th = 6.283185307179586 * u2 + r = math.sqrt(-2.0 * math.log(u1)) + return r * math.cos(th), r * math.sin(th) + + +@jit +def randn(seed, offset, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + """ + Given a :code:`seed` scalar and an :code:`offset` block, + returns a block of random :code:`float32` in :math:`\\mathcal{N}(0, 1)`. + + :param seed: The seed for generating random numbers. + :param offsets: The offsets to generate random numbers for. + """ + i1, i2, _, _ = randint4x(seed, offset, n_rounds) + u1 = uint_to_uniform_float(i1) + u2 = uint_to_uniform_float(i2) + n1, _ = pair_uniform_to_normal(u1, u2) + return n1 + + +@jit +def randn4x(seed, offset, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + """ + Given a :code:`seed` scalar and an :code:`offset` block, + returns 4 blocks of random :code:`float32` in :math:`\\mathcal{N}(0, 1)`. + + :param seed: The seed for generating random numbers. + :param offsets: The offsets to generate random numbers for. + """ + u1, u2, u3, u4 = rand4x(seed, offset, n_rounds) + n1, n2 = pair_uniform_to_normal(u1, u2) + n3, n4 = pair_uniform_to_normal(u3, u4) + return n1, n2, n3, n4 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/semantic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..5fc9cf67e6d070800d848bec66db5aacf98013fe --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/semantic.py @@ -0,0 +1,1939 @@ +from __future__ import annotations # remove after python 3.11 +import warnings + +from typing import List, Optional, Sequence, Tuple, TypeVar, Generic, Type +import numbers + +from triton.runtime import driver + +from .._C.libtriton import ir +from . import core as tl + +T = TypeVar('T') +TensorTy = TypeVar('TensorTy') + + +class IncompatibleTypeErrorImpl(Exception): + + def __init__(self, type_a, type_b): + self.type_a = type_a + self.type_b = type_b + self.message = "invalid operands of type " + self.type_a.__repr__() + " and " + self.type_b.__repr__() + super(IncompatibleTypeErrorImpl, self).__init__(self.message) + + +class TritonSemantic(Generic[TensorTy]): + tensor: Type[TensorTy] = tl.tensor + lang = tl + + builder: ir.builder + + def __init__(self, builder): + self.builder = builder + +# ===----------------------------------------------------------------------===## +# Programming Model +# ===----------------------------------------------------------------------===## + + def program_id(self, axis: int) -> TensorTy: + if axis not in (0, 1, 2): + raise ValueError(f"program_id axis must be 0, 1, or 2 but got {axis}") + return self.tensor(self.builder.create_get_program_id(axis), tl.int32) + + def num_programs(self, axis: int) -> TensorTy: + if axis not in (0, 1, 2): + raise ValueError(f"num_programs axis must be 0, 1, or 2 but got {axis}") + return self.tensor(self.builder.create_get_num_programs(axis), tl.int32) + +# ===----------------------------------------------------------------------===// +# Implicit Casting Utilities +# ===----------------------------------------------------------------------===// + + def integer_promote_impl(self, a_ty: tl.dtype, b_ty: tl.dtype) -> tl.dtype: + a_rank = a_ty.int_bitwidth + b_rank = b_ty.int_bitwidth + a_sn = a_ty.int_signedness + b_sn = b_ty.int_signedness + # Rules for signedness taken from "Usual arithmetic conversions" on + # https://en.cppreference.com/w/c/language/conversion. + if a_sn == b_sn: + return a_ty if a_rank > b_rank else b_ty + elif a_sn == tl.dtype.SIGNEDNESS.UNSIGNED: + return a_ty if a_rank >= b_rank else b_ty + elif b_sn == tl.dtype.SIGNEDNESS.UNSIGNED: + return b_ty if b_rank >= a_rank else a_ty + raise TypeError(f"unexpected signedness {a_sn} and {b_sn}") + + def computation_type_impl(self, a_ty: tl.dtype, a_is_scalar: bool, b_ty: tl.dtype, b_is_scalar: bool, + div_or_mod: bool) -> tl.dtype: + # 0) For scalars we follow semantics similar to PyTorch, namely: + # - If the scalar is of a lower or equal kind (bool < uint < int < fp), + # it doesn't participate in the promotion + if a_is_scalar != b_is_scalar: + scalar_ty, tensor_ty = (a_ty, b_ty) if a_is_scalar else (b_ty, a_ty) + if scalar_ty.kind().value <= tensor_ty.kind().value: + # Upcast because of 3) and 4) below! + if div_or_mod and (tensor_ty in (tl.float16, tl.bfloat16)): + return tl.float32 + return tensor_ty + + # 1) if one operand is double, the other is implicitly + # converted to double + if a_ty.is_fp64() or b_ty.is_fp64(): + return tl.float64 + # 2) if one operand is float, the other is implicitly + # converted to float + if a_ty.is_fp32() or b_ty.is_fp32(): + return tl.float32 + # 3 ) if one operand is half, the other is implicitly converted to half + # unless we're doing / or %, which do not exist natively in PTX for fp16. + # Supported PTX op: add, sub, mul, fma, neg, abs, min, max, tanh, ex2, setp + if a_ty.is_fp16() or b_ty.is_fp16(): + if div_or_mod: + return tl.float32 + else: + return tl.float16 + # 4) return bf16 only if both operands are of bf16 + if a_ty.is_bf16() and b_ty.is_bf16(): + if div_or_mod: + return tl.float32 + else: + return tl.bfloat16 + if a_ty.is_bf16() or b_ty.is_bf16(): + return tl.float32 + # 5) return fp16 if operands are different fp8 + if a_ty.is_fp8() and b_ty.is_fp8(): + return a_ty if a_ty == b_ty else tl.float16 + if not a_ty.is_int() or not b_ty.is_int(): + raise TypeError(f"unexpected type {a_ty} and {b_ty}") + # 6 ) both operands are integer and undergo + # integer promotion + if div_or_mod and a_ty.int_signedness != b_ty.int_signedness: + raise TypeError("Cannot use /, #, or % with " + a_ty.__repr__() + " and " + b_ty.__repr__() + + " because they have different signedness;" + "this is unlikely to result in a useful answer. Cast them to the same signedness.") + return self.integer_promote_impl(a_ty, b_ty) + + def to_tensor(self, x, check_type: bool = True): + if isinstance(x, bool): + return self.tensor(self.builder.get_int1(x), tl.int1) + # Note: compile-time const integers are represented by unsigned values + elif isinstance(x, int): + if -2**31 <= x < 2**31: + dtype = tl.int32 + elif 2**31 <= x < 2**32: + dtype = tl.uint32 + elif -2**63 <= x < 2**63: + dtype = tl.int64 + elif 2**63 <= x < 2**64: + dtype = tl.uint64 + else: + raise ValueError(f'Nonrepresentable integer {x}.') + return self.scalar_constant(x, dtype=dtype) + elif isinstance(x, float): + min_float32 = 2**-126 + max_float32 = (2 - 2**-23) * 2**127 + abs_x = __builtins__['abs'](x) + if abs_x == float("inf") or\ + abs_x == 0.0 or \ + x != x or \ + min_float32 <= abs_x <= max_float32: + dtype = tl.float32 + else: + dtype = tl.float64 + return self.scalar_constant(x, dtype=dtype) + + elif isinstance(x, tl.constexpr): + return self.to_tensor(x.value) + elif isinstance(x, self.tensor): + return x + if check_type: + raise TypeError(f"cannot convert {x} of type {type(x)} to tensor") + return x + +# ===----------------------------------------------------------------------===// +# Binary Operators +# ===----------------------------------------------------------------------===// + + def check_ptr_type_impl(self, type_a: tl.dtype, type_b: tl.dtype, allow_ptr_a: bool) -> None: + if type_a.is_ptr(): + if not allow_ptr_a: + raise IncompatibleTypeErrorImpl(type_a, type_b) + # T* + U* with T != U + if type_b.is_ptr() and (type_a != type_b): + raise IncompatibleTypeErrorImpl(type_a, type_b) + # T* + float + if type_b.is_floating(): + raise IncompatibleTypeErrorImpl(type_a, type_b) + + def binary_op_type_checking_impl(self, lhs: TensorTy | numbers.Number, rhs: TensorTy | numbers.Number, + allow_lhs_ptr=False, allow_rhs_ptr=False, arithmetic_check=True, + div_or_mod=False) -> Tuple[TensorTy, TensorTy]: + lhs_is_scalar = isinstance(lhs, numbers.Number) + rhs_is_scalar = isinstance(rhs, numbers.Number) + if lhs_is_scalar: + lhs_scalar = lhs + lhs = self.to_tensor(lhs) + if rhs_is_scalar: + rhs_scalar = rhs + rhs = self.to_tensor(rhs) + + # implicit typecasting + lhs_sca_ty = lhs.type.scalar + rhs_sca_ty = rhs.type.scalar + self.check_ptr_type_impl(lhs_sca_ty, rhs_sca_ty, allow_lhs_ptr) + self.check_ptr_type_impl(rhs_sca_ty, lhs_sca_ty, allow_rhs_ptr) + if arithmetic_check and not lhs_sca_ty.is_ptr() and not rhs_sca_ty.is_ptr(): + ret_sca_ty = self.computation_type_impl(lhs_sca_ty, lhs_is_scalar, rhs_sca_ty, rhs_is_scalar, div_or_mod) + if (lhs_is_scalar and lhs_scalar < 0 and ret_sca_ty.is_int_unsigned() + or rhs_is_scalar and rhs_scalar < 0 and ret_sca_ty.is_int_unsigned()): + raise ValueError("Cannot perform a binary operation between an unsigned tensor and a negative scalar. " + "Perform a explicit cast on one of them.") + if ret_sca_ty.is_int(): + if lhs_is_scalar and not (ret_sca_ty.get_int_min_value() <= lhs_scalar <= + ret_sca_ty.get_int_max_value()): + raise ValueError(f"Scalar {lhs_scalar} is out of range for type {ret_sca_ty}") + if rhs_is_scalar and not (ret_sca_ty.get_int_min_value() <= rhs_scalar <= + ret_sca_ty.get_int_max_value()): + raise ValueError(f"Scalar {rhs_scalar} is out of range for type {ret_sca_ty}") + lhs = self.scalar_constant(lhs_scalar, dtype=ret_sca_ty) if lhs_is_scalar else self.cast(lhs, ret_sca_ty) + rhs = self.scalar_constant(rhs_scalar, dtype=ret_sca_ty) if rhs_is_scalar else self.cast(rhs, ret_sca_ty) + + # implicit broadcasting + lhs, rhs = self.broadcast_impl_value(lhs, rhs) + return lhs, rhs + + def binary_op_sanitize_overflow_impl(self, lhs: TensorTy, rhs: TensorTy, binary_op: callable): + if lhs.type.scalar.int_bitwidth >= 64 or not self.builder.options.sanitize_overflow: + return + lhs_sca_ty = lhs.type.scalar + rhs_sca_ty = rhs.type.scalar + assert lhs_sca_ty == rhs_sca_ty + assert lhs_sca_ty.is_int() + lhs = self.cast(lhs, tl.int64) + rhs = self.cast(rhs, tl.int64) + ret = binary_op(lhs, rhs, False) + max_value = lhs_sca_ty.get_int_max_value() + max_value = self.scalar_constant(max_value, tl.int64) + min_value = lhs_sca_ty.get_int_min_value() + min_value = self.scalar_constant(min_value, tl.int64) + cond = self.and_(self.less_equal(ret, max_value), self.greater_equal(ret, min_value)) + msg = f"int{lhs_sca_ty.int_bitwidth} overflow detected for operation {binary_op.__name__}" + self.device_assert(cond, msg, None) + + def add(self, input: TensorTy | numbers.Number, other: TensorTy | numbers.Number, + sanitize_overflow: bool) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other, True, True) + input_scalar_ty = input.type.scalar + other_scalar_ty = other.type.scalar + if input_scalar_ty.is_ptr() and other_scalar_ty.is_ptr(): + raise TypeError("cannot add pointers together") + + # offset + ptr + # ptr + offset + if other_scalar_ty.is_ptr() and not input_scalar_ty.is_ptr(): + input, other = other, input + input_scalar_ty = input.type.scalar + other_scalar_ty = other.type.scalar + if input_scalar_ty.is_ptr(): + other_handle = other.handle + if other.dtype.is_int_unsigned() and other.dtype.int_bitwidth < 64: + # addptr treats offset as signed. Zero-extend unsigned offsets to ensure they're positive + i64_ty = other.type.with_element_ty(tl.int64).to_ir(self.builder) + other_handle = self.builder.create_int_cast(other.handle, i64_ty, False) + return self.tensor(self.builder.create_addptr(input.handle, other_handle), input.type) + # float + float + elif input_scalar_ty.is_floating(): + return self.tensor(self.builder.create_fadd(input.handle, other.handle), input.type) + # int + int + elif input_scalar_ty.is_int(): + if sanitize_overflow: + self.binary_op_sanitize_overflow_impl(input, other, self.add) + return self.tensor(self.builder.create_add(input.handle, other.handle), input.type) + raise TypeError(f"unexpected type {input_scalar_ty}") + + def sub(self, input: TensorTy | numbers.Number, other: TensorTy | numbers.Number, + sanitize_overflow: bool) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other, True, False) + scalar_ty = input.type.scalar + # ptr - offset + if scalar_ty.is_ptr(): + return self.add(input, self.minus(other), sanitize_overflow=False) + # float - float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fsub(input.handle, other.handle), input.type) + # int - int + elif scalar_ty.is_int(): + if sanitize_overflow: + self.binary_op_sanitize_overflow_impl(input, other, self.sub) + return self.tensor(self.builder.create_sub(input.handle, other.handle), input.type) + raise TypeError(f"unexpected type {scalar_ty}") + + def mul(self, input: TensorTy | numbers.Number, other: TensorTy | numbers.Number, + sanitize_overflow: bool) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other) + scalar_ty = input.type.scalar + # float * float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fmul(input.handle, other.handle), input.type) + # int * int + elif scalar_ty.is_int(): + if sanitize_overflow: + self.binary_op_sanitize_overflow_impl(input, other, self.mul) + return self.tensor(self.builder.create_mul(input.handle, other.handle), input.type) + raise TypeError(f"unexpected type {scalar_ty}") + + def truediv(self, input: TensorTy | numbers.Number, other: TensorTy | numbers.Number) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other, False, False, True, True) + input_scalar_ty = input.type.scalar + other_scalar_ty = other.type.scalar + # float / int + if input_scalar_ty.is_floating() and other_scalar_ty.is_int(): + other = self.cast(other, input_scalar_ty) + # int / float + elif input_scalar_ty.is_int() and other_scalar_ty.is_floating(): + input = self.cast(input, other_scalar_ty) + # int / int (cast to tl.float32) + elif input_scalar_ty.is_int() and other_scalar_ty.is_int(): + input = self.cast(input, tl.float32) + other = self.cast(other, tl.float32) + # float / float (cast to the highest exponent type) + elif input_scalar_ty.is_floating() and other_scalar_ty.is_floating(): + if input_scalar_ty.fp_mantissa_width > other_scalar_ty.fp_mantissa_width: + other = self.cast(other, input_scalar_ty) + else: + input = self.cast(input, other_scalar_ty) + # unreachable + else: + raise TypeError(f"unexpected type {input_scalar_ty}") + return self.tensor(self.builder.create_fdiv(input.handle, other.handle), input.type) + + def floordiv(self, input: TensorTy | numbers.Number, other: TensorTy | numbers.Number) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other, False, False, True, True) + input_scalar_ty = input.type.scalar + other_scalar_ty = other.type.scalar + if input_scalar_ty.is_int() and other_scalar_ty.is_int(): + ret_ty = self.integer_promote_impl(input_scalar_ty, other_scalar_ty) + input = self.cast(input, ret_ty) + other = self.cast(other, ret_ty) + if ret_ty.is_int_signed(): + return self.tensor(self.builder.create_sdiv(input.handle, other.handle), input.type) + else: + return self.tensor(self.builder.create_udiv(input.handle, other.handle), input.type) + raise TypeError(f"unexpected type {input_scalar_ty}") + + def fdiv(self, input: TensorTy | numbers.Number, other: TensorTy | numbers.Number, ieee_rounding: bool) -> TensorTy: + input_scalar_ty = input.type.scalar + other_scalar_ty = other.type.scalar + if not input_scalar_ty.is_floating() or not other_scalar_ty.is_floating(): + raise TypeError("both operands of fdiv must have floating scalar type") + input, other = self.binary_op_type_checking_impl(input, other, False, False, False, True) + ret = self.builder.create_fdiv(input.handle, other.handle) + return self.tensor(ret, input.type) + + def mod(self, input: TensorTy | numbers.Number, other: TensorTy | numbers.Number) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other, False, False, True, True) + scalar_ty = input.type.scalar + other_scalar_ty = other.type.scalar + # float % float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_frem(input.handle, other.handle), input.type) + # % int + elif scalar_ty.is_int(): + if scalar_ty.int_signedness != other_scalar_ty.int_signedness: + raise TypeError("Cannot mod " + scalar_ty.__repr__() + " by " + other_scalar_ty.__repr__() + " " + "because they have different signedness;" + "this is unlikely to result in a useful answer. Cast them to the same signedness.") + if scalar_ty.is_int_signed(): + return self.tensor(self.builder.create_srem(input.handle, other.handle), input.type) + else: + return self.tensor(self.builder.create_urem(input.handle, other.handle), input.type) + raise TypeError(f"unexpected type {scalar_ty}") + +############## +# other arithmetic ops +############## + + def minimum(self, x: TensorTy, y: TensorTy, propagate_nan: tl.PropagateNan): + x, y = self.binary_op_type_checking_impl(x, y) + dtype = x.dtype + if dtype.is_floating(): + if propagate_nan == tl.PropagateNan.ALL: + return self.tensor(self.builder.create_minimumf(x.handle, y.handle), x.type) + elif propagate_nan == tl.PropagateNan.NONE: + return self.tensor(self.builder.create_minnumf(x.handle, y.handle), x.type) + else: + raise ValueError(f"Unexpected propagate_nan {propagate_nan}") + elif dtype.is_int_signed(): + return self.tensor(self.builder.create_minsi(x.handle, y.handle), x.type) + elif dtype.is_int_unsigned(): + return self.tensor(self.builder.create_minui(x.handle, y.handle), x.type) + else: + raise TypeError(f"Unexpected dtype {dtype}") + + def maximum(self, x: TensorTy, y: TensorTy, propagate_nan: tl.PropagateNan): + x, y = self.binary_op_type_checking_impl(x, y) + dtype = x.dtype + if dtype.is_floating(): + if propagate_nan == tl.PropagateNan.ALL: + return self.tensor(self.builder.create_maximumf(x.handle, y.handle), x.type) + elif propagate_nan == tl.PropagateNan.NONE: + return self.tensor(self.builder.create_maxnumf(x.handle, y.handle), x.type) + else: + raise ValueError(f"Unexpected propagate_nan {propagate_nan}") + elif dtype.is_int_signed(): + return self.tensor(self.builder.create_maxsi(x.handle, y.handle), x.type) + elif dtype.is_int_unsigned(): + return self.tensor(self.builder.create_maxui(x.handle, y.handle), x.type) + else: + raise TypeError(f"Unexpected dtype {dtype}") + + def clamp(self, x: TensorTy, min: TensorTy, max: TensorTy, propagate_nan: tl.PropagateNan): + min, max = self.binary_op_type_checking_impl(min, max) + x, min = self.binary_op_type_checking_impl(x, min) + x, max = self.binary_op_type_checking_impl(x, max) + + dtype = x.dtype + if dtype.is_floating(): + return self.tensor(self.builder.create_clampf(x.handle, min.handle, max.handle, propagate_nan), x.type) + else: + raise TypeError(f"Unexpected dtype {dtype}. Only floating point clamp is supported") + +############## +# bitwise ops +############## + + def bitwise_op_type_checking_impl(self, input: TensorTy, other: TensorTy) -> Tuple[TensorTy, TensorTy]: + input, other = self.binary_op_type_checking_impl(input, other) + input_sca_ty = input.type.scalar + other_sca_ty = other.type.scalar + if not input_sca_ty.is_int() or not other_sca_ty.is_int(): + raise IncompatibleTypeErrorImpl(input_sca_ty, other_sca_ty) + ret_sca_ty = self.integer_promote_impl(input_sca_ty, other_sca_ty) + if ret_sca_ty != input_sca_ty: + input = self.cast(input, ret_sca_ty) + if ret_sca_ty != other_sca_ty: + other = self.cast(other, ret_sca_ty) + return input, other + + def and_(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.bitwise_op_type_checking_impl(input, other) + return self.tensor(self.builder.create_and(input.handle, other.handle), input.type) + + def or_(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.bitwise_op_type_checking_impl(input, other) + return self.tensor(self.builder.create_or(input.handle, other.handle), input.type) + + def xor_(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.bitwise_op_type_checking_impl(input, other) + return self.tensor(self.builder.create_xor(input.handle, other.handle), input.type) + + def logical_and(self, input: TensorTy, other: TensorTy) -> TensorTy: + if not input.type.is_int1(): + input = self.bitcast(input, tl.int1) + if not other.type.is_int1(): + other = self.bitcast(other, tl.int1) + return self.and_(input, other) + + def logical_or(self, input: TensorTy, other: TensorTy) -> TensorTy: + if not input.type.is_int1(): + input = self.bitcast(input, tl.int1) + if not other.type.is_int1(): + other = self.bitcast(other, tl.int1) + return self.or_(input, other) + + def not_(self, input: TensorTy): + if not input.type.is_int1(): + input = self.bitcast(input, tl.int1) + return self.invert(input) + + def lshr(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.bitwise_op_type_checking_impl(input, other) + return self.tensor(self.builder.create_lshr(input.handle, other.handle), input.type) + + def ashr(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.bitwise_op_type_checking_impl(input, other) + return self.tensor(self.builder.create_ashr(input.handle, other.handle), input.type) + + def shl(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.bitwise_op_type_checking_impl(input, other) + return self.tensor(self.builder.create_shl(input.handle, other.handle), input.type) + +# ===----------------------------------------------------------------------===// +# Unary Operators +# ===----------------------------------------------------------------------===// + + def plus(self, input: TensorTy) -> TensorTy: + return input + + def minus(self, input: TensorTy) -> TensorTy: + input_sca_ty = input.type.scalar + if input_sca_ty.is_ptr(): + raise ValueError("wrong type argument to unary minus (" + input_sca_ty.__repr__() + ")") + _0 = self.tensor(self.builder.get_null_value(input_sca_ty.to_ir(self.builder)), input_sca_ty) + return self.sub(_0, input, True) + + def invert(self, input: TensorTy) -> TensorTy: + input_sca_ty = input.type.scalar + if input_sca_ty.is_ptr() or input_sca_ty.is_floating(): + raise ValueError("wrong type argument to unary invert (" + input_sca_ty.__repr__() + ")") + _1 = self.tensor(self.builder.get_all_ones_value(input_sca_ty.to_ir(self.builder)), input_sca_ty) + return self.xor_(input, _1) + +# ===----------------------------------------------------------------------===// +# Comparison Operators +# ===----------------------------------------------------------------------===// + + def _bool_like(self, v: TensorTy) -> tl.block_type: + return v.type.with_element_ty(tl.int1) + + def greater_than(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other) + scalar_ty = input.type.scalar + # float > float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fcmpOGT(input.handle, other.handle), self._bool_like(input)) + # > int + elif scalar_ty.is_int(): + if scalar_ty.is_int_signed(): + return self.tensor(self.builder.create_icmpSGT(input.handle, other.handle), self._bool_like(input)) + else: + return self.tensor(self.builder.create_icmpUGT(input.handle, other.handle), self._bool_like(input)) + raise TypeError(f"unexpected type {scalar_ty}") + + def greater_equal(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other) + scalar_ty = input.type.scalar + # float >= float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fcmpOGE(input.handle, other.handle), self._bool_like(input)) + # >= int + elif scalar_ty.is_int(): + if scalar_ty.is_int_signed(): + return self.tensor(self.builder.create_icmpSGE(input.handle, other.handle), self._bool_like(input)) + else: + return self.tensor(self.builder.create_icmpUGE(input.handle, other.handle), self._bool_like(input)) + raise TypeError(f"unexpected type {scalar_ty}") + + def less_than(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other) + scalar_ty = input.type.scalar + # float < float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fcmpOLT(input.handle, other.handle), self._bool_like(input)) + # < int + elif scalar_ty.is_int(): + if scalar_ty.is_int_signed(): + return self.tensor(self.builder.create_icmpSLT(input.handle, other.handle), self._bool_like(input)) + else: + return self.tensor(self.builder.create_icmpULT(input.handle, other.handle), self._bool_like(input)) + raise TypeError(f"unexpected type {scalar_ty}") + + def less_equal(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other) + scalar_ty = input.type.scalar + # float < float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fcmpOLE(input.handle, other.handle), self._bool_like(input)) + # < int + elif scalar_ty.is_int(): + if scalar_ty.is_int_signed(): + return self.tensor(self.builder.create_icmpSLE(input.handle, other.handle), self._bool_like(input)) + else: + return self.tensor(self.builder.create_icmpULE(input.handle, other.handle), self._bool_like(input)) + raise TypeError(f"unexpected type {scalar_ty}") + + def equal(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other) + scalar_ty = input.type.scalar + # float == float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fcmpOEQ(input.handle, other.handle), self._bool_like(input)) + # == int + elif scalar_ty.is_int(): + return self.tensor(self.builder.create_icmpEQ(input.handle, other.handle), self._bool_like(input)) + raise TypeError(f"unexpected type {scalar_ty}") + + def not_equal(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other) + scalar_ty = input.type.scalar + # float == float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fcmpUNE(input.handle, other.handle), self._bool_like(input)) + # == int + elif scalar_ty.is_int(): + return self.tensor(self.builder.create_icmpNE(input.handle, other.handle), self._bool_like(input)) + raise TypeError(f"unexpected type {scalar_ty}") + +# ===----------------------------------------------------------------------===// +# Block Creation +# ===----------------------------------------------------------------------===// + + def arange(self, start: int, end: int, *, ret_ty: tl.block_type = None) -> TensorTy: + if not isinstance(start, int) or not isinstance(end, int): + raise ValueError("arange's arguments must be of type tl.constexpr") + is_start_int64 = bool(start >> 32) + is_end_int64 = bool(end >> 32) + if is_start_int64 or is_end_int64: + raise ValueError("arange must fit in int32") + if end <= start: + raise ValueError("arange's end argument must be greater than the start argument") + range = end - start + if (range & (range - 1)) != 0: + raise ValueError("arange's range must be a power of 2") + shape = [range] + if ret_ty is None: + ret_ty = tl.block_type(tl.int32, shape) + ret_ty_ir = ret_ty.to_ir(self.builder) + return self.tensor(self.builder.create_make_range(ret_ty_ir, start, end), ret_ty) + + def scalar_constant(self, value, dtype: tl.dtype) -> TensorTy: + # scalar + if dtype is None: + raise ValueError("dtype must be specified when value is not a tensor") + if value == 0: + value = self.builder.get_null_value(dtype.to_ir(self.builder)) + else: + get_value_fn = getattr(self.builder, f"get_{dtype.name}") + value = get_value_fn(value) + return self.tensor(value, dtype) + + def make_scalar(self, value, dtype: tl.dtype) -> TensorTy: + if isinstance(value, tl.tensor): + assert value.numel.value == 1, "only accepts size-1 tensor" + return self.cast(value, dtype) + # scalar + return self.scalar_constant(value, dtype) + + def full(self, shape: List[int], value, dtype: tl.dtype) -> TensorTy: + return self.splat(self.make_scalar(value, dtype), shape) + +# ===----------------------------------------------------------------------===// +# Shape Manipulation +# ===----------------------------------------------------------------------===// + + def splat(self, value: TensorTy, shape: List[int]) -> TensorTy: + assert not value.type.is_block(), "Cannot splat a block tensor" + if len(shape) == 0: + return value + ret_ty = tl.block_type(value.dtype, shape) + return self.tensor(self.builder.create_splat(ret_ty.to_ir(self.builder), value.handle), ret_ty) + + def unsplat(self, value: TensorTy) -> TensorTy: + return self.tensor(self.builder.create_unsplat(value.handle), value.dtype) + + def reshape(self, input: TensorTy, dst_shape: List[int], can_reorder: bool) -> TensorTy: + numel = 1 + for s in dst_shape: + numel *= s + if input.type.numel != numel: + raise ValueError("reshape() cannot change total number of elements in tensor") + ret_ty = tl.block_type(input.type.scalar, dst_shape) + return self.tensor(self.builder.create_reshape(input.handle, dst_shape, can_reorder), ret_ty) + + def expand_dims(self, input: TensorTy, axis: int) -> TensorTy: + dst_shape = [tl._unwrap_if_constexpr(x) for x in input.shape] + dst_shape.insert(axis, 1) + + if not input.type.is_block(): + return self.splat(input, shape=dst_shape) + + ret_ty = tl.block_type(input.type.scalar, dst_shape) + return self.tensor(self.builder.create_expand_dims(input.handle, axis), ret_ty) + + def cat(self, lhs: TensorTy, rhs: TensorTy, can_reorder: bool) -> TensorTy: + assert can_reorder, "current implementation of `cat` always may reorder elements" + assert len(lhs.shape) == 1 + ret_type = tl.block_type(lhs.type.scalar, [lhs.shape[0] + rhs.shape[0]]) + return self.tensor(self.builder.create_cat(lhs.handle, rhs.handle), ret_type) + + def join(self, a: TensorTy, b: TensorTy) -> TensorTy: + a, b = self.broadcast_impl_value(a, b) + + # The IR can't handle joining two scalars, so upcast them to 1D tensors, + # then downcast the result. + was_rank_1 = a.shape == [] + if was_rank_1: + a = self.expand_dims(a, 0) + b = self.expand_dims(b, 0) + + if isinstance(a.shape[-1], tl.constexpr): + two = tl.constexpr(2) + else: + two = 2 + new_shape = a.shape + [two] + + ret_type = tl.block_type(a.type.scalar, new_shape) + ret = self.tensor(self.builder.create_join(a.handle, b.handle), ret_type) + + if was_rank_1: + ret = self.reshape(ret, [2], can_reorder=False) + + return ret + + def split(self, a: TensorTy) -> Tuple[TensorTy, TensorTy]: + assert (len(a.shape) > 0) + assert (tl._unwrap_if_constexpr(a.shape[-1]) == 2) + + new_shape = a.shape[:-1] + ret_type = tl.block_type(a.type.scalar, new_shape) + outLHS, outRHS = self.builder.create_split(a.handle) + return ( + self.tensor(outLHS, ret_type), + self.tensor(outRHS, ret_type), + ) + + def permute(self, input: TensorTy, dims: Tuple[int]) -> TensorTy: + if len(input.shape) != len(dims): + raise ValueError("permute dims must have the same length as input shape") + if sorted(tl._unwrap_if_constexpr(d) for d in dims) != list(range(len(dims))): + raise ValueError(f"permute dims must be a permutation of 0, 1, ..., n-1, but were {dims}") + + ret_type = tl.block_type(input.type.scalar, [input.shape[d] for d in dims]) + return self.tensor(self.builder.create_trans(input.handle, dims), ret_type) + + def broadcast_impl_shape(self, input: TensorTy, shape: Tuple[int]) -> TensorTy: + if not input.type.is_block(): + return self.splat(input, shape) + src_shape = input.type.get_block_shapes() + if len(src_shape) != len(shape): + raise ValueError(f"Cannot broadcast, rank mismatch: {src_shape}, {shape}") + if shape == src_shape: + return input + for i, item in enumerate(src_shape): + if shape[i] != item and item != 1: + raise ValueError(f"Cannot broadcast, the expanded size of the tensor ({shape[i]})" + f" must match the existing size ({item}) at non-singleton dimension" + f" {i}: {src_shape}, {shape}") + ret_ty = tl.block_type(input.type.scalar, shape) + return self.tensor(self.builder.create_broadcast(input.handle, shape), ret_ty) + + def broadcast_impl_value(self, lhs: TensorTy, rhs: TensorTy) -> TensorTy: + lhs_ty = lhs.type + rhs_ty = rhs.type + + # make_shape_compatible(block, scalar) + if lhs_ty.is_block() and not rhs_ty.is_block(): + rhs_ty = lhs_ty.with_element_ty(rhs_ty.scalar) + rhs = self.tensor(self.builder.create_splat(rhs_ty.to_ir(self.builder), rhs.handle), rhs_ty) + # make_shape_compatible(scalar, block) + elif not lhs_ty.is_block() and rhs_ty.is_block(): + lhs_ty = rhs_ty.with_element_ty(lhs_ty.scalar) + lhs = self.tensor(self.builder.create_splat(lhs_ty.to_ir(self.builder), lhs.handle), lhs_ty) + # make_shape_compatible(block, block) + elif lhs_ty.is_block() and rhs_ty.is_block(): + lhs_shape = lhs_ty.get_block_shapes() + rhs_shape = rhs_ty.get_block_shapes() + + if len(lhs_shape) < len(rhs_shape): + # Add new axes to lhs + for _ in range(len(lhs_shape), len(rhs_shape)): + lhs = self.tensor(self.builder.create_expand_dims(lhs.handle, 0), + tl.block_type(lhs_ty.scalar, [1] + lhs_shape.values)) + lhs_ty = lhs.type + lhs_shape = lhs_ty.get_block_shapes() + elif len(rhs_shape) < len(lhs_shape): + # Add new axes to rhs + for _ in range(len(rhs_shape), len(lhs_shape)): + rhs = self.tensor(self.builder.create_expand_dims(rhs.handle, 0), + tl.block_type(rhs_ty.scalar, [1] + rhs_shape.values)) + rhs_ty = rhs.type + rhs_shape = rhs_ty.get_block_shapes() + assert len(rhs_shape) == len(lhs_shape) + + ret_shape = [] + for i, left in enumerate(lhs_shape): + right = rhs_shape[i] + if left == 1: + ret_shape.append(right) + elif (right == 1) or (right == left): + ret_shape.append(left) + else: + raise ValueError("Cannot make_shape_compatible: incompatible dimensions " + "at index " + str(i) + ": " + str(left) + " and " + str(right)) + if lhs_shape != ret_shape: + ret_ty = tl.block_type(lhs_ty.scalar, ret_shape) + lhs = self.tensor(self.builder.create_broadcast(lhs.handle, ret_shape), ret_ty) + if rhs_shape != ret_shape: + ret_ty = tl.block_type(rhs_ty.scalar, ret_shape) + rhs = self.tensor(self.builder.create_broadcast(rhs.handle, ret_shape), ret_ty) + # (scalar, scalar) => returns original blocks + return lhs, rhs + +####### +# cast +####### + + def _str_to_rounding_mode(self, rounding_mode: Optional[str]): + if rounding_mode is None: + return None + if rounding_mode == 'rtne': + return ir.ROUNDING_MODE.RTNE + if rounding_mode == 'rtz': + return ir.ROUNDING_MODE.RTZ + raise ValueError(f"Invalid rounding mode: {rounding_mode}. Supported rounding modes are 'rtne' and 'rtz'.") + + def bitcast(self, input: TensorTy, dst_ty: tl.dtype) -> TensorTy: + src_ty = input.type + if src_ty.is_block(): + dst_ty = src_ty.with_element_ty(dst_ty.scalar) + if src_ty == dst_ty: + return input + src_sca_ty = src_ty.scalar + dst_sca_ty = dst_ty.scalar + if src_sca_ty.is_ptr() or dst_sca_ty.is_ptr(): + return self.cast(input, dst_ty) + # Bitcast + src_bits = src_sca_ty.primitive_bitwidth + dst_bits = dst_sca_ty.primitive_bitwidth + if src_bits != dst_bits: + raise ValueError("Cannot bitcast data-type of size " + str(src_bits) + " to " + "data-type of size " + str(dst_bits)) + return self.tensor(self.builder.create_bitcast(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + + def cast(self, input: TensorTy, dst_ty: tl.dtype, fp_downcast_rounding: Optional[str] = None) -> TensorTy: + src_ty = input.type + src_sca_ty = src_ty.scalar + dst_sca_ty = dst_ty.scalar + if src_sca_ty == dst_sca_ty: + return input + if src_ty.is_block(): + dst_ty = src_ty.with_element_ty(dst_sca_ty) + + # For fp downcasting default rounding mode should be RTNE, for all other conversions it should + # not be set + fp_downcast_rounding = self._str_to_rounding_mode(fp_downcast_rounding) + use_custom_rounding = False + if dst_sca_ty.is_floating() and src_sca_ty.is_floating( + ) and dst_sca_ty.primitive_bitwidth < src_sca_ty.primitive_bitwidth: + if fp_downcast_rounding is None: fp_downcast_rounding = ir.ROUNDING_MODE.RTNE + elif fp_downcast_rounding != ir.ROUNDING_MODE.RTNE: use_custom_rounding = True + else: + if fp_downcast_rounding is not None: + raise ValueError("fp_downcast_rounding should be set only for truncating fp conversions. " + "Source scalar type is " + str(src_sca_ty) + " and destination type is " + + str(dst_sca_ty)) + + if (src_sca_ty.is_fp8e4b15() or dst_sca_ty.is_fp8e4b15()): + assert self.builder.codegen_fns.get( + "convert_custom_types") is not None, "target doesn't provide conversion for this type." + return self.builder.codegen_fns["convert_custom_types"](input, dst_ty, fp_downcast_rounding, _semantic=self) + # Casting with customized floating types involved: fp8 <=> bf16, fp16, fp32, fp64 + # and non-default rounding modes for downcasting + if (src_sca_ty.is_fp8() and dst_sca_ty.is_floating()) or \ + (src_sca_ty.is_floating() and dst_sca_ty.is_fp8()) or \ + use_custom_rounding: + return self.tensor( + self.builder.create_fp_to_fp(input.handle, dst_ty.to_ir(self.builder), fp_downcast_rounding), dst_ty) + + # bf16 <=> (not fp32) + if (src_sca_ty.is_fp16() and not dst_sca_ty.is_fp32()) or \ + (src_sca_ty.is_bf16() and not dst_sca_ty.is_fp32()): + return self.cast(self.cast(input, tl.float32), dst_sca_ty) + + # Standard floating types' casting: truncation + # fp64 => fp32, fp16, bf16 + # fp32 => fp16, bf16 + truncate_fp = src_sca_ty.is_floating() and \ + dst_sca_ty.is_floating() and \ + src_sca_ty.primitive_bitwidth > dst_sca_ty.primitive_bitwidth + if truncate_fp: + return self.tensor(self.builder.create_fp_trunc(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + + # Standard floating types' casting: extension + # fp32 => fp64 + # fp16 => fp32, fp64 + # bf16 => fp32, fp64 + ext_fp = src_sca_ty.is_floating() and \ + dst_sca_ty.is_floating() and \ + src_sca_ty.primitive_bitwidth < dst_sca_ty.primitive_bitwidth + if ext_fp: + return self.tensor(self.builder.create_fp_ext(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + + # Casting between integer types + if src_sca_ty.is_int() and dst_sca_ty.is_int() and \ + (src_sca_ty.int_bitwidth != dst_sca_ty.int_bitwidth or src_sca_ty.int_signedness != dst_sca_ty.int_signedness): + sign_extend = src_sca_ty.is_int_signed() and not src_sca_ty.is_bool() + if dst_sca_ty.is_bool(): + ty = input.dtype.to_ir(self.builder) + _0 = self.tensor(self.builder.get_null_value(ty), input.dtype) + return self.not_equal(input, _0) + else: + return self.tensor(self.builder.create_int_cast(input.handle, dst_ty.to_ir(self.builder), sign_extend), + dst_ty) + + # Casting standard floating types to integer types + if src_sca_ty.is_standard_floating() and dst_sca_ty.is_int(): + if dst_sca_ty.is_bool(): + ty = input.dtype.to_ir(self.builder) + _0 = self.tensor(self.builder.get_null_value(ty), input.dtype) + return self.not_equal(input, _0) + elif dst_sca_ty.is_int_signed(): + return self.tensor(self.builder.create_fp_to_si(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + else: + return self.tensor(self.builder.create_fp_to_ui(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + + # Casting integer types to standard floating types + if src_sca_ty.is_int() and dst_sca_ty.is_standard_floating(): + if src_sca_ty.is_bool() or not src_sca_ty.is_int_signed(): + return self.tensor(self.builder.create_ui_to_fp(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + else: + return self.tensor(self.builder.create_si_to_fp(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + + # Casting pointer types to integer types + if src_sca_ty.is_ptr() and dst_sca_ty.is_int(): + bitwidth = dst_sca_ty.int_bitwidth + if bitwidth == 64: + return self.tensor(self.builder.create_ptr_to_int(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + if bitwidth == 1: + return self.not_equal(self.cast(input, tl.int64), self.tensor(self.builder.get_int64(0), tl.int64)) + + # Casting integer types to pointer types + if src_sca_ty.is_int() and dst_sca_ty.is_ptr(): + return self.tensor(self.builder.create_int_to_ptr(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + + # Casting pointer types to pointer types + if src_sca_ty.is_ptr() and dst_sca_ty.is_ptr(): + return self.tensor(self.builder.create_bitcast(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + + assert False, f'cannot cast {input} to {dst_ty}' + +# ===----------------------------------------------------------------------===// +# Memory Operators +# ===----------------------------------------------------------------------===// + + def _str_to_load_cache_modifier(self, cache_modifier): + cache = ir.CACHE_MODIFIER.NONE # default + if cache_modifier: + if cache_modifier == ".ca": + cache = ir.CACHE_MODIFIER.CA + elif cache_modifier == ".cg": + cache = ir.CACHE_MODIFIER.CG + elif cache_modifier == ".cv": + cache = ir.CACHE_MODIFIER.CV + else: + raise ValueError(f"Cache modifier {cache_modifier} not supported") + return cache + + def _str_to_store_cache_modifier(self, cache_modifier): + cache = ir.CACHE_MODIFIER.NONE # default + if cache_modifier: + if cache_modifier == ".wb": + cache = ir.CACHE_MODIFIER.WB + elif cache_modifier == ".cg": + cache = ir.CACHE_MODIFIER.CG + elif cache_modifier == ".cs": + cache = ir.CACHE_MODIFIER.CS + elif cache_modifier == ".wt": + cache = ir.CACHE_MODIFIER.WT + else: + raise ValueError(f"Cache modifier {cache_modifier} not supported") + return cache + + def _str_to_eviction_policy(self, eviction_policy): + eviction = ir.EVICTION_POLICY.NORMAL # default + if eviction_policy: + if eviction_policy == "evict_last": + eviction = ir.EVICTION_POLICY.EVICT_LAST + elif eviction_policy == "evict_first": + eviction = ir.EVICTION_POLICY.EVICT_FIRST + else: + raise ValueError(f"Eviction policy {eviction_policy} not supported") + return eviction + + def _str_to_padding_option(self, padding_option): + padding = None # default + if padding_option: + if padding_option == "zero": + padding = ir.PADDING_OPTION.PAD_ZERO + elif padding_option == "nan": + padding = ir.PADDING_OPTION.PAD_NAN + else: + raise ValueError(f"Padding option {padding_option} not supported") + return padding + + def _str_to_sem(self, sem_option): + sem = ir.MEM_SEMANTIC.ACQUIRE_RELEASE + if sem_option: + if sem_option == "acquire": + sem = ir.MEM_SEMANTIC.ACQUIRE + elif sem_option == "release": + sem = ir.MEM_SEMANTIC.RELEASE + elif sem_option == "acq_rel": + sem = ir.MEM_SEMANTIC.ACQUIRE_RELEASE + elif sem_option == "relaxed": + sem = ir.MEM_SEMANTIC.RELAXED + else: + raise ValueError(f"Memory semantic {sem_option} not supported") + return sem + + def _str_to_scope(self, scope_option): + scope = ir.MEM_SYNC_SCOPE.GPU + if scope_option: + if scope_option == "gpu": + scope = ir.MEM_SYNC_SCOPE.GPU + elif scope_option == "cta": + scope = ir.MEM_SYNC_SCOPE.CTA + elif scope_option == "sys": + scope = ir.MEM_SYNC_SCOPE.SYSTEM + else: + raise ValueError(f"Memory semantic {scope_option} not supported") + return scope + + def _canonicalize_boundary_check(self, boundary_check, block_shape): + if boundary_check: + if not hasattr(boundary_check, "__iter__"): + boundary_check = [boundary_check] + boundary_check = [elem.value if isinstance(elem, tl.constexpr) else elem for elem in boundary_check] + for dim in boundary_check: + assert isinstance(dim, int) and 0 <= dim < len(block_shape) + assert len(boundary_check) > 0 + assert len(boundary_check) == len(set(boundary_check)), "Duplicate dimension in `boundary_check`" + return sorted(boundary_check) + return () + + def _load_block_pointer(self, ptr, mask, other, boundary_check, padding, cache, eviction, is_volatile): + # Load by a block pointer: `pointer_type>` + # Block pointer can not have `mask` and `other` arguments + if mask is not None or other is not None: + raise ValueError("`mask` and `other` arguments cannot be specified for loading block pointers") + + elt_ty = ptr.type.element_ty.element_ty + assert elt_ty != tl.int1, "`tl.int1` should be rewritten in `tl.make_block_ptr`" + if elt_ty.is_int() and padding == ir.PADDING_OPTION.PAD_NAN: + raise ValueError("Padding option `nan` is not supported for integer block pointers") + + # `dst_ty` is de-referenced type of the pointer type + dst_ty = ptr.type.element_ty + + # Check `boundary_check` argument + boundary_check = self._canonicalize_boundary_check(boundary_check, dst_ty.get_block_shapes()) + + # Build IR + return self.tensor( + self.builder.create_tensor_pointer_load(ptr.handle, boundary_check, padding, cache, eviction, is_volatile), + dst_ty) + + def _load_legacy(self, ptr, mask, other, boundary_check, padding, cache, eviction, is_volatile): + # Load by a tensor of pointers or a pointer of scalar: `block_type>` or `pointer_type<>` + if not ptr.type.scalar.is_ptr(): + raise ValueError(f"Unsupported ptr type {ptr.type.__repr__()} in `tl.load`") + + # Check `mask`, `other`, `boundary_check`, and `padding` arguments + if mask is None and other is not None: + raise ValueError("`other` cannot be provided without `mask`") + if padding or boundary_check: + raise ValueError("`padding_option` or `boundary_check` argument is not supported for loading a tensor of" + "pointers or loading a scalar. Because the compiler does not know the boundary; please " + "use block pointers (defined by `make_block_ptr`) instead") + + # For a pointer of scalar, check the type of `mask` and `other` + if not ptr.type.is_block(): + if mask and mask.type.is_block(): + raise ValueError("Mask argument cannot be block type if pointer argument is not a block") + if other and other.type.is_block(): + raise ValueError("Other argument cannot be block type if pointer argument is not a block") + + # Make `mask` and `other` into the same shape as `ptr` + if ptr.type.is_block(): + if mask is not None: + ptr, mask = self.broadcast_impl_value(ptr, mask) + if other is not None: + ptr, other = self.broadcast_impl_value(ptr, other) + + # Get `pointer_type` and `elt_ty` + ptr_ty = ptr.type.scalar + elt_ty = ptr_ty.element_ty + + # Treat `pointer_type` as `pointer_type` + is_bool = elt_ty == tl.int1 + if is_bool: + elt_ty = tl.int8 + ptr_ty = tl.pointer_type(elt_ty, ptr_ty.address_space) + ptr = self.cast(ptr, ptr_ty) + + # Cast `other` into `elt_ty` type + if other is not None: + other = self.cast(other, elt_ty) + + # Create loaded result type `dst_ty` + if ptr.type.is_block(): + dst_ty = ptr.type.with_element_ty(elt_ty) + else: + # Load by de-referencing the pointer of scalar + dst_ty = elt_ty + + # Build IR + if mask is None: + ret = self.tensor(self.builder.create_load(ptr.handle, cache, eviction, is_volatile), dst_ty) + else: + ret = self.tensor( + self.builder.create_masked_load(ptr.handle, mask.handle, other.handle if other else None, cache, + eviction, is_volatile), dst_ty) + if is_bool: + ret = self.cast(ret, tl.int1) + return ret + + def load(self, ptr: TensorTy, mask: Optional[TensorTy], other: Optional[TensorTy], boundary_check: Tuple, + padding_option: str, cache_modifier: str, eviction_policy: str, is_volatile: bool) -> TensorTy: + # Cache, eviction and padding options + cache = self._str_to_load_cache_modifier(cache_modifier) + eviction = self._str_to_eviction_policy(eviction_policy) + padding = self._str_to_padding_option(padding_option) + + if ptr.type.is_ptr() and ptr.type.element_ty.is_block(): + # Load by a block pointer: `pointer_type>` + return self._load_block_pointer(ptr, mask, other, boundary_check, padding, cache, eviction, is_volatile) + else: + # Load by a tensor of pointers or a pointer of scalar: `block_type>` or `pointer_type<>` + return self._load_legacy(ptr, mask, other, boundary_check, padding, cache, eviction, is_volatile) + + def descriptor_load(self, desc: tl.tensor_descriptor_base, offsets, cache_modifier: str, + eviction_policy: str) -> TensorTy: + assert isinstance(desc, tl.tensor_descriptor_base) + ndim = len(desc.block_shape) + assert len(offsets) == ndim, f"expected {ndim} offsets, but got {len(offsets)}" + + offsets = self._convert_to_ir_values(offsets, require_i64=False) + x = self.builder.create_descriptor_load(desc.handle, offsets, self._str_to_load_cache_modifier(cache_modifier), + self._str_to_eviction_policy(eviction_policy)) + return self.tensor(x, desc.block_type) + + def validate_store_like(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> None: + assert isinstance(desc, tl.tensor_descriptor_base) + ndim = len(desc.block_shape) + assert len(offsets) == ndim, f"expected {ndim} offsets, but got {len(offsets)}" + assert value.shape == desc.block_shape + + def descriptor_store(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> TensorTy: + self.validate_store_like(desc, value, offsets) + # implicitly cast to the descriptor's type + value = self.cast(value, desc.dtype) + offsets = self._convert_to_ir_values(offsets, require_i64=False) + return self.tensor(self.builder.create_descriptor_store(desc.handle, value.handle, offsets), tl.void) + + def descriptor_atomic_add(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> TensorTy: + self.validate_store_like(desc, value, offsets) + assert desc.dtype in {tl.uint32, tl.int32, tl.uint64, tl.float32, tl.float16, tl.bfloat16}, "Unsupported dtype" + offsets = self._convert_to_ir_values(offsets, require_i64=False) + kind = ir.DESCRIPTOR_REDUCE_KIND.ADD + return self.tensor(self.builder.create_descriptor_reduce(kind, desc.handle, value.handle, offsets), tl.void) + + def _has_native_tma(self, ): + target = driver.active.get_current_target() + return (target.backend == "cuda" and target.arch >= 90) + + def _descriptor_atomic_min_max_supported(self, dtype): + assert dtype in {tl.uint32, tl.int32, tl.uint64, tl.int64, tl.float16, tl.bfloat16}, "Unsupported dtype" + if dtype in {tl.float16, tl.bfloat16}: + assert self._has_native_tma(), "16-bit float types require native tma support" + + def descriptor_atomic_min(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> TensorTy: + self.validate_store_like(desc, value, offsets) + self._descriptor_atomic_min_max_supported(desc.dtype) + offsets = self._convert_to_ir_values(offsets, require_i64=False) + kind = ir.DESCRIPTOR_REDUCE_KIND.MIN + return self.tensor(self.builder.create_descriptor_reduce(kind, desc.handle, value.handle, offsets), tl.void) + + def descriptor_atomic_max(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> TensorTy: + self.validate_store_like(desc, value, offsets) + self._descriptor_atomic_min_max_supported(desc.dtype) + offsets = self._convert_to_ir_values(offsets, require_i64=False) + kind = ir.DESCRIPTOR_REDUCE_KIND.MAX + return self.tensor(self.builder.create_descriptor_reduce(kind, desc.handle, value.handle, offsets), tl.void) + + def descriptor_atomic_and(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> TensorTy: + self.validate_store_like(desc, value, offsets) + assert desc.dtype in {tl.uint32, tl.int32, tl.uint64, tl.int64}, "Unsupported dtype" + offsets = self._convert_to_ir_values(offsets, require_i64=False) + kind = ir.DESCRIPTOR_REDUCE_KIND.AND + return self.tensor(self.builder.create_descriptor_reduce(kind, desc.handle, value.handle, offsets), tl.void) + + def descriptor_atomic_or(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> TensorTy: + self.validate_store_like(desc, value, offsets) + assert desc.dtype in {tl.uint32, tl.int32, tl.uint64, tl.int64}, "Unsupported dtype" + offsets = self._convert_to_ir_values(offsets, require_i64=False) + kind = ir.DESCRIPTOR_REDUCE_KIND.OR + return self.tensor(self.builder.create_descriptor_reduce(kind, desc.handle, value.handle, offsets), tl.void) + + def descriptor_atomic_xor(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> TensorTy: + self.validate_store_like(desc, value, offsets) + assert desc.dtype in {tl.uint32, tl.int32, tl.uint64, tl.int64}, "Unsupported dtype" + offsets = self._convert_to_ir_values(offsets, require_i64=False) + kind = ir.DESCRIPTOR_REDUCE_KIND.XOR + return self.tensor(self.builder.create_descriptor_reduce(kind, desc.handle, value.handle, offsets), tl.void) + + def descriptor_gather(self, desc, x_offsets, y_offset, cache_modifier: str, eviction_policy: str) -> TensorTy: + assert isinstance(desc, tl.tensor_descriptor_base) + assert cache_modifier == "", "cache modifier is not supported yet" + assert eviction_policy == "", "eviction policy is not supported yet" + + # Validate descriptor. + assert len(desc.block_shape) == 2, f"descriptor must be 2D, but got {desc.block_shape}" + assert desc.block_shape[0] == 1, f"descriptor block must have 1 row, but got {desc.block_shape}" + + # Validate offsets. + assert len(x_offsets.shape) == 1, f"x offsets must be 1D, but got {x_offsets.shape}" + + # Validate minimum block size. + assert x_offsets.shape[0] >= 8, f"descriptor gather must have at least 8 rows, but got {x_offsets.shape}" + dtype = desc.dtype + min_cols = 32 // dtype.primitive_bitwidth * 8 + assert desc.block_shape[ + 1] >= min_cols, f"descriptor gather of {dtype} must have at least {min_cols} columns, but got {desc.block_shape[1]}" + + type = tl.block_type(desc.dtype, [x_offsets.shape[0], desc.block_shape[1]]) + y_offset = self._convert_to_ir_values((y_offset, ), require_i64=False)[0] + x = self.builder.create_descriptor_gather(desc.handle, x_offsets.handle, y_offset, type.to_ir(self.builder)) + return self.tensor(x, type) + + def descriptor_scatter(self, desc, value: TensorTy, x_offsets, y_offset) -> TensorTy: + assert isinstance(desc, tl.tensor_descriptor_base) + + # Validate descriptor. + assert len(desc.block_shape) == 2, f"descriptor must be 2D, but got {desc.block_shape}" + assert desc.block_shape[0] == 1, f"descriptor block must have 1 row, but got {desc.block_shape}" + + # Validate offsets. + assert len(x_offsets.shape) == 1, f"x offsets must be 1D, but got {x_offsets.shapae}" + + # Validate minimum block size. + assert x_offsets.shape[0] >= 8, f"descriptor scatter must have at least 8 rows, but got {x_offsets.shape}" + dtype = desc.dtype + min_cols = 32 // dtype.primitive_bitwidth * 8 + assert desc.block_shape[ + 1] >= min_cols, f"descriptor scatter of {dtype} must have at least {min_cols} columns, but got {desc.block_shape[1]}" + + y_offset = self._convert_to_ir_values((y_offset, ), require_i64=False)[0] + self.builder.create_descriptor_scatter(desc.handle, value.handle, x_offsets.handle, y_offset) + return self.tensor(None, tl.void) + + def _store_block_pointer(self, ptr, val, mask, boundary_check, cache, eviction): + # Store by a block pointer: `pointer_type>` + # Block pointers can not have the `mask` argument + if mask is not None: + raise ValueError("`mask` and `other` arguments cannot be specified for loading block pointers") + + # Check same shape and element type + block_shape = ptr.type.element_ty.get_block_shapes() + if not val.type.is_block(): + val = self.broadcast_impl_shape(val, block_shape) + assert val.type.is_block(), "Value argument must be block type or a scalar" + assert block_shape == val.type.get_block_shapes( + ), f"Block shape({block_shape}) and value shape({val.type.get_block_shapes()}) mismatch" + assert ptr.type.element_ty.element_ty == val.type.element_ty, f"Block element type({ptr.type.element_ty.element_ty}) and value element type({val.type.element_ty}) mismatch" + + elt_ty = ptr.type.element_ty.element_ty + assert elt_ty != tl.int1, "`tl.int1` should be rewritten in `tl.make_block_ptr`" + + # Check `boundary_check` argument + boundary_check = self._canonicalize_boundary_check(boundary_check, block_shape) + + # Cast to target data type + val = self.cast(val, elt_ty) + + # Build IR + return self.tensor( + self.builder.create_tensor_pointer_store(ptr.handle, val.handle, boundary_check, cache, eviction), tl.void) + + def _store_legacy(self, ptr, val, mask, boundary_check, cache, eviction): + # Store by a tensor of pointers or a pointer of scalar: `block_type>` or `pointer_type<>` + if not ptr.type.scalar.is_ptr(): + raise ValueError(f"Unsupported ptr type {ptr.type.__repr__()} in `tl.store`") + + # Check `boundary_check` argument + if boundary_check: + raise ValueError("`boundary_check` argument is not supported for storing a tensor of pointers or storing a " + "scalar. Because the compiler does not know the boundary; please use block pointers " + "(defined by `make_block_ptr`) instead") + + # For a pointer of scalar, check the type of `val` and `mask` + if not ptr.type.is_block(): + if val.type.is_block(): + raise ValueError("Value argument cannot be block type if pointer argument is not a block") + if mask and mask.type.is_block(): + raise ValueError("Mask argument cannot be block type if pointer argument is not a block") + + # Make `mask` and `val` into the same shape as `ptr` + if ptr.type.is_block(): + val = self.broadcast_impl_shape(val, ptr.type.get_block_shapes()) + if mask is not None: + mask = self.broadcast_impl_shape(mask, ptr.type.get_block_shapes()) + + ptr_ty = ptr.type.scalar + elt_ty = ptr_ty.element_ty + + # Treat `pointer_type` as `pointer_type` + if elt_ty == tl.int1: + elt_ty = tl.int8 + ptr_ty = tl.pointer_type(elt_ty, ptr_ty.address_space) + ptr = self.cast(ptr, ptr_ty) + + # Cast to target data type + val = self.cast(val, elt_ty) + + # Build IR + if mask is None: + return self.tensor(self.builder.create_store(ptr.handle, val.handle, cache, eviction), tl.void) + if not mask.type.scalar.is_bool(): + raise ValueError("Mask must have boolean scalar type") + return self.tensor(self.builder.create_masked_store(ptr.handle, val.handle, mask.handle, cache, eviction), + tl.void) + + def store(self, ptr: TensorTy, val: TensorTy, mask: Optional[TensorTy], boundary_check, cache_modifier: str, + eviction_policy: str) -> TensorTy: + # Cache and eviction options + cache = self._str_to_store_cache_modifier(cache_modifier) + eviction = self._str_to_eviction_policy(eviction_policy) + + if ptr.type.is_const() or ptr.type.scalar.is_const(): + raise ValueError("Cannot store to a constant pointer") + + if ptr.type.is_ptr() and ptr.type.element_ty.is_block(): + # Store by a block pointer: `pointer_type>` + return self._store_block_pointer(ptr, val, mask, boundary_check, cache, eviction) + else: + # Store by a tensor of pointers or a pointer of scalar: `block_type>` or `pointer_type<>` + return self._store_legacy(ptr, val, mask, boundary_check, cache, eviction) + +######### +# atomic +######### + + def atomic_cas(self, ptr: TensorTy, cmp: TensorTy, val: TensorTy, sem: str, scope: str) -> TensorTy: + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + element_ty = ptr.type.scalar.element_ty + if element_ty.primitive_bitwidth not in [16, 32, 64]: + raise ValueError("atomic_cas only supports elements with width {16, 32, 64}") + return self.tensor(self.builder.create_atomic_cas(ptr.handle, cmp.handle, val.handle, sem, scope), val.type) + + def atom_red_typechecking_impl(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, + op: str) -> Tuple[TensorTy, TensorTy, TensorTy]: + if not ptr.type.scalar.is_ptr(): + raise ValueError("Pointer argument of store instruction is " + ptr.type.__repr__()) + if ptr.type.is_const() or ptr.type.element_ty.is_const(): + raise ValueError("Cannot store to a constant pointer") + element_ty = ptr.type.scalar.element_ty + if element_ty is tl.float16 and op != 'add': + raise ValueError("atomic_" + op + " does not support fp16") + if element_ty is tl.bfloat16 and op != 'add': + raise ValueError("atomic_" + op + " does not support bf16") + if element_ty in [tl.int16, tl.uint16] or element_ty.primitive_bitwidth < 16: + raise ValueError("atomic_" + op + " does not support " + str(element_ty)) + if ptr.type.is_block(): + if mask is not None: + mask = self.broadcast_impl_shape(mask, ptr.type.get_block_shapes()) + if val is not None: + val = self.broadcast_impl_shape(val, ptr.type.get_block_shapes()) + val = self.cast(val, ptr.type.scalar.element_ty) + if mask is None: + mask_ir = self.builder.get_int1(True) + mask_ty = tl.int1 + if ptr.type.is_block(): + mask_ty = ptr.type.with_element_ty(tl.int1) + mask_ir = self.builder.create_splat(mask_ty.to_ir(self.builder), mask_ir) + mask = self.tensor(mask_ir, mask_ty) + return ptr, val, mask + + def _signbit(self, x: TensorTy) -> TensorTy: + bitwidth = x.dtype.primitive_bitwidth + idtype = tl.get_int_dtype(bitwidth=bitwidth, signed=False) + ix = self.bitcast(x, idtype) + signbit = self.lshr(ix, bitwidth - 1) + return self.cast(signbit, tl.int1) + + def atomic_max(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, sem: str, scope: str) -> TensorTy: + ptr, val, mask = self.atom_red_typechecking_impl(ptr, val, mask, 'max') + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + sca_ty = val.type.scalar + # direct call to atomic_max for integers + if sca_ty.is_int(): + if sca_ty.is_int_signed(): + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.MAX, ptr.handle, val.handle, mask.handle, sem, scope), + val.type) + else: + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.UMAX, ptr.handle, val.handle, mask.handle, sem, scope), + val.type) + # for float + # return atomic_smax(i_ptr, i_val) if val >= 0 + # return atomic_umin(i_ptr, i_val) if val < 0 + if sca_ty not in {tl.float32, tl.float64}: + raise TypeError(f"atomic_max not supported for dtype {sca_ty}") + + i_type = tl.int32 if sca_ty == tl.float32 else tl.int64 + i_val = self.bitcast(val, i_type) + i_ptr = self.bitcast(ptr, tl.pointer_type(i_type, 1)) + ui_type = tl.uint32 if sca_ty == tl.float32 else tl.uint64 + ui_val = self.bitcast(val, ui_type) + ui_ptr = self.bitcast(ptr, tl.pointer_type(ui_type, 1)) + neg = self._signbit(val) + pos = self.not_(neg) + pos_ret = self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.MAX, i_ptr.handle, i_val.handle, + self.and_(mask, pos).handle, sem, scope), i_val.type) + neg_ret = self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.UMIN, ui_ptr.handle, ui_val.handle, + self.and_(mask, neg).handle, sem, scope), ui_val.type) + ret = self.where(pos, pos_ret, neg_ret) + return self.bitcast(ret, sca_ty) + + def atomic_min(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, sem: str, scope: str) -> TensorTy: + ptr, val, mask = self.atom_red_typechecking_impl(ptr, val, mask, 'min') + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + sca_ty = val.type.scalar + # direct call to atomic_min for integers + if sca_ty.is_int(): + if sca_ty.is_int_signed(): + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.MIN, ptr.handle, val.handle, mask.handle, sem, scope), + val.type) + else: + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.UMIN, ptr.handle, val.handle, mask.handle, sem, scope), + val.type) + # for float + # return atomic_smin(i_ptr, i_val) if val >= 0 + # return atomic_umax(i_ptr, i_val) if val < 0 + if sca_ty not in {tl.float32, tl.float64}: + raise TypeError(f"atomic_min not supported for dtype {sca_ty}") + + i_type = tl.int32 if sca_ty == tl.float32 else tl.int64 + i_val = self.bitcast(val, i_type) + i_ptr = self.bitcast(ptr, tl.pointer_type(i_type, 1)) + ui_type = tl.uint32 if sca_ty == tl.float32 else tl.uint64 + ui_val = self.bitcast(val, ui_type) + ui_ptr = self.bitcast(ptr, tl.pointer_type(ui_type, 1)) + neg = self._signbit(val) + pos = self.not_(neg) + pos_ret = self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.MIN, i_ptr.handle, i_val.handle, + self.and_(mask, pos).handle, sem, scope), i_val.type) + neg_ret = self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.UMAX, ui_ptr.handle, ui_val.handle, + self.and_(mask, neg).handle, sem, scope), ui_ptr.type) + ret = self.where(pos, pos_ret, neg_ret) + return self.bitcast(ret, sca_ty) + + def atomic_add(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, sem: str, scope: str) -> TensorTy: + ptr, val, mask = self.atom_red_typechecking_impl(ptr, val, mask, 'add') + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + sca_ty = val.type.scalar + op = ir.ATOMIC_OP.FADD if sca_ty.is_floating() else ir.ATOMIC_OP.ADD + return self.tensor(self.builder.create_atomic_rmw(op, ptr.handle, val.handle, mask.handle, sem, scope), + val.type) + + def atomic_and(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, sem: str, scope: str) -> TensorTy: + ptr, val, mask = self.atom_red_typechecking_impl(ptr, val, mask, 'and') + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.AND, ptr.handle, val.handle, mask.handle, sem, scope), val.type) + + def atomic_or(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, sem: str, scope: str) -> TensorTy: + ptr, val, mask = self.atom_red_typechecking_impl(ptr, val, mask, 'or') + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.OR, ptr.handle, val.handle, mask.handle, sem, scope), val.type) + + def atomic_xor(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, sem: str, scope: str) -> TensorTy: + ptr, val, mask = self.atom_red_typechecking_impl(ptr, val, mask, 'xor') + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.XOR, ptr.handle, val.handle, mask.handle, sem, scope), val.type) + + def atomic_xchg(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, sem: str, scope: str) -> TensorTy: + ptr, val, mask = self.atom_red_typechecking_impl(ptr, val, mask, 'xchg') + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.XCHG, ptr.handle, val.handle, mask.handle, sem, scope), + val.type) + +# ===----------------------------------------------------------------------===// +# Linear Algebra +# ===----------------------------------------------------------------------===// + + def _str_to_dot_input_precision(self, input_precision): + assert input_precision.lower() in self.builder.options.allowed_dot_input_precisions, \ + f"input_precision must be one of {self.builder.options.allowed_dot_input_precisions}. Got {input_precision}" + input_precision = input_precision.upper() + if input_precision == "TF32X3": + input_precision = "TF32x3" + return getattr(ir.INPUT_PRECISION, input_precision) + + def dot(self, lhs: TensorTy, rhs: TensorTy, acc: TensorTy, input_precision: Optional[str], + max_num_imprecise_acc: int, out_dtype: tl.dtype) -> TensorTy: + assert lhs.type.is_block() and rhs.type.is_block() + + if lhs.dtype.is_fp8() and rhs.dtype.is_fp8(): + # All combinations of supported fp8 x fp8 are permitted + pass + else: + assert lhs.dtype in (tl.int8, tl.uint8, tl.float16, tl.bfloat16, tl.float32, + tl.float64), f"Unsupported lhs dtype {lhs.dtype}" + assert rhs.dtype in (tl.int8, tl.uint8, tl.float16, tl.bfloat16, tl.float32, + tl.float64), f"Unsupported rhs dtype {rhs.dtype}" + assert lhs.dtype == rhs.dtype, f"Both operands must be same dtype. Got {lhs.dtype} and {rhs.dtype}" + + if lhs.dtype.is_fp8e4b15() or rhs.dtype.is_fp8e4b15(): + if "fp8e4b15" in self.builder.options.deprecated_fp8_dot_operand_dtypes: + warnings.warn( + "the use of fp8e4b15 is deprecated on Hopper and later architectures and can cause significant slow down. It will be removed in a future triton release" + ) + # We upcast because there's no fp8e4b15 type in MLIR + lhs = self.cast(lhs, tl.float16) + rhs = self.cast(rhs, tl.float16) + + uses_fp8e4b8 = lhs.dtype.is_fp8e4b8() or rhs.dtype.is_fp8e4b8() + uses_fp8e5b16 = lhs.dtype.is_fp8e5b16() or rhs.dtype.is_fp8e5b16() + if uses_fp8e4b8 or uses_fp8e5b16: + type_name = "fp8e4b8" if uses_fp8e4b8 else "fp8e5b16" + if type_name in self.builder.options.deprecated_fp8_dot_operand_dtypes: + arch = self.builder.options.arch + warnings.warn( + f"{type_name} is AMD gfx942 specific and not supported on {arch} so it's upcasted to fp16 and can cause significant slow down. " + f"Please use OCP fp8 variants on {arch} for performance") + lhs = self.cast(lhs, tl.float16) + rhs = self.cast(rhs, tl.float16) + + if input_precision is None: + input_precision = self.builder.options.default_dot_input_precision + + input_precision = self._str_to_dot_input_precision(input_precision) + + lhs_rank = len(lhs.shape) + rhs_rank = len(rhs.shape) + assert lhs_rank == rhs_rank == 2 or lhs_rank == rhs_rank == 3, f"Both inputs must be either 2D or 3D; (lhs: {lhs.shape} vs rhs: {rhs.shape})" + assert lhs.shape[-1].value == rhs.shape[ + -2].value, f"First input shape ({lhs.shape}) and second input shape {rhs.shape} are not compatible for matmul (second index of first shape ({lhs.shape[-1].value}) must be equal to first index of second shape ({rhs.shape[-2].value})" + assert self.builder.codegen_fns.get( + "min_dot_size") is not None, "target doesn't provide lower shape bounds for dot." + min_dot_size = self.builder.codegen_fns["min_dot_size"](lhs.type, rhs.type) + assert lhs.shape[-2].value >= min_dot_size[0] and lhs.shape[-1].value >= min_dot_size[2] \ + and rhs.shape[-1].value >= min_dot_size[1], \ + f"Input shapes should have M >= {min_dot_size[0]}, N >= {min_dot_size[1]} and K >= {min_dot_size[2]}" + if lhs.type.scalar.is_int(): + assert lhs.type.scalar == tl.int8, "only int8 supported!" + _0 = self.builder.get_int32(0) + ret_scalar_ty = tl.int32 + elif out_dtype.is_bf16(): + raise ValueError( + "out_dtype=bfloat16 is unsupported. Please use out_dtype=float32/float16 and cast with `.to(tl.bfloat16)`" + ) + elif lhs.type.scalar.is_fp32() or lhs.type.scalar.is_bf16(): + _0 = self.builder.get_fp32(0) + ret_scalar_ty = tl.float32 + elif lhs.type.scalar.is_fp64(): + _0 = self.builder.get_fp64(0) + ret_scalar_ty = tl.float64 + else: + _0 = self.builder.get_fp16(0) if out_dtype.is_fp16() else self.builder.get_fp32(0) + ret_scalar_ty = out_dtype + + M = lhs.type.shape[-2] + N = rhs.type.shape[-1] + K = lhs.type.shape[-1] + B = lhs.type.shape[0] if lhs_rank == 3 else None + ret_ty = tl.block_type(ret_scalar_ty, [B, M, N] if B else [M, N]) + if acc is None: + acc_handle = self.builder.create_splat(ret_ty.to_ir(self.builder), _0) + else: + acc_handle = acc.handle + assert acc.type.shape == ret_ty.shape and acc.type.element_ty == out_dtype + + # max_num_imprecise_acc only applies to fp8 -> fp32 dot on sm_90 + if max_num_imprecise_acc is None: + if lhs.dtype.is_fp8() and rhs.dtype.is_fp8(): + max_num_imprecise_acc = self.builder.options.max_num_imprecise_acc_default + else: + max_num_imprecise_acc = 0 + else: + if lhs.dtype.is_fp8() and rhs.dtype.is_fp8() and max_num_imprecise_acc > K: + raise ValueError(f"max_num_imprecise_acc ({max_num_imprecise_acc}) must be <= K ({K})") + + return self.tensor( + self.builder.create_dot(lhs.handle, rhs.handle, acc_handle, input_precision, max_num_imprecise_acc), ret_ty) + + def _str_to_fp_type(self, float_format: str): + ty_enum = getattr(ir.ScaleDotElemTypeTY, float_format.upper(), None) + if ty_enum is None: + raise ValueError(f"Invalid float format: {float_format}.") + return ty_enum + + def _bitcast_to_fp_type(self, val: TensorTy, float_format: str): + """ + If float_format is subbyte, make sure it's packed as uint8 and return it. + Otherwise, return a tensor (perhaps bitcasting) of the specified float format. + """ + triton_ty = {"e5m2": tl.float8e5, "e4m3": tl.float8e4nv, "bf16": tl.bfloat16, "fp16": + tl.float16}.get(float_format) + if triton_ty is None: + assert float_format == "e2m1", f"Internal Error: Unexpected float format: {float_format}" + assert val.dtype == tl.uint8, f"e2m1 format must be packed as uint8. Got {val.dtype}" + return val + if val.dtype == triton_ty: + return val + else: + unsigned_ty = {"e5m2": tl.uint8, "e4m3": tl.uint8, "bf16": tl.uint16, "fp16": tl.uint16}[float_format] + assert val.dtype == unsigned_ty, f"Unexpected dtype for {float_format}. Got {val.dtype}" + return self.bitcast(val, triton_ty) + + def dot_scaled(self, lhs: TensorTy, lhs_scale: TensorTy, lhs_format: str, rhs: TensorTy, + rhs_scale: Optional[TensorTy], rhs_format: str, acc: TensorTy | None, fast_math: bool, + lhs_k_pack: bool, rhs_k_pack: bool, out_dtype: tl.dtype) -> TensorTy: + assert lhs.type.is_block() and rhs.type.is_block() + #TODO: validate types. + lhs_rank = len(lhs.shape) + rhs_rank = len(rhs.shape) + assert lhs_rank == rhs_rank == 2 or lhs_rank == rhs_rank == 3, f"Both inputs must be either 2D or 3D; (lhs: {lhs.shape} vs rhs: {rhs.shape})" + lhs_format: str = lhs_format.value + rhs_format: str = rhs_format.value + lhs_format_enum = self._str_to_fp_type(lhs_format) + rhs_format_enum = self._str_to_fp_type(rhs_format) + allowed_formats = {"e2m1", "e4m3", "e5m2", "bf16", "fp16"} + assert lhs_format in allowed_formats, f"NYI: lhs_format {lhs_format}" + assert rhs_format in allowed_formats, f"NYI: rhs_format {rhs_format}" + rhs_scale_is_none = rhs_scale is None or (isinstance(rhs_scale, tl.constexpr) and rhs_scale.value is None) + lhs_scale_is_none = lhs_scale is None or (isinstance(lhs_scale, tl.constexpr) and lhs_scale.value is None) + lhs = self._bitcast_to_fp_type(lhs, lhs_format) + rhs = self._bitcast_to_fp_type(rhs, rhs_format) + + assert lhs_k_pack or lhs_format == "e2m1", "only mxfp4 inputs can be packed along a dimension different than K" + assert rhs_k_pack or rhs_format == "e2m1", "only mxfp4 inputs can be packed along a dimension different than K" + M, K_LHS = lhs.type.shape[-2:] + K_RHS, N = rhs.type.shape[-2:] + PACKED_A = 2 if lhs_format == "e2m1" else 1 + PACKED_B = 2 if rhs_format == "e2m1" else 1 + PACKED_A_DIM = PACKED_A * K_LHS if lhs_k_pack else K_LHS + PACKED_B_DIM = PACKED_B * K_RHS if rhs_k_pack else K_RHS + assert PACKED_B_DIM == PACKED_A_DIM, f"Reduction dimension should pack the same number of elements; (lhs: {lhs.shape} vs rhs: {rhs.shape})" + #assert K * PACKED_B >= 64, f"scaled_dot NYI for K < 64. Got {K=}" + B = lhs.type.shape[0] if lhs_rank == 3 else None + if not lhs_k_pack: + M = M * PACKED_A + if not rhs_k_pack: + N = N * PACKED_B + ret_ty = tl.block_type(out_dtype, [B, M, N] if B else [M, N]) + _0 = self.builder.get_fp32(0) + if acc is None: + acc_handle = self.builder.create_splat(ret_ty.to_ir(self.builder), _0) + else: + acc_handle = acc.handle + assert acc.type.shape == ret_ty.shape and acc.type.element_ty == out_dtype + rhs_scale_handle = None if rhs_scale_is_none else rhs_scale.handle + lhs_scale_handle = None if lhs_scale_is_none else lhs_scale.handle + return self.tensor( + self.builder.create_dot_scaled(lhs.handle, lhs_scale_handle, lhs_format_enum, rhs.handle, rhs_scale_handle, + rhs_format_enum, fast_math, lhs_k_pack, rhs_k_pack, acc_handle), ret_ty) + +# ===----------------------------------------------------------------------===// +# Indexing +# ===----------------------------------------------------------------------===// + + def where(self, condition: TensorTy, x: TensorTy, y: TensorTy) -> TensorTy: + if condition.dtype != tl.int1: + warnings.warn( + f"tl.where with a non-boolean condition is deprecated and will error out in a future triton release. Got {condition.dtype}" + ) + condition = self.cast(condition, tl.int1) + x, y = self.binary_op_type_checking_impl(x, y, True, True) + # x, y are broadcasted + if condition.type.is_block(): + condition, x = self.broadcast_impl_value(condition, x) + x, y = self.broadcast_impl_value(x, y) + else: + condition, _ = self.broadcast_impl_value(condition, x) + ret_ty = x.type + return self.tensor(self.builder.create_select(condition.handle, x.handle, y.handle), ret_ty) + +# ===----------------------------------------------------------------------===// +# Reduction +# ===----------------------------------------------------------------------=== + + def wrap_tensor(self, x, scalar_ty, ret_shape): + if ret_shape: + res_ty = tl.block_type(scalar_ty, ret_shape) + else: + # 0d-tensor -> scalar + res_ty = scalar_ty + return self.tensor(x, res_ty) + + def reduction(self, inputs: Sequence[TensorTy], axis: int, region_builder_fn) -> Tuple[TensorTy, ...]: + if axis is None: + inputs = tuple(self.reshape(t, [t.numel.value], can_reorder=True) for t in inputs) + axis = 0 + # get result shape + shape = inputs[0].type.shape + rank = len(shape) + assert axis < rank, f"reduction axis must be < inputs rank ({rank})" + ret_shape = [s for i, s in enumerate(shape) if i != axis] + assert all(t.type.shape == shape for t in inputs), "all reduction inputs must have the same shape" + + reduce_op = self.builder.create_reduce([t.handle for t in inputs], axis) + region_builder_fn(reduce_op) + assert reduce_op.verify() + + return tuple( + self.wrap_tensor(reduce_op.get_result(i), inputs[i].type.scalar, ret_shape) for i in range(len(inputs))) + +# ===----------------------------------------------------------------------=== +# Associative Scan +# ===----------------------------------------------------------------------=== + + def associative_scan(self, inputs: Sequence[TensorTy], axis: int, region_builder_fn, + reverse: bool) -> Tuple[TensorTy, ...]: + shape = inputs[0].type.shape + rank = len(shape) + + assert -rank <= axis < rank, f"scan axis {axis} must be < inputs rank ({rank})" + + if axis < 0: + axis += rank + + for t in inputs: + assert t.type.shape == shape, "all scan inputs must have the same shape" + + scan_op = self.builder.create_scan([t.handle for t in inputs], axis, reverse) + region_builder_fn(scan_op) + assert scan_op.verify() + + return tuple(self.wrap_tensor(scan_op.get_result(i), inputs[i].type.scalar, shape) for i in range(len(inputs))) + +# ===----------------------------------------------------------------------=== +# Gather +# ===----------------------------------------------------------------------=== + + def gather(self, src: TensorTy, index: TensorTy, axis: int) -> TensorTy: + assert index.dtype.is_int(), "index must be an integer tensor" + + rank = len(src.type.shape) + assert len(index.type.shape) == rank, "source and index tensors must have the same rank" + + assert -rank <= axis < rank, f"gather axis {axis} must be < source rank ({rank})" + if axis < 0: + axis += rank + + for d in range(rank): + if d == axis: + continue + assert index.type.shape[d] == src.type.shape[d], f"index dim {axis} must match the corresponding source dim" + + gather = self.builder.create_gather(src.handle, index.handle, axis) + return self.wrap_tensor(gather, src.type.scalar, index.type.shape) + +# ===----------------------------------------------------------------------=== +# Map Elementwise +# ===----------------------------------------------------------------------=== + + def broadcast_tensors(self, *inputs): + if not inputs: + return () + head, *tail = inputs + for i in range(len(tail)): + head, tail[i] = self.broadcast_impl_value(head, tail[i]) + for i in range(len(tail)): + head, tail[i] = self.broadcast_impl_value(head, tail[i]) + return (head, *tail) + + def map_elementwise(self, inputs: Sequence[tl.tensor], result_types: Sequence[tl.dtype], pack: int, + region_builder_fn) -> Tuple[tl.tensor, ...]: + inputs = self.broadcast_tensors(*inputs) + + assert len(inputs) > 0, "map_elementwise must have at least 1 input tensor" + result_types = [inputs[0].type.with_element_ty(ty.scalar) for ty in result_types] + elementwise_op = self.builder.create_map_elementwise( + [t.handle for t in inputs], + [ty.to_ir(self.builder) for ty in result_types], + pack, + ) + region_builder_fn(elementwise_op) + # assert elementwise_op.verify() + + return tuple(self.tensor(elementwise_op.get_result(i), ty) for i, ty in enumerate(result_types)) + + +# ===----------------------------------------------------------------------=== +# Histogram +# ===----------------------------------------------------------------------=== + + def histogram(self, input: TensorTy, num_bins: int, mask: Optional[TensorTy]) -> TensorTy: + assert len(input.shape) == 1, "histogram only supports 1D input" + assert input.dtype.is_int(), "histogram only supports integer input" + if mask is not None: + mask = self.broadcast_impl_shape(mask, input.shape) + if not mask.type.scalar.is_bool(): + raise ValueError("Mask must have boolean scalar type") + mask = mask.handle + return self.tensor(self.builder.create_histogram(input.handle, num_bins, mask), + tl.block_type(tl.int32, [num_bins])) + + def multiple_of(self, x: TensorTy, values: List[int]) -> TensorTy: + if max(1, len(x.shape)) != len(values): + raise ValueError("Shape of input to multiple_of does not match the length of values") + x.handle.set_attr("tt.divisibility", ir.make_attr(values, x.handle.get_context())) + return x + + def max_contiguous(self, x: TensorTy, values: List[int]) -> TensorTy: + if len(x.shape) != len(values): + raise ValueError("Shape of input to max_contiguous does not match the length of values") + x.handle.set_attr("tt.contiguity", ir.make_attr(values, x.handle.get_context())) + return x + + def max_constancy(self, x: TensorTy, values: List[int]) -> TensorTy: + if len(x.shape) != len(values): + raise ValueError("Shape of input to max_constancy does not match the length of values") + x.handle.set_attr("tt.constancy", ir.make_attr(values, x.handle.get_context())) + return x + + def debug_barrier(self) -> TensorTy: + return self.tensor(self.builder.create_barrier(), tl.void) + + def device_print(self, prefix: str, args: List[TensorTy], hex: bool) -> TensorTy: + # It makes sense visually for prefix to end in ": "; make it so. Also, + # non-empty prefixes should start with " ". + if not prefix.endswith(" ") and args: + prefix += " " + if not prefix.endswith(": ") and args: + prefix = prefix[:-1] + ": " + if len(prefix) > 2 and not prefix.startswith(" "): + prefix = " " + prefix + + new_args = [arg.handle for arg in args] + is_signed = [arg.dtype.is_int_signed() for arg in args] + return self.tensor(self.builder.create_print(prefix, hex, new_args, is_signed), tl.void) + + def device_assert(self, cond: TensorTy, msg: str, mask: Optional[TensorTy]) -> TensorTy: + if not self.builder.options.debug: + return + if mask is not None: + cond = self.or_(cond, self.not_(mask)) + return self.tensor(self.builder.create_assert(cond.handle, msg), tl.void) + + def assume(self, cond) -> TensorTy: + return self.tensor(self.builder.create_assume(cond.handle), tl.void) + + def _convert_elem_to_ir_value(self, elem, require_i64): + if isinstance(elem, int): + elem = tl.constexpr(elem) + if isinstance(elem, tl.constexpr): + if isinstance(elem.value, bool): + return self.builder.get_int1(elem.value) + if require_i64: + assert -2**63 <= elem.value < 2**63, f"Block pointers only support 64 bit `shape/strides`, " \ + f"got a value {elem.value} which is out of the range" + return self.builder.get_int64(elem.value) + else: + assert -2**31 <= elem.value < 2**31, f"Block pointers only support 32 bit `offsets/block_shape`, " \ + f"got a value {elem.value} which is out of the range" + return self.builder.get_int32(elem.value) + elif isinstance(elem, tl.tensor): + assert elem.numel.value == 1, "Expected a scalar in shape/strides/offsets" + assert elem.dtype.is_int(), "Expected an integer scalar type in shape/strides/offsets" + if elem.dtype != tl.int64 and require_i64: + return self.builder.create_int_cast(elem.handle, self.builder.get_int64_ty(), + elem.dtype.is_int_signed()) + elif elem.dtype == tl.int64 and not require_i64: + assert False, "Block pointers only support 32 bit `offsets/block_shape`, " \ + "add a `.to(tl.int32)` or use regular indexing for 64 bit support" + return elem.handle + assert False, f"Unsupported element type in shape/strides/offsets: {type(elem)}" + + def _convert_to_ir_values(self, list_like, require_i64=True): + if hasattr(list_like, "__iter__"): + return [self._convert_elem_to_ir_value(elem, require_i64) for elem in list_like] + return [self._convert_elem_to_ir_value(list_like, require_i64)] + + def make_block_ptr(self, base: TensorTy, shape, strides, offsets, block_shape, order) -> TensorTy: + # Convert dynamic arguments to IR values + # NOTES(Chenggang): current `shape/strides` are `int64_t`, while `offsets/block_shape` are `int32_t` + shape = self._convert_to_ir_values(shape) + strides = self._convert_to_ir_values(strides) + offsets = self._convert_to_ir_values(offsets, require_i64=False) + + # Check `base` type + if not base.type.is_ptr() or base.type.element_ty.is_block(): + raise ValueError("Expected `base` to be a pointer type (but not a block pointer type or others)") + + # Treat `pointer_type` as `pointer_type` + if base.type.element_ty == tl.int1: + base = self.cast(base, tl.pointer_type(tl.int8, base.type.address_space)) + + # Check whether `block_shape` is static + if not hasattr(block_shape, "__iter__"): + block_shape = [block_shape] + block_shape = [elem.value if isinstance(elem, tl.constexpr) else elem for elem in block_shape] + assert all(isinstance(elem, int) and -2**31 <= elem < 2**31 for elem in block_shape), \ + "Expected a list of constant integers (`int32_t` range) in `block_shape`" + + # Check `order` + if not hasattr(order, "__iter__"): + order = [order] + order = [elem.value if isinstance(elem, tl.constexpr) else elem for elem in order] + assert sorted(order) == list(range(len(order))), "Expected a permutation of (0, 1, ..., len(order)-1) in order" + + # Must have same length + assert all(len(block_shape) == len(list_like) for list_like in [shape, strides, offsets, order]), \ + "Expected shape/strides/offsets/block_shape to have the same length" + + # Build value, the type is: + # `pointer_type>` in Python + # `tt.ptr>` in MLIR + handle = self.builder.create_make_block_ptr(base.handle, shape, strides, offsets, block_shape, order) + return self.tensor(handle, tl.pointer_type(tl.block_type(base.type.element_ty, block_shape))) + + def advance(self, base: TensorTy, offsets) -> TensorTy: + # Convert dynamic offsets to IR values + offsets = self._convert_to_ir_values(offsets, require_i64=False) + + # Advanced block pointer type is the same as before + return self.tensor(self.builder.create_advance(base.handle, offsets), base.type) + + def make_tensor_descriptor(self, base: TensorTy, shape: List[TensorTy], strides: List[TensorTy], + block_shape: List[tl.constexpr], padding_option: str = "zero") -> tl.tensor_descriptor: + ndim = len(shape) + if not (1 <= ndim <= 5): + raise ValueError(f"Expected 1 <= ndim <= 5 but got {ndim} dimensions") + if len(strides) != ndim: + raise ValueError(f"Expected {ndim} strides but got {len(strides)}") + if len(block_shape) != ndim: + raise ValueError(f"Expected block_shape to have {ndim} dimensions but got {len(strides)}") + assert isinstance(base.dtype, tl.pointer_type) + elem_size = base.dtype.element_ty.primitive_bitwidth // 8 + contig_dim_size = tl._unwrap_if_constexpr(block_shape[-1]) + if contig_dim_size * elem_size < 16: + raise ValueError( + f"Descriptor block shape must have at least 16 bytes in the last dimension, but got {contig_dim_size} * {elem_size} = {contig_dim_size * elem_size} bytes" + ) + + last_stride = tl._unwrap_if_constexpr(strides[-1]) + if last_stride != 1: + raise ValueError(f"Tensor descriptor last dim must be 1 but got {last_stride}") + + shape = [self.make_scalar(x, tl.int32) for x in shape] + strides = [self.make_scalar(tl._unwrap_if_constexpr(x), tl.int64) for x in strides] + + # Check whether `block_shape` is static + block_shape = tl._unwrap_shape(block_shape) + + assert isinstance(base.type, tl.pointer_type) + type = tl.block_type(base.type.element_ty, block_shape) + base_handle = base.handle + is_signed_int = base.type.element_ty.is_int_signed() + + padding = self._str_to_padding_option(padding_option) + + if base.type.element_ty.is_int() and padding == ir.PADDING_OPTION.PAD_NAN: + raise ValueError("Padding option `nan` is not supported for integer blocks") + + handle = self.builder.create_make_tensor_descriptor(base_handle, [s.handle for s in shape], + [s.handle for s in strides], block_shape, is_signed_int, + padding) + return tl.tensor_descriptor(handle, shape, strides, type) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/standard.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/standard.py new file mode 100644 index 0000000000000000000000000000000000000000..4d3a8a1df46c9470d9d10409758ea94ae7638346 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/standard.py @@ -0,0 +1,534 @@ +from __future__ import annotations + +from ..runtime.jit import jit, constexpr_function +from . import core +from . import math + +# constexpr utilities + + +@constexpr_function +def _log2(i): + log2 = 0 + n = i + while n > 1: + n >>= 1 + log2 += 1 + return log2 + + +@constexpr_function +def _is_power_of_two(i): + return (i & (i - 1)) == 0 and i != 0 + + +# ----------------------- +# Standard library +# ----------------------- + + +@core._tensor_member_fn +@jit +def cdiv(x, div): + """ + Computes the ceiling division of :code:`x` by :code:`div` + + :param x: the input number + :type x: Block + :param div: the divisor + :type div: Block + """ + return (x + div - 1) // div + + +@core._tensor_member_fn +@jit +@math._add_math_1arg_docstr("sigmoid") +def sigmoid(x): + return 1 / (1 + math.exp(-x)) + + +@core._tensor_member_fn +@jit +@math._add_math_1arg_docstr("softmax") +def softmax(x, dim=None, keep_dims=False, ieee_rounding=False): + if dim is None: + _dim: core.constexpr = 0 + else: + _dim: core.constexpr = dim + z = x - max(x, _dim, keep_dims=keep_dims) + num = math.exp(z) + den = sum(num, _dim, keep_dims=keep_dims) + return math.fdiv(num, den, ieee_rounding) + + +@core._tensor_member_fn +@jit +def ravel(x, can_reorder=False): + """ + Returns a contiguous flattened view of :code:`x`. + + :param x: the input tensor + :type x: Block + """ + return core.reshape(x, [x.numel], can_reorder=can_reorder) + + +@jit +def swizzle2d(i, j, size_i, size_j, size_g): + """ + Transforms the indices of a row-major `size_i * size_j` matrix into + the indices of a column-major matrix for each group of `size_g` rows. + + For example, for :code:`size_i = size_j = 4` and :code:`size_g = 2`, it will + transform :: + + [[0 , 1 , 2 , 3 ], + [4 , 5 , 6 , 7 ], + [8 , 9 , 10, 11], + [12, 13, 14, 15]] + + into :: + + [[0, 2, 4 , 6 ], + [1, 3, 5 , 7 ], + [8, 10, 12, 14], + [9, 11, 13, 15]] + """ + # "unrolled index in array" + ij = i * size_j + j + # number of elements in `size_g` groups + # of `size_j` columns + size_gj = size_g * size_j + # index of the group in which (i,j) is + group_id = ij // size_gj + # row-index of the first element of this group + off_i = group_id * size_g + # last group may have fewer rows + size_g = core.minimum(size_i - off_i, size_g) + # linear index with respect to the first element in this group + ij = ij % size_gj + # new row and column indices + new_i = off_i + ij % size_g + new_j = ij // size_g + return new_i, new_j + + +@jit +def zeros(shape, dtype): + """ + Returns a tensor filled with the scalar value 0 for the given :code:`shape` and :code:`dtype`. + + :param shape: Shape of the new array, e.g., (8, 16) or (8, ) + :type shape: tuple of ints + :param dtype: Data-type of the new array, e.g., :code:`tl.float16` + :type dtype: DType + """ + return core.full(shape, 0, dtype) + + +@jit +def zeros_like(input): + """ + Returns a tensor of zeros with the same shape and type as a given tensor. + + :param input: input tensor + :type input: Tensor + """ + return zeros(input.shape, input.dtype) + + +# max and argmax + + +@jit +def _argmax_combine(value1, index1, value2, index2, tie_break_left): + if tie_break_left: + tie = value1 == value2 and index1 < index2 + else: + tie = False + gt = value1 > value2 or tie + v_ret = core.where(gt, value1, value2) + i_ret = core.where(gt, index1, index2) + return v_ret, i_ret + + +@jit +def _argmax_combine_tie_break_left(value1, index1, value2, index2): + return _argmax_combine(value1, index1, value2, index2, True) + + +@jit +def _argmax_combine_tie_break_fast(value1, index1, value2, index2): + return _argmax_combine(value1, index1, value2, index2, False) + + +@jit +def _elementwise_max(a, b): + return core.maximum(a, b) + + +@core._tensor_member_fn +@jit +@core._add_reduction_docstr("maximum", return_indices_arg="return_indices", + tie_break_arg="return_indices_tie_break_left") +def max(input, axis=None, return_indices=False, return_indices_tie_break_left=True, keep_dims=False): + input = core._promote_bfloat16_to_float32(input) + if return_indices: + if return_indices_tie_break_left: + return core._reduce_with_indices(input, axis, _argmax_combine_tie_break_left, keep_dims=keep_dims) + else: + return core._reduce_with_indices(input, axis, _argmax_combine_tie_break_fast, keep_dims=keep_dims) + else: + if core.constexpr(input.dtype.primitive_bitwidth) < core.constexpr(32): + if core.constexpr(input.dtype.is_floating()): + input = input.to(core.float32) + else: + assert input.dtype.is_int(), "Expecting input to be integer type" + input = input.to(core.int32) + return core.reduce(input, axis, _elementwise_max, keep_dims=keep_dims) + + +@core._tensor_member_fn +@jit +@core._add_reduction_docstr("maximum index", tie_break_arg="tie_break_left") +def argmax(input, axis, tie_break_left=True, keep_dims=False): + (_, ret) = max(input, axis, return_indices=True, return_indices_tie_break_left=tie_break_left, keep_dims=keep_dims) + return ret + + +# min and argmin + + +@jit +def _argmin_combine(value1, index1, value2, index2, tie_break_left): + if tie_break_left: + tie = value1 == value2 and index1 < index2 + else: + tie = False + lt = value1 < value2 or tie + value_ret = core.where(lt, value1, value2) + index_ret = core.where(lt, index1, index2) + return value_ret, index_ret + + +@jit +def _argmin_combine_tie_break_left(value1, index1, value2, index2): + return _argmin_combine(value1, index1, value2, index2, True) + + +@jit +def _argmin_combine_tie_break_fast(value1, index1, value2, index2): + return _argmin_combine(value1, index1, value2, index2, False) + + +@jit +def _elementwise_min(a, b): + return core.minimum(a, b) + + +@core._tensor_member_fn +@jit +@core._add_reduction_docstr("minimum", return_indices_arg="return_indices", + tie_break_arg="return_indices_tie_break_left") +def min(input, axis=None, return_indices=False, return_indices_tie_break_left=True, keep_dims=False): + input = core._promote_bfloat16_to_float32(input) + if return_indices: + if return_indices_tie_break_left: + return core._reduce_with_indices(input, axis, _argmin_combine_tie_break_left, keep_dims=keep_dims) + else: + return core._reduce_with_indices(input, axis, _argmin_combine_tie_break_fast, keep_dims=keep_dims) + else: + if core.constexpr(input.dtype.primitive_bitwidth) < 32: + if core.constexpr(input.dtype.is_floating()): + input = input.to(core.float32) + else: + assert input.dtype.is_int(), "Expecting input to be integer type" + input = input.to(core.int32) + return core.reduce(input, axis, _elementwise_min, keep_dims=keep_dims) + + +@core._tensor_member_fn +@jit +@core._add_reduction_docstr("minimum index", tie_break_arg="tie_break_left") +def argmin(input, axis, tie_break_left=True, keep_dims=False): + _, ret = min(input, axis, return_indices=True, return_indices_tie_break_left=tie_break_left, keep_dims=keep_dims) + return ret + + +@jit +def _sum_combine(a, b): + return a + b + + +# sum + + +@constexpr_function +def _pick_sum_dtype(in_dtype, dtype): + if dtype is not None: + return dtype + + # For integer bitwidths less than 32, pick int32 with the same sign to + # avoid overflow. + out_dtype = None + if in_dtype.is_int_signed(): + out_dtype = core.int32 if in_dtype.int_bitwidth < 32 else None + elif in_dtype.is_int_unsigned(): + out_dtype = core.uint32 if in_dtype.int_bitwidth < 32 else None + return out_dtype + + +@core._tensor_member_fn +@jit +@core._add_reduction_docstr("sum", dtype_arg="dtype") +def sum(input, axis=None, keep_dims=False, dtype: core.constexpr = None): + # Pick a default dtype for the reduction if one was not specified. + out_dtype: core.constexpr = _pick_sum_dtype(input.dtype, dtype) + + if out_dtype is not None: + input = input.to(out_dtype) + return core.reduce(input, axis, _sum_combine, keep_dims=keep_dims) + + +@jit +def _xor_combine(a, b): + return a ^ b + + +# xor sum + + +@core._tensor_member_fn +@jit +@core._add_reduction_docstr("xor sum") +def xor_sum(input, axis=None, keep_dims=False): + core.static_assert(input.type.scalar.is_int(), "xor_sum only supported for integers") + return core.reduce(input, axis, _xor_combine, keep_dims=keep_dims) + + +# or reduction + + +@jit +def _or_combine(x, y): + return x | y + + +@core._tensor_member_fn +@jit +@core._add_reduction_docstr("reduce_or") +def reduce_or(input, axis, keep_dims=False): + core.static_assert(input.type.scalar.is_int(), "reduce_or only supported for integers") + return core.reduce(input, axis, _or_combine, keep_dims=keep_dims) + + +# cumsum + + +@core._tensor_member_fn +@jit +@core._add_scan_docstr("cumsum", dtype_arg="dtype") +def cumsum(input, axis=0, reverse=False, dtype: core.constexpr = None): + # todo rename this to a generic function name + + input = core._promote_bfloat16_to_float32(input) + out_dtype: core.constexpr = _pick_sum_dtype(input.dtype, dtype) + + if out_dtype is not None: + input = input.to(out_dtype) + + return core.associative_scan(input, axis, _sum_combine, reverse) + + +# cumprod + + +@jit +def _prod_combine(a, b): + return a * b + + +@core._tensor_member_fn +@jit +@core._add_scan_docstr("cumprod") +def cumprod(input, axis=0, reverse=False): + # todo rename this to a generic function name + input = core._promote_bfloat16_to_float32(input) + return core.associative_scan(input, axis, _prod_combine, reverse) + + +# sort + + +@jit +def _indicator(n_dims: core.constexpr, j: core.constexpr): + ar = core.arange(0, 2) + ar = core.reshape(ar, [1] * (n_dims - j - 1) + [2] + [1] * j) + return ar + + +@jit +def _compare_and_swap(x, flip, i: core.constexpr): + # compare-and-swap on the ith *innermost* dimension + n_dims: core.constexpr = _log2(x.numel) + + # flip along middle dimension (the bitwise XORs will be optimised away): + idtype = core.get_int_dtype(bitwidth=x.dtype.primitive_bitwidth, signed=True) + ix = x.to(idtype, bitcast=True) + iy = ix ^ xor_sum(ix, n_dims - 1 - i, True) + y = iy.to(x.dtype, bitcast=True) + + # determines whether we are in the right (rather than left) position along the axis: + is_right = _indicator(n_dims, i) + + # conditional swap: + ret = core.where((x > y) != (flip ^ is_right), y, x) + return ret + + +@jit +def _bitonic_merge_hypercube(x, stage: core.constexpr, order: core.constexpr): + ''' + order_type 0 == ascending + order_type 1 == descending + order_type 2 == alternating + ''' + # flip denotes whether to re-arrange sub-sequences of elements in ascending or + # descending order. + # if flip = 00000000... then all elements will be re-arranged ascendingly at this stage + # if flip = 00110011... then all the elements will be re-arranged alternatingly (with + # a stride of 2) at this stage + if order == 2: + flip = _indicator(_log2(x.numel), stage) + else: + flip = order + # perform `stage` rounds of `compare-and-swap` + for i in core.static_range(stage): + x = _compare_and_swap(x, flip, stage - 1 - i) + return x + + +@jit +def _bitonic_merge(x, stage: core.constexpr, order: core.constexpr, n_dims: core.constexpr): + h = core.reshape(x, [2] * _log2(x.numel)) + h = _bitonic_merge_hypercube(h, stage, order) + x = core.reshape(h, x.shape) + return x + + +@jit +def sort_impl(x, k: core.constexpr = None, dim: core.constexpr = None, descending: core.constexpr = core.CONSTEXPR_0): + """ + Sorts a tensor along a specified dimension. + + :param x: The input tensor to be sorted. + :type x: Tensor + :param dim: The dimension along which to sort the tensor. If None, the tensor is sorted along the last dimension. Currently, only sorting along the last dimension is supported. + :type dim: int, optional + :param k: the number of top elements to select. If none, assume k = x.shape[dim] + :type k: int, optional + :param descending: If set to True, the tensor is sorted in descending order. If set to False, the tensor is sorted in ascending order. + :type descending: bool, optional + """ + # handle default dimension or check that it is the most minor dim + _dim: core.constexpr = len(x.shape) - 1 if dim is None else dim + core.static_assert(_dim == len(x.shape) - 1, "only minor dimension is currently supported") + + log_n: core.constexpr = _log2(x.shape[_dim]) + log_k: core.constexpr = log_n if k is None else _log2(k) + + n_dims: core.constexpr = _log2(x.numel) + + # reshape to hypercube: + h = core.reshape(x, [2] * n_dims) + + # run first log_k bitonic sort iterations: + for i in core.static_range(1, log_k + 1): + h = _bitonic_merge_hypercube(h, i, 2 if i < log_n else descending) + + # select top k elements using bitonic top-k + # https://www.doc.ic.ac.uk/~hlgr/pdfs/MassivelyParallelTopK.pdf + for i in core.static_range(log_k + 1, log_n + 1): + h = max(h, axis=(_log2(h.numel) - 1 - log_k)) if descending else min(h, axis=(_log2(h.numel) - 1 - log_k)) + h = _bitonic_merge_hypercube(h, log_k, 2 if i < log_n else descending) + + # reshape back: + x = core.reshape(h, x.shape[:-1] + [2**log_k]) + return x + + +@jit +def sort(x, dim: core.constexpr = None, descending: core.constexpr = core.CONSTEXPR_0): + return sort_impl(x, dim=dim, descending=descending) + + +@jit +def topk(x, k: core.constexpr, dim: core.constexpr = None): + return sort_impl(x, k=k, dim=dim, descending=True) + + +@jit +def bitonic_merge(x, dim: core.constexpr = None, descending: core.constexpr = core.CONSTEXPR_0): + # handle default dimension or check that it is the most minor dim + _dim: core.constexpr = len(x.shape) - 1 if dim is None else dim + core.static_assert(_dim == len(x.shape) - 1, "only minor dimension is currently supported") + n_dims: core.constexpr = _log2(x.shape[-1]) + return _bitonic_merge(x, n_dims, descending, n_dims) + + +@constexpr_function +def _get_flip_dim(dim, shape): + if dim is None: + dim = len(shape) - 1 + if dim < 0: # flip doesn't work if dim < 0 because the xor-swap for loop will start/end at the wrong index + dim += len(shape) + return dim + + +@core._tensor_member_fn +@jit +def flip(x, dim=None): + """ + Flips a tensor `x` along the dimension `dim`. + + :param x: the first input tensor + :type x: Block + :param dim: the dimension to flip along + :type dim: int + """ + core.static_assert(-len(x.shape) <= dim and dim < len(x.shape)) + _dim: core.constexpr = _get_flip_dim(dim, x.shape) + core.static_assert(_is_power_of_two(x.shape[_dim])) + steps: core.constexpr = _log2(x.shape[_dim]) + + # reshape the swap dimension to (2, 2, ..., 2) + idtype = core.get_int_dtype(bitwidth=x.dtype.primitive_bitwidth, signed=True) + y = core.reshape(x.to(idtype, bitcast=True), x.shape[:_dim] + [2] * steps + x.shape[_dim + 1:]) + for i in core.static_range(steps): + y = y ^ xor_sum(y, _dim + i, True) + x = core.reshape(y, x.shape).to(x.dtype, bitcast=True) + return x + + +@jit +def interleave(a, b): + """ + Interleaves the values of two tensors along their last dimension. The two tensors must have the same shape. + Equivalent to `tl.join(a, b).reshape(a.shape[:-1] + [2 * a.shape[-1]])` + + :param a: The first input tensor. + :type a: Tensor + :param b: The second input tensor. + :type b: Tensor + """ + c = core.join(a, b) + + if len(c.shape) == 1: + # We must have interleaved two scalars. + return c + else: + # This `else` is necessary because Triton's AST parser doesn't + # understand that if we take the `if` above we definitely don't run this + # `else`. + return core.reshape(c, c.shape[:-2] + [2 * c.shape[-2]]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/target_info.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/target_info.py new file mode 100644 index 0000000000000000000000000000000000000000..2c1a277f04d5dd79bf506a49f8aa8d2f0e6d8e90 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/language/target_info.py @@ -0,0 +1,54 @@ +from triton.runtime import driver +from triton.runtime.jit import constexpr_function + +__all__ = ["current_target"] + + +def current_target(): + try: + active_driver = driver.active + except RuntimeError: + # If there is no active driver, return None + return None + return active_driver.get_current_target() + + +current_target.__triton_builtin__ = True + + +@constexpr_function +def is_cuda(): + target = current_target() + return target is not None and target.backend == "cuda" + + +@constexpr_function +def cuda_capability_geq(major, minor=0): + """ + Determines whether we have compute capability >= (major, minor) and + returns this as a constexpr boolean. This can be used for guarding + inline asm implementations that require a certain compute capability. + """ + target = current_target() + if target is None or target.backend != "cuda": + return False + assert isinstance(target.arch, int) + return target.arch >= major * 10 + minor + + +@constexpr_function +def is_hip(): + target = current_target() + return target is not None and target.backend == "hip" + + +@constexpr_function +def is_hip_cdna3(): + target = current_target() + return target is not None and target.arch == "gfx942" + + +@constexpr_function +def is_hip_cdna4(): + target = current_target() + return target is not None and target.arch == "gfx950" diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..efbd85819526b7556809c6927a02512835c830d7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/__init__.py @@ -0,0 +1,12 @@ +# ruff: noqa +from .scope import scope, cpu_timed_scope, enter_scope, exit_scope +from .state import state, enter_state, exit_state +from .profile import ( + start, + activate, + deactivate, + finalize, + profile, + DEFAULT_PROFILE_NAME, +) +from . import context, specs, mode diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/context.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/context.py new file mode 100644 index 0000000000000000000000000000000000000000..7f457a1a5a4e8f6f070ba887d0f21a5ba0b6aeb1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/context.py @@ -0,0 +1,18 @@ +from typing import Optional +from triton._C.libproton import proton as libproton +from .flags import get_profiling_on + + +def depth(session: Optional[int] = 0) -> Optional[int]: + """ + Get the depth of the context. + + Args: + session (int): The session ID of the profiling session. Defaults to 0. + + Returns: + depth (int or None): The depth of the context. If profiling is off, returns None. + """ + if not get_profiling_on(): + return None + return libproton.get_context_depth(session) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/flags.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/flags.py new file mode 100644 index 0000000000000000000000000000000000000000..20687cc65e2acfa0551573ecdab6329411e3daac --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/flags.py @@ -0,0 +1,49 @@ +""" +This file contains the global flags used in the proton package. +""" + +# Whether to enable profiling. Default is False. +profiling_on = False +# Whether instrumentation is enabled. Default is False. +instrumentation_on = False +# Whether the script is run from the command line. Default is False. +command_line = False + + +def set_profiling_on(): + global profiling_on + profiling_on = True + + +def set_profiling_off(): + global profiling_on + profiling_on = False + + +def get_profiling_on(): + global profiling_on + return profiling_on + + +def set_command_line(): + global command_line + command_line = True + + +def is_command_line(): + global command_line + return command_line + + +def get_instrumentation_on(): + return instrumentation_on + + +def set_instrumentation_on(): + global instrumentation_on + instrumentation_on = True + + +def set_instrumentation_off(): + global instrumentation_on + instrumentation_on = False diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/hooks/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/hooks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ba3ff539527cd54e488828e92db7c4f7aaed882 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/hooks/__init__.py @@ -0,0 +1,4 @@ +# ruff: noqa +from .hook import HookManager +from .instrumentation import InstrumentationHook +from .launch import LaunchHook diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/hooks/hook.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/hooks/hook.py new file mode 100644 index 0000000000000000000000000000000000000000..a672722a1279f68cf80d5fde3d0b654100611d7a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/hooks/hook.py @@ -0,0 +1,128 @@ +from triton.compiler import LazyDict +from abc import abstractmethod +from typing import Dict, Any, Optional +from collections import defaultdict +import triton.knobs as knobs + + +class Hook: + priority: int = 0 + + @abstractmethod + def init_handle(self, module: Any, function: Any, name: str, metadata_group: Dict[str, str], + hash: str) -> None: # noqa: D401 + raise NotImplementedError + + @abstractmethod + def enter(self, metadata: LazyDict) -> None: + raise NotImplementedError + + @abstractmethod + def exit(self, metadata: LazyDict) -> None: + raise NotImplementedError + + @abstractmethod + def activate(self) -> None: + raise NotImplementedError + + @abstractmethod + def deactivate(self) -> None: + raise NotImplementedError + + +class HookManager: + # active hooks + active_hooks: list[Hook] = [] + # session_id -> (hook_type -> active) + session_hooks: Dict[int, Dict[Hook, bool]] = defaultdict(lambda: defaultdict(bool)) + + @staticmethod + def init_handle(module: Any, function: Any, name: str, metadata_group: Dict[str, str], hash: str) -> None: + for hook in HookManager.active_hooks: + hook.init_handle(module, function, name, metadata_group, hash) + + @staticmethod + def enter(metadata: LazyDict) -> None: + for hook in HookManager.active_hooks: + hook.enter(metadata) + + @staticmethod + def exit(metadata: LazyDict) -> None: + # It's important to reverse the order of hooks so that we keep the first in last out order + for hook in reversed(HookManager.active_hooks): + hook.exit(metadata) + + @staticmethod + def activate(session: Optional[int] = None) -> None: + if session is None: + sessions = HookManager.session_hooks.keys() + else: + sessions = [session] + + for session in sessions: + for hook in HookManager.session_hooks[session]: + if hook not in HookManager.active_hooks: + hook.activate() + HookManager.active_hooks.append(hook) + HookManager.session_hooks[session][hook] = True + # Sort active_hooks by priority + HookManager.active_hooks.sort(key=lambda x: x.priority, reverse=True) + + @staticmethod + def deactivate(session: Optional[int] = None) -> None: + if session is None: + sessions = HookManager.session_hooks.keys() + else: + sessions = [session] + + deactivated_hooks = set() + for session in sessions: + for hook in HookManager.session_hooks[session]: + if hook in HookManager.active_hooks: + deactivated_hooks.add(hook) + HookManager.session_hooks[session][hook] = False + + # Check if any other sessions rely on this hook + for hook in deactivated_hooks: + if not any(session_hooks[hook] for session_hooks in HookManager.session_hooks.values()): + hook.deactivate() + HookManager.active_hooks.remove(hook) + + @staticmethod + def register(hook: Hook, session: int) -> None: + HookManager.session_hooks[session][hook] = True + if hook not in HookManager.active_hooks: + hook.activate() + HookManager.active_hooks.append(hook) + # Sort active_hooks by priority + HookManager.active_hooks.sort(key=lambda x: x.priority, reverse=True) + + # Register the heads + knobs.runtime.kernel_load_end_hook.add(HookManager.init_handle) + knobs.runtime.launch_enter_hook.add(HookManager.enter) + knobs.runtime.launch_exit_hook.add(HookManager.exit) + + @staticmethod + def unregister(session: Optional[int] = None) -> None: + if session is not None and session not in HookManager.session_hooks: + return + + if session is None: + for hook in HookManager.active_hooks: + hook.deactivate() + HookManager.active_hooks.clear() + HookManager.session_hooks.clear() + else: + popped_hooks = HookManager.session_hooks.pop(session) + # Deactivate hooks that are not used by any other session + for hook, active in popped_hooks.items(): + if not active: + continue + if not any(session_hooks[hook] for session_hooks in HookManager.session_hooks.values()): + hook.deactivate() + HookManager.active_hooks.remove(hook) + # Unregister the heads + if not HookManager.active_hooks: + knobs.runtime.kernel_load_end_hook.remove(HookManager.init_handle) + knobs.runtime.launch_enter_hook.remove(HookManager.enter) + knobs.runtime.launch_exit_hook.remove(HookManager.exit) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/hooks/instrumentation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/hooks/instrumentation.py new file mode 100644 index 0000000000000000000000000000000000000000..b00a24f4d6e85a89e675cdaebb79dfb07eba985f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/hooks/instrumentation.py @@ -0,0 +1,360 @@ +import functools +from typing import Dict, Optional, Union, Any + +import triton +from triton._C.libtriton import ir as triton_ir +from triton._C.libtriton import proton as triton_proton +from triton._C.libtriton import amd as triton_amd +from triton._C.libtriton import nvidia as triton_nvidia +from triton._C.libtriton import passes as triton_passes +from triton._C.libproton import proton as libproton +from triton.compiler import LazyDict +from triton.runtime.jit import JITFunction +from triton.runtime._allocation import set_profile_allocator, NullAllocator +from triton.backends import backends + +from .hook import Hook +from ..flags import set_instrumentation_on, set_instrumentation_off +from .. import mode + +# TODO(fywkevin): add support for major.minor +VERSION = 1 + + +class CudaAllocator: + + def __init__(self, instrumentation_hook): + self.instrumentation_hook = instrumentation_hook + + def __call__(self, size: int, alignment: int, stream: Optional[int]): + if alignment != self.instrumentation_hook.profile_buffer_alignment: + raise RuntimeError( + f"Alignment mismatch: {alignment} != {self.instrumentation_hook.profile_buffer_alignment}") + aligned_size = (size + alignment - 1) // alignment * alignment + # Note: profile_buffer_size may be smaller than the aligned size if the kernel launches many blocks + # and the host CPU cannot store all profiling data in memory. This streaming mode is not yet implemented. + # In the future, we should support copying data incrementally from device to host to enable + # more efficient profiling data processing, rather than relying solely on post-processing. + aligned_size = max(aligned_size, self.instrumentation_hook.profile_buffer_size) + + # Create the buffer + import torch + buffer = torch.empty((aligned_size, ), dtype=torch.uint8, device="cuda") + self.instrumentation_hook.buffer = buffer + return buffer + + +class Instrumentation: + + def __init__(self, ir_map: Dict[str, Any]): + self.manager = ir_map + + def register(self, ir: str, func): + if ir in self.manager: + raise RuntimeError(f"IR already registered: {ir}") + self.manager[ir] = func + + def patch(self, ir: str, pm, context): + self.load_dialects(context) + if ir in self.manager: + self.manager[ir](pm) + + def load_dialects(self, ctx): + triton_proton.load_dialects(ctx) + + +def _interpret_mode(mode_obj: Union[str, mode.InstrumentationMode]) -> mode.InstrumentationMode: + if isinstance(mode_obj, mode.InstrumentationMode): + return mode_obj + elif not mode_obj: + mode_obj = "default" + + parts = mode_obj.split(":") + mode_name = parts[0] + opts: Dict[str, str] = {} + for opt in parts[1:]: + if "=" in opt: + key, val = opt.split("=", 1) + opts[key] = val + else: + raise ValueError(f"Malformed instrumentation option: '{opt}'") + + # Get option values or empty strings + options = { + "metric_type": opts.get("metric_type", "cycle"), "buffer_type": opts.get("buffer_type", "shared"), + "buffer_strategy": opts.get("buffer_strategy", "circular"), "buffer_size": int(opts.get("buffer_size", "0")), + "granularity": opts.get("granularity", "warp"), "sampling_strategy": opts.get("sampling_strategy", "none"), + "sampling_options": opts.get("sampling_options", ""), "optimizations": opts.get("optimizations", "") + } + + # Helper function to validate and map options to their enum values + def get_option_value(opt_name, mapping): + value = options[opt_name] + if value and value not in mapping: + raise ValueError(f"Unknown {opt_name}: {value}") + return mapping[value] if value else value + + # Look up enum values for each option + options["metric_type"] = get_option_value("metric_type", mode.metric_types) + options["buffer_type"] = get_option_value("buffer_type", mode.buffer_types) + options["buffer_strategy"] = get_option_value("buffer_strategy", mode.buffer_strategies) + options["granularity"] = get_option_value("granularity", mode.granularities) + options["sampling_strategy"] = get_option_value("sampling_strategy", mode.sampling_strategies) + + values = ([value.strip() + for value in options["optimizations"].split(",")] if len(options["optimizations"]) > 0 else []) + for value in values: + if value not in mode.optimizations: + raise ValueError(f"Unknown optimization: {value}") + options["optimizations"] = [mode.optimizations[value] for value in values] + + # Create the appropriate mode instance + if mode_name == "default": + return mode.Default(**options) + elif mode_name == "mma": + return mode.MMA(**options) + else: + raise ValueError(f"Unknown mode: {mode_obj}") + + +def _get_backend_name() -> str: + backend = triton.runtime.driver.active.get_current_target().backend + if backend == "cuda": + return "nvidia" + elif backend == "hip": + return "amd" + else: + raise RuntimeError(f"Unsupported backend: {backend}") + + +class InstrumentationHook(Hook): + priority: int = 0 + # It's important to note that only one instance of the instrumentation hook can be active at a time. + active_count: int = 0 + enable_host_buffer: bool = False + host_buffer: Optional[Any] = None + # FIXME(fywkevin): change to a more reasonable value after we have support for periodic buffer dumping. + profile_buffer_size: int = 1 + profile_buffer_alignment: int = 128 + + def __init__(self, mode_obj: Union[None, str, mode.InstrumentationMode]): + # Mapping of function objects to their scope ID pairs + self.mode: mode.InstrumentationMode = _interpret_mode(mode_obj) + + self.allocator = CudaAllocator(self) + self.buffer = None + self.metadata_path: Dict[Any, Optional[str]] = {} + + def activate(self): + if InstrumentationHook.active_count > 0: + raise RuntimeError("Only one instance of the instrumentation hook can be active at a time.") + + InstrumentationHook.active_count += 1 + + set_instrumentation_on() + + device = triton.runtime.driver.active.get_current_device() + max_shared_mem = triton.runtime.driver.active.utils.get_device_properties(device)["max_shared_mem"] + backend_name = _get_backend_name() + + def to_llvmir_passes(pm): + is_long_clk = False if mode.Optimize.CLOCK32 in self.mode.optimizations else True + triton_proton.add_convert_proton_to_protongpu(pm, self.mode.metric_type, self.mode.sampling_strategy, + self.mode.sampling_options, self.mode.granularity, + self.mode.buffer_strategy, self.mode.buffer_type, + self.mode.buffer_size, max_shared_mem, + self.profile_buffer_size, self.profile_buffer_alignment, + is_long_clk) + triton_passes.common.add_cse(pm) + + if mode.Optimize.SCHED_STORES in self.mode.optimizations: + triton_proton.add_schedule_buffer_store(pm) + + triton_proton.add_allocate_proton_shared_memory(pm) + + if mode.Optimize.SCHED_BARRIERS in self.mode.optimizations and backend_name == "amd": + triton_proton.add_sched_barriers(pm) + + def to_llvm_passes(pm): + triton_proton.add_allocate_proton_global_scratch_buffer(pm) + if backend_name == "nvidia": + triton_proton.add_convert_proton_nvidia_gpu_to_llvm(pm) + elif backend_name == "amd": + arch = triton.runtime.driver.active.utils.get_device_properties(device)["arch"].split(":")[0] + triton_proton.add_convert_proton_amd_gpu_to_llvm(pm, arch) + + backends[backend_name].compiler.instrumentation = Instrumentation({ + "ttgpuir_to_llvmir": + lambda pm: to_llvmir_passes(pm), + "llvmir_to_llvm": + lambda pm: to_llvm_passes(pm), + }) + + # Set up the profiling allocator + set_profile_allocator(self.allocator) + + original_run = JITFunction.run + + original_mode = self.mode + + @functools.wraps(original_run) + def instrumented_run(self, *args, **kwargs): + kwargs["instrumentation_mode"] = str(original_mode) + return original_run(self, *args, **kwargs) + + JITFunction.run = instrumented_run + + def deactivate(self): + if InstrumentationHook.active_count == 0: + return + + InstrumentationHook.active_count -= 1 + + backend_name = _get_backend_name() + + # No instrumentation passes are registered anymore + backends[backend_name].compiler.instrumentation = {} + + # No runtime instrumentation hook is active anymore + set_instrumentation_off() + + # Restore original JIT function run method + if hasattr(JITFunction.run, "__wrapped__"): + JITFunction.run = JITFunction.run.__wrapped__ + + # Reset profile allocator + set_profile_allocator(NullAllocator()) + + # Reset host memory for external processing + if InstrumentationHook.enable_host_buffer: + InstrumentationHook.host_buffer = None + + # Reset the buffer reference + self.buffer = None + + def init_handle(self, module: Any, function: Any, name: str, metadata_group: Dict[str, str], hash: str) -> None: + if not function: + return + + # Find the IR path in metadata + ir_path = next((path for key, path in metadata_group.items() if key.endswith(("ttgir"))), None) + metadata_path = next((path for key, path in metadata_group.items() if key.endswith(("json"))), None) + self.metadata_path[function] = metadata_path + + if ir_path: + context = triton_ir.context() + triton_ir.load_dialects(context) + backend_name = _get_backend_name() + if backend_name == "nvidia": + triton_nvidia.load_dialects(context) + elif backend_name == "amd": + triton_amd.load_dialects(context) + triton_proton.load_dialects(context) + module = triton_ir.parse_mlir_module(ir_path, context) + module.context = context + + scope_id_names = triton_proton.get_scope_id_names(module) + scope_id_parents = triton_proton.get_scope_id_parents(module) + libproton.init_function_metadata(function, name, scope_id_names, scope_id_parents, metadata_path) + else: + raise RuntimeError(f"IR path not found in metadata for function {function}") + + def _data_ptr(self) -> int: + return 0 if self.buffer is None else self.buffer.data_ptr() + + def enter(self, metadata: LazyDict) -> None: + func = metadata.data.get("function") + stream = metadata.data.get("stream") + alloc_size = 0 if self.buffer is None else self.buffer.element_size() * self.buffer.numel() + libproton.enter_instrumented_op(stream, func, self._data_ptr(), alloc_size) + if InstrumentationHook.enable_host_buffer: + InstrumentationHook.host_buffer = None + + def exit(self, metadata: LazyDict) -> None: + func = metadata.data.get("function") + stream = metadata.data.get("stream") + alloc_size = 0 if self.buffer is None else self.buffer.element_size() * self.buffer.numel() + libproton.exit_instrumented_op(stream, func, self._data_ptr(), alloc_size) + + if InstrumentationHook.enable_host_buffer: + self._populate_host_buffer(func) + + def _populate_host_buffer(self, function: Any) -> None: + if function and self.metadata_path[function]: + import torch + import struct + import json + + def encode_target(target: Dict[str, Any]) -> int: + #TODO(fywkevin): also account for `arch` + if target["backend"] == "cuda": + return 1 + elif target["backend"] == "hip": + return 2 + return 0 + + alloc_size = 0 if self.buffer is None else self.buffer.element_size() * self.buffer.numel() + sampled_warps = self.mode.sampling_options.strip().split(",") + data = {} + with open(self.metadata_path[function], 'r') as file: + data = json.load(file) + + device_type = encode_target(data["target"]) + scratch_mem_size = data["profile_scratch_size"] + total_unit = data["num_warps"] + uid_num = total_unit if self.mode.sampling_strategy == triton_proton.SAMPLING_STRATEGY.NONE else len( + sampled_warps) + block_num = int(alloc_size / scratch_mem_size) + + # Binary trace layout: + # +------------------+ + # | version | 4 bytes + # +------------------+ + # | header_offset | 4 bytes + # +------------------+ + # | header_size | 4 bytes + # +------------------+ + # | payload_offset | 4 bytes + # +------------------+ + # | payload_size | 4 bytes + # +------------------+ + # | device_type | 4 bytes + # +------------------+ + # | block_num | 4 bytes + # +------------------+ + # | total_unit | 4 bytes + # +------------------+ + # | scratch_mem_size | 4 bytes + # +------------------+ + # | uid_num | 4 bytes + # +------------------+ + # | | + # | uid_vec | uid_num * 4 bytes + # | | + # +------------------+ + # | | + # | payload | size_payload bytes + # | | + # +------------------+ + + is_all_warps = self.mode.sampling_options == "" and self.mode.granularity == triton_proton.GRANULARITY.WARP + if is_all_warps: + uid_vec = [i for i in range(total_unit)] + else: + uid_vec = [int(i) for i in sampled_warps] + + header_size = 40 + uid_num * 4 + header_offset = 4 + payload_offset = header_size + payload_size = alloc_size + header_values = [ + VERSION, header_offset, header_size, payload_offset, payload_size, device_type, block_num, total_unit, + scratch_mem_size, uid_num, *uid_vec + ] + header_bytes = struct.pack("I" * len(header_values), *header_values) + + InstrumentationHook.host_buffer = torch.empty(header_size + alloc_size, dtype=torch.uint8, device="cpu") + config_portion = InstrumentationHook.host_buffer[:header_size] + config_portion.copy_(torch.tensor(list(header_bytes), dtype=torch.uint8)) + data_portion = InstrumentationHook.host_buffer[header_size:].view_as(self.buffer) + data_portion.copy_(self.buffer.cpu()) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/hooks/launch.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/hooks/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..0243c8b67f1adf07b409e11e18a66775f601f1b6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/hooks/launch.py @@ -0,0 +1,49 @@ +from ..state import enter_state, exit_state +from triton.compiler import LazyDict +from .hook import Hook +from triton._C.libproton import proton as libproton +from contextvars import ContextVar + +COMPUTE_METADATA_SCOPE_NAME = "__proton_launch_metadata" + +op_name = ContextVar("op_name", default=None) +id = ContextVar("id", default=None) + + +class LaunchHook(Hook): + # Highest priority + priority = 100 + # This is a singleton class + _instance = None + flops_width = [8, 16, 32, 64] + metrics = [f"flops{width}" for width in flops_width] + ["bytes"] + ["flops"] + + def __init__(self): + pass + + def __new__(cls): + if cls._instance is None: + cls._instance = super(LaunchHook, cls).__new__(cls) + return cls._instance + + def init_handle(self, module, function, name: str, metadata_group: dict, hash: str) -> None: + pass + + def activate(self): + pass + + def deactivate(self): + pass + + def enter(self, metadata: LazyDict) -> None: + enter_state(COMPUTE_METADATA_SCOPE_NAME) + lazy_metadata = metadata.get() + exit_state() + fn_metrics = {k: lazy_metadata[k] for k in LaunchHook.metrics if k in lazy_metadata} + op_name.set(lazy_metadata["name"]) + id.set(libproton.record_scope()) + libproton.enter_op(id.get(), lazy_metadata["name"]) + libproton.add_metrics(id.get(), fn_metrics) + + def exit(self, metadata: LazyDict) -> None: + libproton.exit_op(id.get(), op_name.get()) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/language.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/language.py new file mode 100644 index 0000000000000000000000000000000000000000..f2e345fa203e12206aa0391037dd0273bf6e03f4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/language.py @@ -0,0 +1,66 @@ +from triton.language import core as tl +from triton.language.core import builtin +from triton._C.libtriton import proton as triton_proton +from triton.language.semantic import TritonSemantic +from triton.experimental.gluon.language._semantic import GluonSemantic + +from .flags import get_instrumentation_on + +_ALL_SEMANTICS = { + "triton": TritonSemantic, + "gluon": GluonSemantic, +} +""" +By default **only Gluon** semantic is enabled. +Instrumenting kernels written in Triton DSL is disable because Triton's higher-level IR undergoes +aggressive compiler rewrites (loop pipelining, instruction re-ordering, IR duplication, etc.). +These transformations can invalidate naïve instrumentation and lead to misleading results. +""" +_SEMANTICS = {_ALL_SEMANTICS["gluon"]} + + +def _check_supported_semantic(semantic): + if not isinstance(semantic, tuple(_SEMANTICS)): + raise TypeError(f"Unsupported semantic type: {type(semantic)}. " + f"Supported semantics are: {_SEMANTICS}") + + +def enable_semantic(semantic_name: str): + _SEMANTICS.add(_ALL_SEMANTICS[semantic_name]) + + +def disable_semantic(semantic_name: str): + _SEMANTICS.remove(_ALL_SEMANTICS[semantic_name]) + + +def record(is_start: tl.constexpr, scope_name: tl.constexpr, semantic): + if not get_instrumentation_on(): + return + _check_supported_semantic(semantic) + is_start = tl._unwrap_if_constexpr(is_start) + scope_name = tl._unwrap_if_constexpr(scope_name) + op_builder = semantic.builder.get_op_builder() + return tl.tensor(triton_proton.create_proton_record(op_builder, is_start, scope_name), tl.void) + + +@builtin +def enter_scope(name: tl.constexpr, _semantic=None): + record(is_start=True, scope_name=name, semantic=_semantic) + + +@builtin +def exit_scope(name: tl.constexpr, _semantic=None): + record(is_start=False, scope_name=name, semantic=_semantic) + + +class scope: + + def __init__(self, name: str, _semantic=None): + self.name = name + self.semantic = _semantic + + def __enter__(self): + enter_scope(self.name, _semantic=self.semantic) + + def __exit__(self, exc_type, exc_value, traceback): + exit_scope(self.name, _semantic=self.semantic) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/mode.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/mode.py new file mode 100644 index 0000000000000000000000000000000000000000..ff41d58872f906ed2a9895c47bbe4514fad32ee6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/mode.py @@ -0,0 +1,123 @@ +from dataclasses import dataclass, field +from triton._C.libtriton import proton as triton_proton +from typing import List +from enum import Enum + +metric_types = {"cycle": triton_proton.METRIC_TYPE.CYCLE} + +buffer_strategies = { + "circular": triton_proton.BUFFER_STRATEGY.CIRCULAR, + "flush": triton_proton.BUFFER_STRATEGY.FLUSH, +} + +buffer_types = { + "shared": triton_proton.BUFFER_TYPE.SHARED, + "global": triton_proton.BUFFER_TYPE.GLOBAL, +} + +sampling_strategies = { + "none": triton_proton.SAMPLING_STRATEGY.NONE, + "selective": triton_proton.SAMPLING_STRATEGY.SELECTIVE, +} + +granularities = { + "cta": triton_proton.GRANULARITY.CTA, + "warp": triton_proton.GRANULARITY.WARP, + "warp_2": triton_proton.GRANULARITY.WARP_2, + "warp_4": triton_proton.GRANULARITY.WARP_4, + "warp_8": triton_proton.GRANULARITY.WARP_8, + "warp_group": triton_proton.GRANULARITY.WARP_GROUP, + "warp_group_2": triton_proton.GRANULARITY.WARP_GROUP_2, + "warp_group_4": triton_proton.GRANULARITY.WARP_GROUP_4, + "warp_group_8": triton_proton.GRANULARITY.WARP_GROUP_8, +} + + +class Optimize(Enum): + TIMESHIFT = "time_shift" + SCHED_STORES = "sched_stores" + SCHED_BARRIERS = "sched_barriers" + CLOCK32 = "clock32" + + def __str__(self): + return self.value + + +optimizations = { + "time_shift": Optimize.TIMESHIFT, + "sched_stores": Optimize.SCHED_STORES, + "sched_barriers": Optimize.SCHED_BARRIERS, + "clock32": Optimize.CLOCK32, +} + + +@dataclass(frozen=True) +class BaseMode: + name: str + + +@dataclass(frozen=True) +class PCSampling(BaseMode): + name: str = field(default="pcsampling", init=False) + interval: int = 1000 + + def __post_init__(self): + if self.interval <= 0: + raise ValueError("Interval must be a positive integer.") + + def __str__(self): + return f"{self.name}:interval={self.interval}" + + +@dataclass(frozen=True) +class InstrumentationMode(BaseMode): + """Common base class for instrumentation modes with shared configuration.""" + metric_type: triton_proton.METRIC_TYPE = triton_proton.METRIC_TYPE.CYCLE + sampling_strategy: triton_proton.SAMPLING_STRATEGY = triton_proton.SAMPLING_STRATEGY.NONE + sampling_options: str = "" + granularity: triton_proton.GRANULARITY = triton_proton.GRANULARITY.WARP + buffer_strategy: triton_proton.BUFFER_STRATEGY = triton_proton.BUFFER_STRATEGY.CIRCULAR + buffer_type: triton_proton.BUFFER_TYPE = triton_proton.BUFFER_TYPE.SHARED + buffer_size: int = 0 + optimizations: List[Optimize] = field(default_factory=list) + + def __post_init__(self): + # automatically map string inputs to enums using the global lookup dicts + mappings = [ + ("metric_type", metric_types), + ("sampling_strategy", sampling_strategies), + ("granularity", granularities), + ("buffer_strategy", buffer_strategies), + ("buffer_type", buffer_types), + ] + for field_name, lookup in mappings: + value = getattr(self, field_name) + if isinstance(value, str): + if value not in lookup: + raise ValueError(f"Unknown {field_name}: {value}") + object.__setattr__(self, field_name, lookup[value]) + + values_str = getattr(self, "optimizations") + if isinstance(values_str, str): + values = [value.strip() for value in values_str.split(",")] if len(values_str) > 0 else [] + for value in values: + if value not in optimizations: + raise ValueError(f"Unknown optimization: {value}") + object.__setattr__(self, "optimizations", [optimizations[value] for value in values]) + + def __str__(self): + optimizations_str = ",".join([str(opt) for opt in self.optimizations]) + return (f"{self.name}:metric_type={self.metric_type}:sampling_strategy={self.sampling_strategy}" + f":sampling_options={self.sampling_options}:granularity={self.granularity}" + f":buffer_strategy={self.buffer_strategy}:buffer_type={self.buffer_type}" + f":buffer_size={self.buffer_size}:optimizations={optimizations_str}") + + +@dataclass(frozen=True) +class Default(InstrumentationMode): + name: str = field(default="default", init=False) + + +@dataclass(frozen=True) +class MMA(InstrumentationMode): + name: str = field(default="mma", init=False) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/profile.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/profile.py new file mode 100644 index 0000000000000000000000000000000000000000..ccdf11836cc4e3e9f332ea03eb08dbff391549f8 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/profile.py @@ -0,0 +1,258 @@ +import functools +import triton +import os +import pathlib + +from triton import knobs +from triton._C.libproton import proton as libproton +from .flags import set_profiling_off, set_profiling_on, is_command_line +from .hooks import HookManager, LaunchHook, InstrumentationHook +from .mode import BaseMode +from typing import Optional, Union + +DEFAULT_PROFILE_NAME = "proton" + + +def _select_backend() -> str: + backend = triton.runtime.driver.active.get_current_target().backend + if backend == "cuda": + return "cupti" + elif backend == "hip": + return "roctracer" + else: + raise ValueError("No backend is available for the current target.") + + +def _get_backend_default_path(backend: str) -> str: + lib_path = "" + if backend == "cupti": + # First try to get the path from the environment variable that overrides the default path + lib_path = knobs.proton.cupti_dir + if lib_path is None: + # Get the default path for the cupti backend, + # which is the most compatible with the current CUPTI header file triton is compiled with + lib_path = str(pathlib.Path(__file__).parent.parent.absolute() / "backends" / "nvidia" / "lib" / "cupti") + return lib_path + + +def _get_mode_str(backend: str, mode: Optional[Union[str, BaseMode]]) -> str: + if backend == "instrumentation": + prefix = triton.runtime.driver.active.get_current_target().backend + return f"{prefix}:{mode}" if mode else prefix + return str(mode) if mode else "" + + +def _check_env(backend: str) -> None: + if backend == "roctracer": + hip_device_envs = ["HIP_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"] + for env in hip_device_envs: + if os.getenv(env, None) is not None: + raise ValueError( + f"Proton does not work when the environment variable {env} is set on AMD GPUs. Please unset it and use `ROCR_VISIBLE_DEVICES` instead" + ) + + +def start( + name: Optional[str] = None, + *, + context: Optional[str] = "shadow", + data: Optional[str] = "tree", + backend: Optional[str] = None, + mode: Optional[Union[str, BaseMode]] = None, + hook: Optional[str] = None, +): + """ + Start profiling with the given name and backend. + + Usage: + + ```python + proton.start("my_profile") + # do something + proton.finalize() + ``` + + Args: + name (str, optional): The name (with path) of the profiling session. + If not provided, the default name is "~/proton.", where suffix is the default + format according to the data type. For example, if data is "tree", the default name is "~/proton.hatchet". + context (str, optional): The context to use for profiling. + Available options are ["shadow", "python"]. + Defaults to "shadow". + data (str, optional): The data structure to use for profiling. + Available options are ["tree", "trace"]. + Defaults to "tree". + backend (str, optional): The backend to use for profiling. + Available options are [None, "cupti", "roctracer", "instrumentation"]. + Defaults to None, which automatically selects the backend matching the current active runtime. + mode (Union[str, BaseMode], optional): The "mode" to use for profiling, which is specific to the backend. + Can be a string or an instance of BaseMode (or any subclass thereof). + Defaults to None. + For "cupti", available options are [None, "pcsampling"]. + For "roctracer", available options are [None]. + For "instrumentation", available options are [None]. + Each mode has a set of control knobs following with the mode name. + For example, "pcsampling" has an "interval" control knob, expressed as "pcsampling:interval=1000". + hook (str, optional): The hook to use for profiling. + Available options are [None, "launch"]. + Defaults to None. + Returns: + session (int): The session ID of the profiling session. + """ + if is_command_line(): + # Ignore the start() call if the script is run from the command line. + return + + set_profiling_on() + + name = DEFAULT_PROFILE_NAME if name is None else name + backend = _select_backend() if backend is None else backend + backend_path = _get_backend_default_path(backend) + mode_str = _get_mode_str(backend, mode) + + _check_env(backend) + + # Convert mode to its string representation for libproton's runtime + session = libproton.start(name, context, data, backend, mode_str, backend_path) + + if hook == "triton": + HookManager.register(LaunchHook(), session) + if backend == "instrumentation": + HookManager.register(InstrumentationHook(mode), session) + + return session + + +def activate(session: Optional[int] = None) -> None: + """ + Activate the specified session. + The profiling session will be active and data will be recorded. + + Args: + session (int): The session ID of the profiling session. Defaults to None (all sessions) + + Returns: + None + """ + if is_command_line() and session != 0: + raise ValueError("Only one session can be activated when running from the command line.") + + HookManager.activate(session) + + if session is None: + libproton.activate_all() + else: + libproton.activate(session) + + +def deactivate(session: Optional[int] = None) -> None: + """ + Stop the specified session. + The profiling session's data will still be in the memory, but no more data will be recorded. + + Args: + session (int): The session ID of the profiling session. Defaults to None (all sessions) + + Returns: + None + """ + if is_command_line() and session != 0: + raise ValueError("Only one session can be deactivated when running from the command line.") + + HookManager.deactivate(session) + + if session is None: + libproton.deactivate_all() + else: + libproton.deactivate(session) + + +def finalize(session: Optional[int] = None, output_format: Optional[str] = "") -> None: + """ + Finalizes a profiling session. + Flush and write the profiling data to the file specified by the session name. + + Args: + session (int, optional): The session ID to finalize. If None, all sessions are finalized. Defaults to None. + output_format (str, optional): The output format for the profiling results. + Available options are ["hatchet", "chrome_trace"]. + + Returns: + None + """ + HookManager.unregister(session) + + if session is None: + set_profiling_off() + libproton.finalize_all(output_format) + else: + if is_command_line() and session != 0: + raise ValueError("Only one session can be finalized when running from the command line.") + libproton.finalize(session, output_format) + + +def _profiling( + func, + name: Optional[str] = None, + context: Optional[str] = "shadow", + data: Optional[str] = "tree", + backend: Optional[str] = None, + mode: Optional[str] = None, + hook: Optional[str] = None, +): + """ + Context manager for profiling. Internally use only. + + Args: + See start() for the arguments. + + Returns: + wrapper (function): The wrapped function. + """ + + @functools.wraps(func) + def wrapper(*args, **kwargs): + session = start(name, context=context, data=data, backend=backend, mode=mode, hook=hook) + ret = func(*args, **kwargs) + deactivate(session) + return ret + + return wrapper + + +def profile( + func=None, + *, + name: Optional[str] = None, + context: Optional[str] = "shadow", + data: Optional[str] = "tree", + backend: Optional[str] = None, + mode: Optional[str] = None, + hook: Optional[str] = None, +): + """ + Decorator for profiling. + + Usage: + + ```python + @proton.profile + def foo(): + pass + ``` + + Args: + See start() for the arguments. + + Returns: + decorator (function): The decorator function. + """ + if func is None: + # It's being used with parentheses, so return a decorator + def decorator(f): + return _profiling(f, name=name, context=context, data=data, backend=backend, mode=mode, hook=hook) + + return decorator + else: + # It's being used without parentheses, so apply the decorator directly + return _profiling(func, name=name, context=context, data=data, backend=backend, mode=mode, hook=hook) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/proton.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/proton.py new file mode 100644 index 0000000000000000000000000000000000000000..7c9cc478a688549e07abff5608c7b0e58955651e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/proton.py @@ -0,0 +1,88 @@ +import argparse +import sys +import os +from .profile import start, finalize, _select_backend +from .flags import set_command_line + + +def parse_arguments(): + parser = argparse.ArgumentParser( + description="The proton command utility for profiling scripts and pytest tests.", usage=""" + proton [options] script.py [script_args] [script_options] + proton [options] pytest [pytest_args] [script_options] + python -m triton.profiler.proton [options] script.py [script_args] [script_options] +""", formatter_class=argparse.RawTextHelpFormatter) + parser.add_argument("-n", "--name", type=str, help="Name of the profiling session") + parser.add_argument("-b", "--backend", type=str, help="Profiling backend", default=None, + choices=["cupti", "roctracer", "instrumentation"]) + parser.add_argument("-c", "--context", type=str, help="Profiling context", default="shadow", + choices=["shadow", "python"]) + parser.add_argument("-m", "--mode", type=str, help="Profiling mode", default=None) + parser.add_argument("-d", "--data", type=str, help="Profiling data", default="tree", choices=["tree", "trace"]) + parser.add_argument("-k", "--hook", type=str, help="Profiling hook", default=None, choices=[None, "launch"]) + parser.add_argument('target_args', nargs=argparse.REMAINDER, help='Subcommand and its arguments') + args = parser.parse_args() + return args, args.target_args + + +def is_pytest(script): + return os.path.basename(script) == 'pytest' + + +def execute_as_main(script, args): + script_path = os.path.abspath(script) + # Prepare a clean global environment + clean_globals = { + "__name__": "__main__", + "__file__": script_path, + "__builtins__": __builtins__, + sys.__name__: sys, + } + + original_argv = sys.argv + sys.argv = [script] + args + # Append the script's directory in case the script uses relative imports + sys.path.append(os.path.dirname(script_path)) + + # Execute in the isolated environment + try: + with open(script_path, 'rb') as file: + code = compile(file.read(), script_path, 'exec') + exec(code, clean_globals) + except Exception as e: + print(f"An error occurred while executing the script: {e}") + sys.exit(1) + finally: + sys.argv = original_argv + + +def do_setup_and_execute(target_args): + # Set the command line mode to avoid any `start` calls in the script. + set_command_line() + + script = target_args[0] + script_args = target_args[1:] if len(target_args) > 1 else [] + if is_pytest(script): + import pytest + pytest.main(script_args) + else: + execute_as_main(script, script_args) + + +def run_profiling(args, target_args): + backend = args.backend if args.backend else _select_backend() + + start(args.name, context=args.context, data=args.data, backend=backend, hook=args.hook) + + do_setup_and_execute(target_args) + + finalize() + + +def main(): + args, target_args = parse_arguments() + run_profiling(args, target_args) + + +if __name__ == "__main__": + main() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/scope.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/scope.py new file mode 100644 index 0000000000000000000000000000000000000000..624c1bd5c5ba340a4b53fc6b9642be0cfa284cec --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/scope.py @@ -0,0 +1,129 @@ +import threading +import time +from functools import wraps +from typing import Optional, Union + +from .flags import get_profiling_on +from triton._C.libproton import proton as libproton + +thread_local_scopes = threading.local() + +MetricValueType = Union[float, int] + + +class scope: + """ + A context manager and decorator for entering and exiting a scope. + + Usage: + context manager: + ```python + with proton.scope("test0", {metric_name: metric_value}): + foo[1,](x, y) + ``` + + decorator: + ```python + @proton.scope("test0", {metric_name: metric_value}) + def foo(x, y): + ... + ``` + + Args: + name (str): The name of the scope. + metrics (dict[str, float], optional): The metrics of the scope. Default is None. + """ + + def __init__(self, name: str, metrics: Optional[dict[str, MetricValueType]] = None) -> None: + self.name = name + self.metrics = metrics + self.id = None + + def _enter_scope(self): + if not get_profiling_on(): + return + self.id = libproton.record_scope() + libproton.enter_scope(self.id, self.name) + if self.metrics: + libproton.add_metrics(self.id, self.metrics) + + def _exit_scope(self): + if not get_profiling_on() or self.id is None: + return + libproton.exit_scope(self.id, self.name) + + def __enter__(self): + self._enter_scope() + return self + + def __exit__(self, exc_type, exc_value, traceback): + self._exit_scope() + + def __call__(self, func): + + @wraps(func) + def wrapper(*args, **kwargs): + self._enter_scope() + try: + return func(*args, **kwargs) + finally: + self._exit_scope() + + return wrapper + + +class cpu_timed_scope(scope): + """ + A scope that measures elapsed time (cpu_time). + + Args: + name (str): The name of the scope. + metrics (dict[str, float], optional): Additional metrics to add. Default is None. + """ + + def __init__(self, name: str, metrics: Optional[dict[str, float]] = None) -> None: + super().__init__(name, metrics) + self.start_time = None + if metrics and "cpu_time" in metrics: + raise ValueError("The metric name 'cpu_time' is reserved.") + + def _enter_scope(self): + if not get_profiling_on(): + return + self.start_time = time.time_ns() + super()._enter_scope() + + def _exit_scope(self): + if not get_profiling_on(): + return + super()._exit_scope() + if self.start_time is not None: + cpu_time = time.time_ns() - self.start_time + libproton.add_metrics(self.id, {"cpu_time (ns)(exc)": cpu_time}) + + +def enter_scope(name: str, *, metrics: Optional[dict[str, MetricValueType]] = None) -> Optional[int]: + if not get_profiling_on(): + return None + id = libproton.record_scope() + thread_local_scopes.scopes = getattr(thread_local_scopes, "scopes", []) + thread_local_scopes.scopes.append((id, name)) + libproton.enter_scope(id, name) + if metrics: + libproton.add_metrics(id, metrics) + return id + + +def exit_scope(name: Optional[str] = None, *, metrics: Optional[dict[str, MetricValueType]] = None) -> Optional[int]: + # `name` is an optional argument here, only to match the counterpart in enter_scope to make the API consistent with `proton.language.exit_scope` + if not get_profiling_on(): + return None + id, popped_name = thread_local_scopes.scopes.pop() + if name and name != popped_name: + raise ValueError(f"Scope name mismatch: {name} != {popped_name}") + elif not name: + name = popped_name + libproton.exit_scope(id, name) + if metrics: + libproton.add_metrics(id, metrics) + return id diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/specs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/specs.py new file mode 100644 index 0000000000000000000000000000000000000000..b30c3416d8ebc60351d6a4ce07b711512f3b22ef --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/specs.py @@ -0,0 +1,69 @@ +flops_by_device = { + "CUDA": { + "80": + lambda width, **kwargs: 624e12 / (width / 8), + "89": + lambda width, **kwargs: (330.3 * 1e12) / (width / 8), # TODO(Keren): Implement fp16 acc-> 660.6 fp8 + "90": + lambda width, num_sms, clock_rate, **kwargs: ((num_sms / 114 * clock_rate / (1755 * 1e3) * 1513) * 1e12) / + (width / 8), + "100": + lambda width, num_sms, clock_rate, **kwargs: (num_sms * 16384 * (clock_rate / 1e3) * 1e6) / (width / 8), + } +} + +amd_bps_by_arch = { + 'gfx90a': 3.2 * 1e12, + 'gfx942': 5.3 * 1e12, + 'gfx950': 8.0 * 1e12, +} + +# FP8 Matrix Performance(FLOPS/clock/CU) +# For gfx90a we use the performance of INT8 since it doesn't support FP8 matrix operations. +amd_fp8_flops_by_arch = {'gfx90a': 1024, 'gfx942': 4096, 'gfx950': 8192} + + +def max_flops(device_type, arch, width, num_sms, clock_rate): + """ + Calculate the maximum FLOPS for a given device type and width. + + Args: + device_type (str): The type of device (e.g., "CUDA", "HIP"). + arch (str): The architecture of the device (e.g., "80", "90"). + width (int): The width in bits. + num_sms (int): The number of streaming multiprocessors. + clock_rate (float): The clock rate in GHz. + + Returns: + float: The maximum FLOPS for the given device type and width. + """ + if device_type == "HIP": + return amd_fp8_flops_by_arch[arch] * num_sms * clock_rate * 1e3 / (width / 8) + + if device_type not in flops_by_device: + raise ValueError(f"Unsupported device type: {device_type}") + + if arch not in flops_by_device[device_type]: + raise ValueError(f"Unsupported architecture: {arch}") + + flops_func = flops_by_device[device_type][arch] + + return flops_func(width, num_sms=num_sms, clock_rate=clock_rate) + + +def max_bps(device_type, arch, bus_width, memory_clock_rate): + """ + Calculate the maximum bytes per second for a given bus width and memory clock rate. + + Args: + bus_width (int): The bus width in bits. + memory_clock_rate (float): The memory clock rate in GHz. + + Returns: + float: The maximum bytes per second. + """ + if device_type == "CUDA": + return 2 * bus_width * memory_clock_rate * 1e3 / 8 + else: + assert device_type == "HIP" + return amd_bps_by_arch[arch] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/state.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/state.py new file mode 100644 index 0000000000000000000000000000000000000000..dd1e47801fdb3ceb4bdc023441a79f7c7711f60a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/state.py @@ -0,0 +1,61 @@ +from triton._C.libproton import proton as libproton +from .flags import get_profiling_on +from functools import wraps + + +class state: + """ + A context manager and decorator for entering and exiting a state. + + Usage: + context manager: + ```python + with proton.state("test0"): + foo[1,](x, y) + ``` + + decorator: + ```python + @proton.state("test0") + def foo(x, y): + ... + ``` + + Args: + name (str): The name of the state. + """ + + def __init__(self, name: str) -> None: + self.name = name + + def __enter__(self): + if not get_profiling_on(): + return self + libproton.enter_state(self.name) + return self + + def __exit__(self, exc_type, exc_value, traceback) -> None: + if not get_profiling_on(): + return + libproton.exit_state() + + def __call__(self, func): + + @wraps(func) + def wrapper(*args, **kwargs): + if get_profiling_on(): + libproton.enter_state(self.name) + ret = func(*args, **kwargs) + if get_profiling_on(): + libproton.exit_state() + return ret + + return wrapper + + +def enter_state(name: str) -> None: + libproton.enter_state(name) + + +def exit_state() -> None: + libproton.exit_state() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/viewer.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/viewer.py new file mode 100644 index 0000000000000000000000000000000000000000..ab7a49e733b7932fbf75f5bdaf5d244cdd3ee376 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/profiler/viewer.py @@ -0,0 +1,413 @@ +import argparse +from collections import namedtuple +import json +import pandas as pd + +try: + import hatchet as ht + from hatchet.query import NegationQuery +except ImportError: + raise ImportError("Failed to import hatchet. `pip install llnl-hatchet` to get the correct version.") +import numpy as np +from triton.profiler.hooks.launch import COMPUTE_METADATA_SCOPE_NAME, LaunchHook +from triton.profiler import specs + + +def match_available_metrics(metrics, inclusive_metrics, exclusive_metrics): + ret = [] + if not isinstance(metrics, list): + metrics = [metrics] + if metrics: + for metric in metrics: + metric = metric.lower() + for raw_metric in inclusive_metrics + exclusive_metrics: + suffix = " (inc)" if raw_metric in inclusive_metrics else "" + raw_metric_no_unit = raw_metric.split("(")[0].strip().lower() + if metric in (raw_metric, raw_metric_no_unit): + ret.append(raw_metric + suffix) + break + if len(ret) == 0: + raise RuntimeError(f"Metric {metric} is not found. Use the --list flag to list available metrics") + return ret + + +def remove_frames(database: json): + # We first fine frames that match either one of the two conditions: + # 1. The frame name is COMPUTE_METADATA_SCOPE_NAME + # 2. The frame has no metrics and no children + # Then we go up from the located nodes and remove the parents if all children were + # metadata nodes + def remove_frame_helper(node): + if "frame" not in node: + return node + if node["frame"]["name"] == COMPUTE_METADATA_SCOPE_NAME: + return None + if len(node["metrics"]) == 0 and len(node["children"]) == 0: + return None + children = node.get("children", []) + new_children = [] + for child in children: + new_child = remove_frame_helper(child) + if new_child is not None: + new_children.append(new_child) + if len(new_children) > 0 or len(children) == 0: + node["children"] = new_children + return node + return None + + new_database = [] + for node in database: + new_node = remove_frame_helper(node) + if new_node is not None: + new_database.append(new_node) + return new_database + + +def get_raw_metrics(file): + database = json.load(file) + database = remove_frames(database) + device_info = database.pop(1) + gf = ht.GraphFrame.from_literal(database) + inclusive_metrics = gf.show_metric_columns() + exclusive_metrics = [metric for metric in gf.dataframe.columns if metric not in inclusive_metrics] + return gf, inclusive_metrics, exclusive_metrics, device_info + + +def get_min_time_flops(df, device_info): + min_time_flops = pd.DataFrame(0.0, index=df.index, columns=["min_time"]) + for device_type in device_info: + for device_index in device_info[device_type]: + arch = device_info[device_type][device_index]["arch"] + num_sms = device_info[device_type][device_index]["num_sms"] + clock_rate = device_info[device_type][device_index]["clock_rate"] + for width in LaunchHook.flops_width: + idx = df["device_id"] == device_index + device_frames = df[idx] + if f"flops{width}" not in device_frames.columns: + continue + max_flops = specs.max_flops(device_type, arch, width, num_sms, clock_rate) + min_time_flops.loc[idx, "min_time"] += device_frames[f"flops{width}"].fillna(0) / max_flops + return min_time_flops + + +def get_min_time_bytes(df, device_info): + min_time_bytes = pd.DataFrame(0.0, index=df.index, columns=["min_time"]) + for device_type in device_info: + for device_index in device_info[device_type]: + idx = df["device_id"] == device_index + device_frames = df[idx] + device = device_info[device_type][device_index] + memory_clock_rate = device["memory_clock_rate"] # in khz + bus_width = device["bus_width"] # in bits + peak_bandwidth = specs.max_bps(device_type, device['arch'], bus_width, memory_clock_rate) + min_time_bytes.loc[idx, "min_time"] += device_frames["bytes"] / peak_bandwidth + return min_time_bytes + + +FactorDict = namedtuple("FactorDict", ["name", "factor"]) +time_factor_dict = FactorDict("time", {"time/s": 1, "time/ms": 1e-3, "time/us": 1e-6, "time/ns": 1e-9}) +avg_time_factor_dict = FactorDict("avg_time", {f"avg_{key}": value for key, value in time_factor_dict.factor.items()}) +cpu_time_factor_dict = FactorDict("cpu_time", + {"cpu_time/s": 1, "cpu_time/ms": 1e-3, "cpu_time/us": 1e-6, "cpu_time/ns": 1e-9}) +avg_cpu_time_factor_dict = FactorDict("avg_cpu_time", + {f"avg_{key}": value + for key, value in cpu_time_factor_dict.factor.items()}) +bytes_factor_dict = FactorDict("bytes", {"byte/s": 1, "gbyte/s": 1e9, "tbyte/s": 1e12}) + +derivable_metrics = { + **{key: bytes_factor_dict + for key in bytes_factor_dict.factor.keys()}, +} + +# FLOPS have a specific width to their metric +default_flop_factor_dict = {"flop/s": 1, "gflop/s": 1e9, "tflop/s": 1e12} +derivable_metrics.update( + {key: FactorDict("flops", default_flop_factor_dict) + for key in default_flop_factor_dict.keys()}) +for width in LaunchHook.flops_width: + factor_name = f"flops{width}" + factor_dict = {f"flop{width}/s": 1, f"gflop{width}/s": 1e9, f"tflop{width}/s": 1e12} + derivable_metrics.update({key: FactorDict(factor_name, factor_dict) for key in factor_dict.keys()}) + + +def derive_metrics(gf, metrics, inclusive_metrics, exclusive_metrics, device_info): + derived_metrics = [] + + def get_time_seconds(df, metric, factor_dict): + time_metric_name = match_available_metrics(metric, inclusive_metrics, exclusive_metrics)[0] + time_unit = factor_dict.name + "/" + time_metric_name.split("(")[1].split(")")[0] + return df[time_metric_name] * factor_dict.factor[time_unit] + + for metric in metrics: + if metric == "util": # exclusive + min_time_bytes = get_min_time_bytes(gf.dataframe, device_info) + min_time_flops = get_min_time_flops(gf.dataframe, device_info) + time_sec = get_time_seconds(gf.dataframe, "time", time_factor_dict) + internal_frame_indices = gf.dataframe["device_id"].isna() + gf.dataframe["util"] = min_time_flops["min_time"].combine(min_time_bytes["min_time"], max) / time_sec + gf.dataframe.loc[internal_frame_indices, "util"] = np.nan + derived_metrics.append("util") + elif metric in derivable_metrics: # flop/s, byte/s, inclusive + derivable_metric = derivable_metrics[metric] + metric_name = derivable_metric.name + metric_factor_dict = derivable_metric.factor + matched_metric_name = match_available_metrics(metric_name, inclusive_metrics, exclusive_metrics)[0] + gf.dataframe[f"{metric} (inc)"] = (gf.dataframe[matched_metric_name] / + (get_time_seconds(gf.dataframe, "time", time_factor_dict)) / + metric_factor_dict[metric]) + derived_metrics.append(f"{metric} (inc)") + elif (metric in time_factor_dict.factor or metric in cpu_time_factor_dict.factor + or metric in avg_time_factor_dict.factor or metric in avg_cpu_time_factor_dict.factor): # inclusive + is_cpu = metric in cpu_time_factor_dict.factor or metric in avg_cpu_time_factor_dict.factor + is_avg = metric in avg_time_factor_dict.factor or metric in avg_cpu_time_factor_dict.factor + + factor_dict = ((avg_cpu_time_factor_dict if is_avg else cpu_time_factor_dict) if is_cpu else + (avg_time_factor_dict if is_avg else time_factor_dict)) + metric_name = "cpu_time" if is_cpu else "time" + metric_time_unit = factor_dict.name + "/" + metric.split("/")[1] + + time_value = get_time_seconds(gf.dataframe, metric_name, factor_dict) + if is_avg: + time_value = time_value / gf.dataframe["count (inc)"] + + gf.dataframe[f"{metric} (inc)"] = time_value / factor_dict.factor[metric_time_unit] + derived_metrics.append(f"{metric} (inc)") + else: + metric_name_and_unit = metric.split("/") + metric_name = metric_name_and_unit[0] + if len(metric_name_and_unit) > 1: # percentage, exclusive or inclusive + metric_unit = metric_name_and_unit[1] + if metric_unit != "%": + raise ValueError(f"Unsupported unit {metric_unit}") + matched_metric_name = match_available_metrics(metric_name, inclusive_metrics, exclusive_metrics)[0] + single_frame = gf.dataframe[matched_metric_name] + suffix = "" + if "(inc)" in matched_metric_name: + suffix = " (inc)" + total = gf.dataframe[matched_metric_name].iloc[0] + else: + total = gf.dataframe[matched_metric_name].sum() + gf.dataframe[metric + suffix] = (single_frame / total) * 100.0 + derived_metrics.append(metric + suffix) + else: + matched_metric_name = match_available_metrics(metric_name, inclusive_metrics, exclusive_metrics)[0] + derived_metrics.append(matched_metric_name) + + # Update derived metrics to the graph frame + for derived_metric in derived_metrics: + if derived_metric.endswith("(inc)"): + gf.inc_metrics.append(derived_metric) + else: + gf.exc_metrics.append(derived_metric) + + return derived_metrics + + +def format_frames(gf, format): + if format == "file_function_line": + gf.dataframe["name"] = gf.dataframe["name"].apply(lambda x: x.split("/")[-1]) + elif format == "function_line": + gf.dataframe["name"] = gf.dataframe["name"].apply(lambda x: x.split(":")[-1]) + elif format == "file_function": + gf.dataframe["name"] = gf.dataframe["name"].apply( + lambda x: f"{x.split('/')[-1].split(':')[0]}@{x.split('@')[-1].split(':')[0]}") + return gf + + +def filter_frames(gf, include=None, exclude=None, threshold=None, metric=None): + if include: + query = f""" +MATCH ("*")->(".", p)->("*") +WHERE p."name" =~ "{include}" +""" + gf = gf.filter(query, squash=True) + if exclude: + inclusion_query = f""" +MATCH (".", p)->("*") +WHERE p."name" =~ "{exclude}" +""" + query = NegationQuery(inclusion_query) + gf = gf.filter(query, squash=True) + if threshold: + query = ["*", {metric: f">= {threshold}"}] + gf = gf.filter(query, squash=True) + return gf + + +def emit_warnings(gf, metrics): + if "bytes (inc)" in metrics: + byte_values = gf.dataframe["bytes (inc)"].values + min_byte_value = np.nanmin(byte_values) + if min_byte_value < 0: + print("Warning: Negative byte values detected, this is usually the result of a datatype overflow\n") + + +def print_tree(gf, metrics, depth=100, format=None, print_sorted=False): + gf = format_frames(gf, format) + print(gf.tree(metric_column=metrics, expand_name=True, depth=depth, render_header=False)) + + if print_sorted: + print("Sorted kernels by metric " + metrics[0]) + sorted_df = gf.dataframe.sort_values(by=[metrics[0]], ascending=False) + for row in range(1, len(sorted_df)): + kernel_name = (sorted_df.iloc[row]["name"][:100] + + "..." if len(sorted_df.iloc[row]["name"]) > 100 else sorted_df.iloc[row]["name"]) + print("{:105} {:.4}".format(kernel_name, sorted_df.iloc[row][metrics[0]])) + emit_warnings(gf, metrics) + + +def read(filename): + with open(filename, "r") as f: + gf, inclusive_metrics, exclusive_metrics, device_info = get_raw_metrics(f) + assert len(inclusive_metrics + exclusive_metrics) > 0, "No metrics found in the input file" + gf.update_inclusive_columns() + return gf, inclusive_metrics, exclusive_metrics, device_info + + +def parse(metrics, filename, include=None, exclude=None, threshold=None): + gf, inclusive_metrics, exclusive_metrics, device_info = read(filename) + metrics = derive_metrics(gf, metrics, inclusive_metrics, exclusive_metrics, device_info) + # TODO: generalize to support multiple metrics, not just the first one + gf = filter_frames(gf, include, exclude, threshold, metrics[0]) + return gf, metrics + + +def show_metrics(file_name): + with open(file_name, "r") as f: + _, inclusive_metrics, exclusive_metrics, _ = get_raw_metrics(f) + print("Available inclusive metrics:") + if inclusive_metrics: + for raw_metric in inclusive_metrics: + raw_metric_no_unit = raw_metric.split("(")[0].strip().lower() + print(f"- {raw_metric_no_unit}") + print("Available exclusive metrics:") + if exclusive_metrics: + for raw_metric in exclusive_metrics: + raw_metric_no_unit = raw_metric.split("(")[0].strip().lower() + print(f"- {raw_metric_no_unit}") + + +def main(): + argparser = argparse.ArgumentParser( + description="Performance data viewer for proton profiles.", + formatter_class=argparse.RawTextHelpFormatter, + ) + argparser.add_argument( + "-l", + "--list", + action="store_true", + help="""List available metrics. Metric names are case insensitive and ignore units. +Derived metrics can be created when source metrics are available. +- time/s, time/ms, time/us, time/ns: time +- avg_time/s, avg_time/ms, avg_time/us, avg_time/ns: time / count +- flop[<8/16/32/64>]/s, gflop[<8/16/32/64>]/s, tflop[<8/16/32/64>]/s: flops / time +- byte/s, gbyte/s, tbyte/s: bytes / time +- util: max(sum(flops) / peak_flops_time, sum(bytes) / peak_bandwidth_time) +- /%%: frame(metric) / sum(metric). Only available for inclusive metrics (e.g. time) +""", + ) + argparser.add_argument( + "-m", + "--metrics", + type=str, + default=None, + help="""At maximum two metrics can be specified, separated by comma. +There are two modes: +1) Choose the output metric to display. It's case insensitive and ignore units. +2) Derive a new metric from existing metrics. +""", + ) + argparser.add_argument( + "-i", + "--include", + type=str, + default=None, + help= + """Find frames that match the given regular expression and return all nodes in the paths that pass through the matching frames. +For example, the following command will display all paths that contain frames that contains "test": +``` +proton-viewer -i ".*test.*" path/to/file.json +``` +""", + ) + argparser.add_argument( + "-e", + "--exclude", + type=str, + default=None, + help="""Exclude frames that match the given regular expression and their children. +For example, the following command will exclude all paths starting from frames that contains "test": +``` +proton-viewer -e ".*test.*" path/to/file.json +``` +""", + ) + argparser.add_argument( + "-t", + "--threshold", + type=float, + default=None, + help= + "Exclude frames(kernels) whose metrics are below the given threshold. This filter only applies on the first metric.", + ) + argparser.add_argument( + "-d", + "--depth", + type=int, + default=100, + help="The depth of the tree to display", + ) + argparser.add_argument( + "-f", + "--format", + type=str, + choices=["full", "file_function_line", "function_line", "file_function"], + default="full", + help="""Formatting the frame name. +- full: include the path, file name, function name and line number. +- file_function_line: include the file name, function name and line number. +- function_line: include the function name and line number. +- file_function: include the file name and function name. +""", + ) + argparser.add_argument( + "--print-sorted", + action="store_true", + default=False, + help="Sort output by metric value instead of chronologically", + ) + argparser.add_argument( + "--diff-profile", + "-diff", + type=str, + default=None, + help="Compare two profiles. When used as 'proton-viewer -m time -diff file1.log file2.log', " + "computes the difference: file2['time'] - file1['time']", + ) + + args, target_args = argparser.parse_known_args() + assert len(target_args) == 1, "Must specify a file to read" + + file_name = target_args[0] + metrics = args.metrics.split(",") if args.metrics else None + include = args.include + exclude = args.exclude + threshold = args.threshold + depth = args.depth + format = args.format + diff = args.diff_profile + print_sorted = args.print_sorted + if include and exclude: + raise ValueError("Cannot specify both include and exclude") + if args.list: + show_metrics(file_name) + elif metrics: + gf, derived_metrics = parse(metrics, file_name, include, exclude, threshold) + if diff: + gf2, _ = parse(metrics, diff, include, exclude, threshold) + gf = gf.sub(gf2) + print_tree(gf, derived_metrics, depth, format, print_sorted) + + +if __name__ == "__main__": + main() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0b3979d28d9a4359be5ceb3d2dea08f4d56899e6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__init__.py @@ -0,0 +1,23 @@ +from .autotuner import (Autotuner, Config, Heuristics, autotune, heuristics) +from .cache import RedisRemoteCacheBackend, RemoteCacheBackend +from .driver import driver +from .jit import JITFunction, KernelInterface, MockTensor, TensorWrapper, reinterpret +from .errors import OutOfResources, InterpreterError + +__all__ = [ + "autotune", + "Autotuner", + "Config", + "driver", + "Heuristics", + "heuristics", + "InterpreterError", + "JITFunction", + "KernelInterface", + "MockTensor", + "OutOfResources", + "RedisRemoteCacheBackend", + "reinterpret", + "RemoteCacheBackend", + "TensorWrapper", +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9da0f79f9c96b50eef06e021256f3611f49dc114 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/_allocation.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/_allocation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f1b17e662d26431de6d93c86d7759e859235c9e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/_allocation.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/_async_compile.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/_async_compile.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42b58c144846793d37e738f3fe3923bbb7fe7d12 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/_async_compile.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/autotuner.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/autotuner.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a5f904630b95e219271332e95817f2611b9426e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/autotuner.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/build.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/build.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd0125d71b233f03fd36616c0292409083109e26 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/build.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/cache.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/cache.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb9895775803abf4a0e9b5525555a5867b264717 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/cache.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/driver.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/driver.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc21a128ad3cba0352d3321b9a2c2e9022d77c83 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/driver.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/errors.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/errors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b44142c9664854c52852ffe792f8f4de7b381b8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/errors.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/jit.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/jit.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..593831d743aec66d0cfc4583b9defcc6796e39a9 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/__pycache__/jit.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/_allocation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/_allocation.py new file mode 100644 index 0000000000000000000000000000000000000000..68bef4d5769182e2114fa5d6af8455d89e80635b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/_allocation.py @@ -0,0 +1,44 @@ +from typing import Optional, Protocol +from contextvars import ContextVar + + +class Buffer(Protocol): + + def data_ptr(self) -> int: + ... + + +class Allocator(Protocol): + + def __call__(self, size: int, alignment: int, stream: Optional[int]) -> Buffer: + ... + + +class NullAllocator: + + def __call__(self, size: int, alignment: int, stream: Optional[int]) -> Buffer: + raise RuntimeError("Kernel requires a runtime memory allocation, but no allocator was set. " + + "Use triton.set_allocator to specify an allocator.") + + +_allocator: ContextVar[Allocator] = ContextVar("_allocator", default=NullAllocator()) + + +def set_allocator(allocator: Allocator): + """ + The allocator function is called during kernel launch for kernels that + require additional global memory workspace. + """ + _allocator.set(allocator) + + +_profile_allocator: Allocator = ContextVar("_allocator", default=NullAllocator()) + + +def set_profile_allocator(allocator: Optional[Allocator]): + """ + The profile allocator function is called before kernel launch for kernels + that require additional global memory workspace. + """ + global _profile_allocator + _profile_allocator.set(allocator) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/_async_compile.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/_async_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..ee0906043f37da5445d41882d052223426a43497 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/_async_compile.py @@ -0,0 +1,55 @@ +from __future__ import annotations +from typing import Callable, Optional +from concurrent.futures import Executor, as_completed, Future +from contextvars import ContextVar + +active_mode: ContextVar[Optional[AsyncCompileMode]] = ContextVar("async_compile_active_mode", default=None) + + +class FutureKernel: + + def __init__(self, finalize_compile: Callable, future: Future): + self.finalize_compile = finalize_compile + self.kernel = None + self.future = future + + def result(self): + if self.kernel is not None: + return self.kernel + + kernel = self.future.result() + self.finalize_compile(kernel) + self.kernel = kernel + return kernel + + +class AsyncCompileMode: + + def __init__(self, executor: Executor): + self.executor = executor + self.raw_futures = [] + self.future_kernels = {} + + def submit(self, key, compile_fn, finalize_fn): + future = self.future_kernels.get(key) + if future is not None: + return future + + future = self.executor.submit(compile_fn) + future._key = key + self.raw_futures.append(future) + future_kernel = FutureKernel(finalize_fn, future) + self.future_kernels[key] = future_kernel + return future_kernel + + def __enter__(self): + if active_mode.get() is not None: + raise RuntimeError("Another AsyncCompileMode is already active") + active_mode.set(self) + return self + + def __exit__(self, exc_type, exc_value, traceback): + # Finalize any outstanding compiles + for future in as_completed(self.raw_futures): + self.future_kernels[future._key].result() + active_mode.set(None) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/autotuner.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/autotuner.py new file mode 100644 index 0000000000000000000000000000000000000000..a29c95aaed7e55254cfc9e33fcdea40f57d35b59 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/autotuner.py @@ -0,0 +1,476 @@ +from __future__ import annotations + +import builtins +import time +import inspect +import hashlib +import json +from functools import cached_property +from typing import Dict, Tuple, List, Optional + +from .. import knobs +from .jit import KernelInterface, JITFunction +from .errors import OutOfResources, PTXASError +from .driver import driver +from .cache import get_cache_manager, triton_key +from triton._C.libtriton import get_cache_invalidating_env_vars + + +class Autotuner(KernelInterface): + + def __init__(self, fn, arg_names, configs, key, reset_to_zero, restore_value, pre_hook=None, post_hook=None, + prune_configs_by: Optional[Dict] = None, warmup=None, rep=None, use_cuda_graph=False, do_bench=None, + cache_results=False): + """ + :param prune_configs_by: a dict of functions that are used to prune configs, fields: + 'perf_model': performance model used to predicate running time with different configs, returns running time + 'top_k': number of configs to bench + 'prune_num_stages_by'(optional): a function used to prune num_stages. It takes configs:List[Config] as its input, and returns pruned configs. + """ + if not configs: + self.configs = [Config({}, num_warps=4, num_stages=3, num_ctas=1)] + else: + self.configs = configs + self.keys = key + self.cache: Dict[Tuple, Config] = {} + self.arg_names = arg_names + self.cache_results = cache_results or (knobs.autotuning.cache and not knobs.runtime.interpret) + + # Reset to zero or restore values + self.reset_to_zero = [] + if reset_to_zero is not None: + self.reset_to_zero = list(reset_to_zero) + self.restore_value = [] + if restore_value is not None: + self.restore_value = list(restore_value) + + # Hook to reset or restore for required tensors + self.pre_hook = lambda kwargs, reset_only=False: 0 + self.post_hook = lambda kwargs, exception: 0 + self.user_defined_pre_hook = False + self.user_defined_post_hook = False + if pre_hook: + self.pre_hook = pre_hook + self.user_defined_pre_hook = True + elif (len(self.reset_to_zero) > 0 or len(self.restore_value) > 0): + + def _pre_hook(kwargs, reset_only=False): + for name in self.reset_to_zero: + kwargs[name].zero_() + if not reset_only: + self.restore_copies = {name: kwargs[name].clone() for name in self.restore_value} + + self.pre_hook = _pre_hook + + if post_hook: + self.post_hook = post_hook + self.user_defined_post_hook = True + elif len(self.restore_value) > 0: + + def _post_hook(kwargs, exception): + for name in self.restore_value: + kwargs[name].copy_(self.restore_copies[name]) + self.restore_copies = {} + + self.post_hook = _post_hook + + self.perf_model = None + self.configs_top_k = 1.0 + self.early_config_prune = None + if prune_configs_by: + self.perf_model = prune_configs_by.get("perf_model", self.perf_model) + self.configs_top_k = prune_configs_by.get("top_k", self.configs_top_k) + self.early_config_prune = prune_configs_by.get("early_config_prune", self.early_config_prune) + + self.fn = fn + self.base_fn = fn + while not inspect.isfunction(self.base_fn): + self.base_fn = self.base_fn.fn + + self._do_bench = do_bench + self.num_warmups = warmup + self.num_reps = rep + self.use_cuda_graph = use_cuda_graph + + # If we got explicitly called via the old interface, raise a warning + # and proceed with the old behavior. + if warmup is not None or rep is not None or use_cuda_graph: + import warnings + warnings.warn(("warmup, rep, and use_cuda_graph parameters are deprecated. See " + "https://github.com/triton-lang/triton/pull/4496 for details."), DeprecationWarning, + stacklevel=1) + if use_cuda_graph: + from ..testing import do_bench_cudagraph + self._do_bench = lambda kernel_call, quantiles: do_bench_cudagraph( + kernel_call, + rep=rep if rep is not None else 100, + quantiles=quantiles, + ) + return + + import triton.testing + self._do_bench = lambda kernel_call, quantiles: triton.testing.do_bench( + kernel_call, + warmup=warmup if warmup is not None else 25, + rep=rep if rep is not None else 100, + quantiles=quantiles, + ) + return + + @cached_property + def do_bench(self): + if self._do_bench is None: + return driver.active.get_benchmarker() + return self._do_bench + + def _bench(self, *args, config, **meta): + from ..compiler.errors import CompileTimeAssertionFailure + + verbose = knobs.autotuning.print + if verbose: + print(f"Autotuning kernel {self.base_fn.__name__} with config {config}") + + # check for conflicts, i.e. meta-parameters both provided + # as kwargs and by the autotuner + conflicts = meta.keys() & config.kwargs.keys() + if conflicts: + raise ValueError(f"Conflicting meta-parameters: {', '.join(conflicts)}." + " Make sure that you don't re-define auto-tuned symbols.") + # augment meta-parameters with tunable ones + current = dict(meta, **config.all_kwargs()) + full_nargs = {**self.nargs, **current} + + def kernel_call(): + if config.pre_hook: + config.pre_hook(full_nargs) + self.pre_hook(full_nargs) + try: + self.fn.run( + *args, + **current, + ) + except Exception as e: + try: + self.post_hook(full_nargs, exception=e) + finally: + # Throw exception raised by `self.fn.run` + raise + + self.post_hook(full_nargs, exception=None) + + try: + return self.do_bench(kernel_call, quantiles=(0.5, 0.2, 0.8)) + except (OutOfResources, CompileTimeAssertionFailure, PTXASError) as e: + if verbose: + print(f"Autotuning failed with {e}") + return [float("inf"), float("inf"), float("inf")] + + def check_disk_cache(self, tuning_key, configs, bench_fn): + # We can't serialize prehooks, so just give up and run the benchmarks. + if not tuning_key or any(cfg.pre_hook for cfg in configs): + bench_fn() + return False + + from triton.compiler.compiler import make_backend + + fn = self.fn + while not isinstance(fn, JITFunction): + fn = fn.fn + + env_vars = get_cache_invalidating_env_vars() + cache_key = [ + triton_key(), + make_backend(driver.active.get_current_target()).hash(), + fn.cache_key, + str(sorted(env_vars.items())), + str(tuning_key), + ] + [str(c) for c in configs] + cache_key = hashlib.sha256("-".join(cache_key).encode("utf-8")).hexdigest() + cache = get_cache_manager(cache_key) + file_name = f"{fn.__name__[:150]}.autotune.json" + path = cache.get_file(file_name) + if path: + with open(path, "r") as cached_configs: + timings = json.load(cached_configs)["configs_timings"] + timings = {Config(**config): timing for config, timing in timings} + self.cache[tuning_key] = builtins.min(timings, key=timings.get) + self.configs_timings = timings + return True + + bench_fn() + cache.put( + json.dumps({ + "key": + tuning_key, + "configs_timings": + [(config.__dict__, timings) for config, timings in self.configs_timings.items() if not config.pre_hook], + }), file_name, binary=False) + return False + + def run(self, *args, **kwargs): + self.nargs = dict(zip(self.arg_names, args)) + used_cached_result = True + if len(self.configs) > 1: + all_args = {**self.nargs, **kwargs} + _args = {k: v for (k, v) in all_args.items() if k in self.arg_names} + key = [_args[key] for key in self.keys if key in _args] + for _, arg in _args.items(): + if hasattr(arg, "dtype"): + key.append(str(arg.dtype)) + key = tuple(key) + if key not in self.cache: + used_cached_result = False + pruned_configs = self.prune_configs(kwargs) + + def benchmark(): + bench_start = time.time() + timings = {config: self._bench(*args, config=config, **kwargs) for config in pruned_configs} + bench_end = time.time() + self.bench_time = bench_end - bench_start + self.cache[key] = builtins.min(timings, key=timings.get) + full_nargs = {**self.nargs, **kwargs, **self.cache[key].all_kwargs()} + self.pre_hook(full_nargs, reset_only=True) + self.configs_timings = timings + + if self.cache_results: + used_cached_result = self.check_disk_cache(key, pruned_configs, benchmark) + else: + benchmark() + + config = self.cache[key] + else: + config = self.configs[0] + self.best_config = config + if knobs.autotuning.print and not used_cached_result: + print(f"Triton autotuning for function {self.base_fn.__name__},\nwith key as {key},\n" + f"finished after {self.bench_time:.2f}s,\nbest config selected: {self.best_config};") + if config.pre_hook is not None: + full_nargs = {**self.nargs, **kwargs, **config.all_kwargs()} + config.pre_hook(full_nargs) + ret = self.fn.run( + *args, + **kwargs, + **config.all_kwargs(), + ) + self.nargs = None + return ret + + def prune_configs(self, kwargs: Dict) -> List[Config]: + pruned_configs = self.configs + if self.early_config_prune: + pruned_configs = self.early_config_prune(self.configs, self.nargs, **kwargs) + if self.perf_model: + top_k = self.configs_top_k + if isinstance(top_k, float) and top_k <= 1.0: + top_k = int(len(self.configs) * top_k) + elif not isinstance(top_k, int): + # Slice index must be an integer + raise TypeError("Error while pruning configs, top_k must be either 1) a float <= 1.0 or 2) an int") + + if len(pruned_configs) > top_k: + est_timing = { + config: self.perf_model( + **self.nargs, + **kwargs, + **config.all_kwargs(), + ) + for config in pruned_configs + } + pruned_configs = sorted(est_timing.keys(), key=lambda x: est_timing[x])[:top_k] + return pruned_configs + + def warmup(self, *args, **kwargs): + self.nargs = dict(zip(self.arg_names, args)) + ret = [] + for autotune_config in self.prune_configs(kwargs): + ret.append(self.fn.warmup( + *args, + **kwargs, + **autotune_config.all_kwargs(), + )) + self.nargs = None + return ret + + +class Config: + """ + An object that represents a possible kernel configuration for the auto-tuner to try. + + :ivar kwargs: a dictionary of meta-parameters to pass to the kernel as keyword arguments. + :type kwargs: dict[Str, Any] + :ivar num_warps: the number of warps to use for the kernel when compiled for GPUs. For example, if + `num_warps=8`, then each kernel instance will be automatically parallelized to + cooperatively execute using `8 * 32 = 256` threads. + :type num_warps: int + :ivar num_stages: the number of stages that the compiler should use when software-pipelining loops. + Mostly useful for matrix multiplication workloads on SM80+ GPUs. + :type num_stages: int + :ivar num_ctas: number of blocks in a block cluster. SM90+ only. + :type num_ctas: int + :type maxnreg: Optional[int] + :ivar maxnreg: maximum number of registers one thread can use. Corresponds + to ptx .maxnreg directive. Not supported on all platforms. + :ivar pre_hook: a function that will be called before the kernel is called. Parameters of this + function are args. + :ivar ir_override: filename of a user-defined IR (*.{ttgir|llir|ptx|amdgcn}). + """ + + def __init__(self, kwargs, num_warps=4, num_stages=3, num_ctas=1, maxnreg=None, pre_hook=None, ir_override=None): + self.kwargs = kwargs + self.num_warps = num_warps + self.num_ctas = num_ctas + self.num_stages = num_stages + self.maxnreg = maxnreg + self.pre_hook = pre_hook + self.ir_override = ir_override + + def __setstate__(self, state): + self.kwargs = state.get("kwargs", {}) + self.num_warps = state.get("num_warps", 4) + self.num_stages = state.get("num_stages", 3) + self.num_ctas = state.get("num_ctas", 1) + self.maxnreg = state.get("maxnreg", None) + self.pre_hook = state.get("pre_hook", None) + self.ir_override = state.get("ir_override", None) + + def all_kwargs(self): + return { + **self.kwargs, **{ + k: v + for (k, v) in ( + ("num_warps", self.num_warps), + ("num_ctas", self.num_ctas), + ("num_stages", self.num_stages), + ("maxnreg", self.maxnreg), + ("ir_override", self.ir_override), + ) if v is not None + } + } + + def __str__(self): + res = [] + for k, v in self.kwargs.items(): + res.append(f"{k}: {v}") + res.append(f"num_warps: {self.num_warps}") + res.append(f"num_ctas: {self.num_ctas}") + res.append(f"num_stages: {self.num_stages}") + res.append(f"maxnreg: {self.maxnreg}") + return ", ".join(res) + + def __hash__(self): + return hash((*self.all_kwargs().items(), self.pre_hook)) + + def __eq__(self, other): + self_tuple = tuple(( + *self.all_kwargs().items(), + self.pre_hook, + )) + other_tuple = tuple(( + *other.all_kwargs().items(), + other.pre_hook, + )) + return self_tuple == other_tuple + + +def autotune(configs, key, prune_configs_by=None, reset_to_zero=None, restore_value=None, pre_hook=None, post_hook=None, + warmup=None, rep=None, use_cuda_graph=False, do_bench=None, cache_results=False): + """ + Decorator for auto-tuning a :code:`triton.jit`'d function. + + .. highlight:: python + .. code-block:: python + + @triton.autotune(configs=[ + triton.Config(kwargs={'BLOCK_SIZE': 128}, num_warps=4), + triton.Config(kwargs={'BLOCK_SIZE': 1024}, num_warps=8), + ], + key=['x_size'] # the two above configs will be evaluated anytime + # the value of x_size changes + ) + @triton.jit + def kernel(x_ptr, x_size, BLOCK_SIZE: tl.constexpr): + ... + :note: When all the configurations are evaluated, the kernel will run multiple times. + This means that whatever value the kernel updates will be updated multiple times. + To avoid this undesired behavior, you can use the `reset_to_zero` argument, which + resets the value of the provided tensor to `zero` before running any configuration. + + If the environment variable :code:`TRITON_PRINT_AUTOTUNING` is set to + :code:`"1"`, Triton will print a message to stdout after autotuning each + kernel, including the time spent autotuning and the best configuration. + + :param configs: a list of :code:`triton.Config` objects + :type configs: list[triton.Config] + :param key: a list of argument names whose change in value will trigger the evaluation of all provided configs. + :type key: list[str] + :param prune_configs_by: a dict of functions that are used to prune configs, fields: + 'perf_model': performance model used to predicate running time with different configs, returns running time + 'top_k': number of configs to bench + 'early_config_prune'(optional): a function used to do early prune (eg, num_stages). It takes configs:List[Config] as its input, and returns pruned configs. + :param reset_to_zero: a list of argument names whose value will be reset to zero before evaluating any configs. + :type reset_to_zero: list[str] + :param restore_value: a list of argument names whose value will be restored after evaluating any configs. + :type restore_value: list[str] + :param pre_hook: a function that will be called before the kernel is called. + This overrides the default pre_hook used for 'reset_to_zero' and 'restore_value'. + 'kwargs': a dict of all arguments passed to the kernel. + 'reset_only': a boolean indicating whether the pre_hook is called to reset the values only, without a corresponding post_hook. + :type pre_hook: lambda args, reset_only + :param post_hook: a function that will be called after the kernel is called. + This overrides the default post_hook used for 'restore_value'. + 'kwargs': a dict of all arguments passed to the kernel. + 'exception': the exception raised by the kernel in case of a compilation or runtime error. + :type post_hook: lambda args, exception + :param warmup: warmup time (in ms) to pass to benchmarking (deprecated). + :type warmup: int + :param rep: repetition time (in ms) to pass to benchmarking (deprecated). + :type rep: int + :param do_bench: a benchmark function to measure the time of each run. + :type do_bench: lambda fn, quantiles + :param cache_results: whether to cache autotune timings to disk. Defaults to False. + "type cache_results: bool + """ + + def decorator(fn): + return Autotuner(fn, fn.arg_names, configs, key, reset_to_zero, restore_value, pre_hook=pre_hook, + post_hook=post_hook, prune_configs_by=prune_configs_by, warmup=warmup, rep=rep, + use_cuda_graph=use_cuda_graph, do_bench=do_bench, cache_results=cache_results) + + return decorator + + +class Heuristics(KernelInterface): + + def __init__(self, fn, arg_names, values) -> None: + self.fn = fn + self.values = values + self.arg_names = arg_names + + def run(self, *args, **kwargs): + for v, heur in self.values.items(): + kwargs[v] = heur({**dict(zip(self.arg_names, args)), **kwargs}) + return self.fn.run(*args, **kwargs) + + +def heuristics(values): + """ + Decorator for specifying how the values of certain meta-parameters may be computed. + This is useful for cases where auto-tuning is prohibitively expensive, or just not applicable. + + .. highlight:: python + .. code-block:: python + + # smallest power-of-two >= x_size + @triton.heuristics(values={'BLOCK_SIZE': lambda args: triton.next_power_of_2(args['x_size'])}) + @triton.jit + def kernel(x_ptr, x_size, BLOCK_SIZE: tl.constexpr): + ... + :param values: a dictionary of meta-parameter names and functions that compute the value of the meta-parameter. + each such function takes a list of positional arguments as input. + :type values: dict[str, Callable[[dict[str, Any]], Any]] + """ + + def decorator(fn): + return Heuristics(fn, fn.arg_names, values) + + return decorator diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/build.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/build.py new file mode 100644 index 0000000000000000000000000000000000000000..7614fe2ae0262cc486201481c99e6bc4c34ebabc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/build.py @@ -0,0 +1,93 @@ +from __future__ import annotations + +import functools +import hashlib +import importlib.util +import logging +import os +import shutil +import subprocess +import sysconfig +import tempfile + +from types import ModuleType + +from .cache import get_cache_manager +from .. import knobs + + +def _build(name: str, src: str, srcdir: str, library_dirs: list[str], include_dirs: list[str], libraries: list[str], + ccflags: list[str]) -> str: + if impl := knobs.build.impl: + return impl(name, src, srcdir, library_dirs, include_dirs, libraries) + suffix = sysconfig.get_config_var('EXT_SUFFIX') + so = os.path.join(srcdir, '{name}{suffix}'.format(name=name, suffix=suffix)) + cc = os.environ.get("CC") + if cc is None: + clang = shutil.which("clang") + gcc = shutil.which("gcc") + cc = gcc if gcc is not None else clang + if cc is None: + raise RuntimeError( + "Failed to find C compiler. Please specify via CC environment variable or set triton.knobs.build.impl.") + # This function was renamed and made public in Python 3.10 + if hasattr(sysconfig, 'get_default_scheme'): + scheme = sysconfig.get_default_scheme() + else: + scheme = sysconfig._get_default_scheme() # type: ignore + # 'posix_local' is a custom scheme on Debian. However, starting Python 3.10, the default install + # path changes to include 'local'. This change is required to use triton with system-wide python. + if scheme == 'posix_local': + scheme = 'posix_prefix' + py_include_dir = sysconfig.get_paths(scheme=scheme)["include"] + custom_backend_dirs = knobs.build.backend_dirs + include_dirs = include_dirs + [srcdir, py_include_dir, *custom_backend_dirs] + # for -Wno-psabi, see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111047 + cc_cmd = [cc, src, "-O3", "-shared", "-fPIC", "-Wno-psabi", "-o", so] + cc_cmd += [f'-l{lib}' for lib in libraries] + cc_cmd += [f"-L{dir}" for dir in library_dirs] + cc_cmd += [f"-I{dir}" for dir in include_dirs if dir is not None] + cc_cmd.extend(ccflags) + subprocess.check_call(cc_cmd, stdout=subprocess.DEVNULL) + return so + + +@functools.lru_cache +def platform_key() -> str: + from platform import machine, system, architecture + return ",".join([machine(), system(), *architecture()]) + + +def _load_module_from_path(name: str, path: str) -> ModuleType: + spec = importlib.util.spec_from_file_location(name, path) + if not spec or not spec.loader: + raise RuntimeError(f"Failed to load newly compiled {name} from {path}") + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def compile_module_from_src(src: str, name: str, library_dirs: list[str] | None = None, + include_dirs: list[str] | None = None, libraries: list[str] | None = None, + ccflags: list[str] | None = None) -> ModuleType: + key = hashlib.sha256((src + platform_key()).encode("utf-8")).hexdigest() + cache = get_cache_manager(key) + suffix = sysconfig.get_config_var("EXT_SUFFIX") + cache_path = cache.get_file(f"{name}{suffix}") + + if cache_path is not None: + try: + return _load_module_from_path(name, cache_path) + except (RuntimeError, ImportError): + log = logging.getLogger(__name__) + log.warning(f"Triton cache error: compiled module {name}.so could not be loaded") + + with tempfile.TemporaryDirectory() as tmpdir: + src_path = os.path.join(tmpdir, name + ".c") + with open(src_path, "w") as f: + f.write(src) + so = _build(name, src_path, tmpdir, library_dirs or [], include_dirs or [], libraries or [], ccflags or []) + with open(so, "rb") as f: + cache_path = cache.put(f.read(), f"{name}{suffix}", binary=True) + + return _load_module_from_path(name, cache_path) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/cache.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..0442f00e68f5f907a4da56ebd7689e8c469219ef --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/cache.py @@ -0,0 +1,309 @@ +import json +import os +import uuid +from abc import ABC, abstractmethod +from typing import Dict, List, Optional +import base64 +import hashlib +import functools +import sysconfig + +from triton import __version__, knobs + + +class CacheManager(ABC): + + def __init__(self, key, override=False, dump=False): + pass + + @abstractmethod + def get_file(self, filename) -> Optional[str]: + pass + + @abstractmethod + def put(self, data, filename, binary=True) -> str: + pass + + @abstractmethod + def get_group(self, filename: str) -> Optional[Dict[str, str]]: + pass + + @abstractmethod + def put_group(self, filename: str, group: Dict[str, str]): + pass + + +class FileCacheManager(CacheManager): + + def __init__(self, key, override=False, dump=False): + self.key = key + self.lock_path = None + if dump: + self.cache_dir = knobs.cache.dump_dir + self.cache_dir = os.path.join(self.cache_dir, self.key) + self.lock_path = os.path.join(self.cache_dir, "lock") + os.makedirs(self.cache_dir, exist_ok=True) + elif override: + self.cache_dir = knobs.cache.override_dir + self.cache_dir = os.path.join(self.cache_dir, self.key) + else: + # create cache directory if it doesn't exist + self.cache_dir = knobs.cache.dir + if self.cache_dir: + self.cache_dir = os.path.join(self.cache_dir, self.key) + self.lock_path = os.path.join(self.cache_dir, "lock") + os.makedirs(self.cache_dir, exist_ok=True) + else: + raise RuntimeError("Could not create or locate cache dir") + + def _make_path(self, filename) -> str: + return os.path.join(self.cache_dir, filename) + + def has_file(self, filename) -> bool: + if not self.cache_dir: + raise RuntimeError("Could not create or locate cache dir") + return os.path.exists(self._make_path(filename)) + + def get_file(self, filename) -> Optional[str]: + if self.has_file(filename): + return self._make_path(filename) + else: + return None + + def get_group(self, filename: str) -> Optional[Dict[str, str]]: + grp_filename = f"__grp__{filename}" + if not self.has_file(grp_filename): + return None + grp_filepath = self._make_path(grp_filename) + with open(grp_filepath) as f: + grp_data = json.load(f) + child_paths = grp_data.get("child_paths", None) + # Invalid group data. + if child_paths is None: + return None + result = {} + for c, p in child_paths.items(): + if os.path.exists(p): + result[c] = p + return result + + # Note a group of pushed files as being part of a group + def put_group(self, filename: str, group: Dict[str, str]) -> str: + if not self.cache_dir: + raise RuntimeError("Could not create or locate cache dir") + grp_contents = json.dumps({"child_paths": group}) + grp_filename = f"__grp__{filename}" + return self.put(grp_contents, grp_filename, binary=False) + + def put(self, data, filename, binary=True) -> str: + if not self.cache_dir: + raise RuntimeError("Could not create or locate cache dir") + binary = isinstance(data, bytes) + if not binary: + data = str(data) + assert self.lock_path is not None + filepath = self._make_path(filename) + # Random ID to avoid any collisions + rnd_id = str(uuid.uuid4()) + # we use the PID in case a bunch of these around so we can see what PID made it + pid = os.getpid() + # use temp dir to be robust against program interruptions + temp_dir = os.path.join(self.cache_dir, f"tmp.pid_{pid}_{rnd_id}") + os.makedirs(temp_dir, exist_ok=True) + temp_path = os.path.join(temp_dir, filename) + + mode = "wb" if binary else "w" + with open(temp_path, mode) as f: + f.write(data) + # Replace is guaranteed to be atomic on POSIX systems if it succeeds + # so filepath cannot see a partial write + os.replace(temp_path, filepath) + os.removedirs(temp_dir) + return filepath + + +class RemoteCacheBackend: + """ + A backend implementation for accessing a remote/distributed cache. + """ + + def __init__(self, key: str): + pass + + @abstractmethod + def get(self, filenames: List[str]) -> Dict[str, bytes]: + pass + + @abstractmethod + def put(self, filename: str, data: bytes): + pass + + +class RedisRemoteCacheBackend(RemoteCacheBackend): + + def __init__(self, key): + import redis + self._key = key + self._key_fmt = knobs.cache.redis.key_format + self._redis = redis.Redis( + host=knobs.cache.redis.host, + port=knobs.cache.redis.port, + ) + + def _get_key(self, filename: str) -> str: + return self._key_fmt.format(key=self._key, filename=filename) + + def get(self, filenames: List[str]) -> Dict[str, str]: + results = self._redis.mget([self._get_key(f) for f in filenames]) + return {filename: result for filename, result in zip(filenames, results) if result is not None} + + def put(self, filename: str, data: bytes) -> Dict[str, bytes]: + self._redis.set(self._get_key(filename), data) + + +class RemoteCacheManager(CacheManager): + + def __init__(self, key, override=False, dump=False): + # Setup backend pointed too by `TRITON_REMOTE_CACHE_BACKEND`. + remote_cache_cls = knobs.cache.remote_manager_class + if not remote_cache_cls: + raise RuntimeError( + "Unable to instantiate RemoteCacheManager, TRITON_REMOTE_CACHE_BACKEND doesn't point to a valid class") + self._backend = remote_cache_cls(key) + + self._override = override + self._dump = dump + + # Use a `FileCacheManager` to materialize remote cache paths locally. + self._file_cache_manager = FileCacheManager(key, override=override, dump=dump) + + def _materialize(self, filename: str, data: bytes): + # We use a backing `FileCacheManager` to provide the materialized data. + return self._file_cache_manager.put(data, filename, binary=True) + + def get_file(self, filename: str) -> Optional[str]: + # We don't handle the dump/override cases. + if self._dump or self._override: + return self._file_cache_manager.get_file(filename) + + # We always check the remote cache backend -- even if our internal file- + # based cache has the item -- to make sure LRU accounting works as + # expected. + results = self._backend.get([filename]) + if len(results) == 0: + return None + (_, data), = results.items() + return self._materialize(filename, data) + + def put(self, data, filename: str, binary=True) -> str: + # We don't handle the dump/override cases. + if self._dump or self._override: + return self._file_cache_manager.put(data, filename, binary=binary) + + if not isinstance(data, bytes): + data = str(data).encode("utf-8") + self._backend.put(filename, data) + return self._materialize(filename, data) + + def get_group(self, filename: str) -> Optional[Dict[str, str]]: + # We don't handle the dump/override cases. + if self._dump or self._override: + return self._file_cache_manager.get_group(filename) + + grp_filename = f"__grp__{filename}" + grp_filepath = self.get_file(grp_filename) + if grp_filepath is None: + return None + with open(grp_filepath) as f: + grp_data = json.load(f) + child_paths = grp_data.get("child_paths", None) + + result = None + + # Found group data. + if child_paths is not None: + result = {} + for child_path, data in self._backend.get(child_paths).items(): + result[child_path] = self._materialize(child_path, data) + + return result + + def put_group(self, filename: str, group: Dict[str, str]): + # We don't handle the dump/override cases. + if self._dump or self._override: + return self._file_cache_manager.put_group(filename, group) + + grp_contents = json.dumps({"child_paths": sorted(list(group.keys()))}) + grp_filename = f"__grp__{filename}" + return self.put(grp_contents, grp_filename) + + +def _base32(key): + # Assume key is a hex string. + return base64.b32encode(bytes.fromhex(key)).decode("utf-8").rstrip("=") + + +def get_cache_manager(key) -> CacheManager: + cls = knobs.cache.manager_class or FileCacheManager + return cls(_base32(key)) + + +def get_override_manager(key) -> CacheManager: + cls = knobs.cache.manager_class or FileCacheManager + return cls(_base32(key), override=True) + + +def get_dump_manager(key) -> CacheManager: + cls = knobs.cache.manager_class or FileCacheManager + return cls(_base32(key), dump=True) + + +def make_so_cache_key(version_hash, signature, constants, ids, **kwargs): + # Get unique key for the compiled code + signature = {k: 'ptr' if v[0] == '*' else v for k, v in signature.items()} + key = f"{version_hash}-{''.join(signature.values())}-{constants}-{ids}" + for kw in kwargs: + key = f"{key}-{kwargs.get(kw)}" + key = hashlib.sha256(key.encode("utf-8")).hexdigest() + return _base32(key) + + +@functools.lru_cache() +def triton_key(): + import pkgutil + TRITON_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + contents = [] + # frontend + with open(__file__, "rb") as f: + contents += [hashlib.sha256(f.read()).hexdigest()] + # compiler + path_prefixes = [ + (os.path.join(TRITON_PATH, "compiler"), "triton.compiler."), + (os.path.join(TRITON_PATH, "backends"), "triton.backends."), + ] + for path, prefix in path_prefixes: + for lib in pkgutil.walk_packages([path], prefix=prefix): + with open(lib.module_finder.find_spec(lib.name).origin, "rb") as f: + contents += [hashlib.sha256(f.read()).hexdigest()] + + # backend + libtriton_hash = hashlib.sha256() + ext = sysconfig.get_config_var("EXT_SUFFIX").split(".")[-1] + with open(os.path.join(TRITON_PATH, "_C", f"libtriton.{ext}"), "rb") as f: + while True: + chunk = f.read(1024**2) + if not chunk: + break + libtriton_hash.update(chunk) + contents.append(libtriton_hash.hexdigest()) + # language + language_path = os.path.join(TRITON_PATH, 'language') + for lib in pkgutil.walk_packages([language_path], prefix="triton.language."): + with open(lib.module_finder.find_spec(lib.name).origin, "rb") as f: + contents += [hashlib.sha256(f.read()).hexdigest()] + return f'{__version__}' + '-'.join(contents) + + +def get_cache_key(src, backend, backend_options, env_vars): + key = f"{triton_key()}-{src.hash()}-{backend.hash()}-{backend_options.hash()}-{str(sorted(env_vars.items()))}" + return key diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/driver.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/driver.py new file mode 100644 index 0000000000000000000000000000000000000000..0092156792991984045e6158678ec85f74b1776a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/driver.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from ..backends import backends, DriverBase + + +def _create_driver() -> DriverBase: + active_drivers = [x.driver for x in backends.values() if x.driver.is_active()] + if len(active_drivers) != 1: + raise RuntimeError(f"{len(active_drivers)} active drivers ({active_drivers}). There should only be one.") + return active_drivers[0]() + + +class DriverConfig: + + def __init__(self) -> None: + self._default: DriverBase | None = None + self._active: DriverBase | None = None + + @property + def default(self) -> DriverBase: + if self._default is None: + self._default = _create_driver() + return self._default + + @property + def active(self) -> DriverBase: + if self._active is None: + self._active = self.default + return self._active + + def set_active(self, driver: DriverBase) -> None: + self._active = driver + + def reset_active(self) -> None: + self._active = self.default + + +driver = DriverConfig() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/errors.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..1a8046430eca0eaaada3ba0076d14d43a8ab6d94 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/errors.py @@ -0,0 +1,36 @@ +from ..errors import TritonError +from typing import Optional + + +class InterpreterError(TritonError): + + def __init__(self, error_message: Optional[str] = None): + self.error_message = error_message + + def __str__(self) -> str: + return self.error_message or "" + + +class OutOfResources(TritonError): + + def __init__(self, required, limit, name): + self.required = required + self.limit = limit + self.name = name + + def __str__(self) -> str: + return f"out of resource: {self.name}, Required: {self.required}, Hardware limit: {self.limit}. Reducing block sizes or `num_stages` may help." + + def __reduce__(self): + # this is necessary to make CompilationError picklable + return (type(self), (self.required, self.limit, self.name)) + + +class PTXASError(TritonError): + + def __init__(self, error_message: Optional[str] = None): + self.error_message = error_message + + def __str__(self) -> str: + error_message = self.error_message or "" + return f"PTXAS error: {error_message}" diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/interpreter.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/interpreter.py new file mode 100644 index 0000000000000000000000000000000000000000..aaacc9db27d138701b642ff8683b5bb6c77a074a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/interpreter.py @@ -0,0 +1,1414 @@ +from __future__ import annotations +import ast +import textwrap +import inspect +from typing import Tuple, List, Dict, Callable + +import math +import numpy as np + +import triton +import triton.language as tl +import dataclasses +from dataclasses import dataclass + +from triton.language.semantic import TritonSemantic +from triton.tools.tensor_descriptor import TensorDescriptor +from .errors import InterpreterError +from functools import partial +from .._C.libtriton import interpreter as _interpreter +from .._C.libtriton import ir as _ir + + +@dataclass +class TensorHandle: + ''' + data: numpy array + dtype: triton type, either pointer_type or scalar_type. + we don't store block_type here because the shape information is already available in the data field + attr: a dictionary of attributes + ''' + data: np.array + dtype: tl.dtype + attr: Dict = dataclasses.field(default_factory=dict) + + def __bool__(self): + return bool(self.data.all()) + + def get_element_ty(self): + dtype = self.dtype + while hasattr(dtype, "element_ty"): + dtype = dtype.element_ty + return dtype + + def clone(self): + return TensorHandle(self.data.copy(), self.dtype) + + def set_attr(self, key, value): + self.attr[key] = value + + +class BlockPointerHandle: + + def __init__(self, base, shape, strides, offsets, block_shape, order): + self.base = base + self.shape = shape + self.strides = strides + self.offsets = offsets + self.block_shape = block_shape + self.order = order + + def materialize_pointers(self, boundary_check): + dtype_tt = self.base.get_element_ty() + n_bytes = dtype_tt.primitive_bitwidth // 8 + ptrs = np.broadcast_to(self.base.data, self.block_shape) + masks = np.ones(self.block_shape, dtype=bool) + for dim in range(len(self.block_shape)): + bcast_dims = [1] * len(self.block_shape) + bcast_dims[dim] = self.block_shape[dim] + off = (self.offsets[dim].data + np.arange(self.block_shape[dim])).reshape(bcast_dims) + ptrs = ptrs + (n_bytes * off * self.strides[dim].data).astype(np.uint64) + if dim in boundary_check: + masks = masks & (off < self.shape[dim].data) & (off >= 0) + ptrs = TensorHandle(ptrs, self.base.dtype.scalar) + return ptrs, masks + + +class TensorDescHandle: + + def __init__(self, base: TensorHandle, shape: List[TensorHandle], strides: List[TensorHandle], + block_shape: List[int], padding): + self.base = base + self.ndim = len(shape) + self.shape = shape + self.strides = strides + self.block_shape = block_shape + self.padding = padding + + def validate(self): + assert self.base.data.item() % 16 == 0, "base must be 16-byte aligned" + assert len(self.strides) == self.ndim + assert len(self.block_shape) == self.ndim + assert self.ndim >= 1, "descriptor cannot be 0 dimensional" + + for stride in self.strides[:-1]: + assert stride.data.item() % 16 == 0, "stride must be 16-byte aligned" + assert self.strides[-1].data.item() == 1, "last dim must be contiguous" + + def materialize_pointers(self, offsets: List[TensorHandle]): + assert len(offsets) == self.ndim + scalar_ty = self.base.dtype.element_ty + itemsize = scalar_ty.primitive_bitwidth // 8 + assert (offsets[-1].data * itemsize) % 16 == 0, "block offset start must be 16-byte aligned" + + ptrs = np.broadcast_to(self.base.data, self.block_shape) + masks = np.ones(self.block_shape, dtype=bool) + for dim in range(len(self.block_shape)): + bcast_dims = [1] * len(self.block_shape) + bcast_dims[dim] = self.block_shape[dim] + off = (offsets[dim].data + np.arange(self.block_shape[dim])).reshape(bcast_dims) + ptrs = ptrs + (itemsize * off * self.strides[dim].data).astype(np.uint64) + masks = masks & (0 <= off) & (off < self.shape[dim].data) + assert ptrs.dtype == np.uint64 + ptrs = TensorHandle(ptrs, self.base.dtype.scalar) + return ptrs, masks + + +@dataclass(frozen=True) +class InterpreterOptions: + extern_libs: dict = None + debug: bool = False + sanitize_overflow: bool = True + arch: str = None + supported_fp8_dtypes: Tuple[str] = ("fp8e5", "fp8e5b16", "fp8e4nv", "fp8e4b8", "fp8e4b15") + deprecated_fp8_dot_operand_dtypes: Tuple[str] = () + default_dot_input_precision: str = "tf32" + allowed_dot_input_precisions: Tuple[str] = ("tf32", "tf32x3", "ieee") + max_num_imprecise_acc_default: int = 0 + backend_name: str = "interpreter" + + +def _get_signed_np_dtype(dtype): + if dtype == np.uint8: + return np.int8 + if dtype == np.uint16: + return np.int16 + if dtype == np.uint32: + return np.int32 + if dtype == np.uint64: + return np.int64 + return dtype + + +def _get_np_dtype(tt_dtype): + if isinstance(tt_dtype, tl.pointer_type): + return np.dtype(np.uint64) + np_types = { + tl.int1: np.dtype(bool), + tl.float16: np.dtype(np.float16), + tl.float32: np.dtype(np.float32), + tl.float64: np.dtype(np.float64), + tl.int8: np.dtype(np.int8), + tl.uint8: np.dtype(np.uint8), + tl.int16: np.dtype(np.int16), + tl.uint16: np.dtype(np.uint16), + tl.int32: np.dtype(np.int32), + tl.uint32: np.dtype(np.uint32), + tl.int64: np.dtype(np.int64), + tl.uint64: np.dtype(np.uint64), + # bfloat16 types are stored as uint16 + tl.bfloat16: np.dtype(np.uint16), + # float8 types are stored as uint8 + tl.float8e5: np.dtype(np.uint8), + tl.float8e5b16: np.dtype(np.uint8), + tl.float8e4nv: np.dtype(np.uint8), + tl.float8e4b8: np.dtype(np.uint8), + tl.float8e4b15: np.dtype(np.uint8), + } + if isinstance(tt_dtype, tl.block_type): + if isinstance(tt_dtype.element_ty, tl.pointer_type): + return np.dtype(np.uint64) + return np_types[tt_dtype.element_ty] + return np_types[tt_dtype] + + +def _convert_float(input, input_dtype, output_dtype, rounding_mode): + input_uint_dtype = getattr(np, f"uint{input_dtype.primitive_bitwidth}") + output_unint_dtype = getattr(np, f"uint{output_dtype.primitive_bitwidth}") + input_bin = np.frombuffer(input.tobytes(), dtype=input_uint_dtype) + sign = (input_bin >> (input_dtype.primitive_bitwidth - 1)) & 0x01 + input_exponent_width = input_dtype.primitive_bitwidth - input_dtype.fp_mantissa_width - 1 + output_exponent_width = output_dtype.primitive_bitwidth - output_dtype.fp_mantissa_width - 1 + significand = input_bin & ((1 << input_dtype.fp_mantissa_width) - 1) + bias_input = input_dtype.exponent_bias + bias_output = output_dtype.exponent_bias + exponent = ((input_bin >> input_dtype.fp_mantissa_width) & ((1 << input_exponent_width) - 1)).astype(np.int32) + subnormal_index = exponent == 0 + if np.any(subnormal_index): + # Credit to Phil: phil@openai.com + # subnormal repr: ((-1.0)**sign) * (2.0**(1 - exp_bias)) * (2^(m0) + 2^(m1) + ... + 2^(mn)) + # where m0, m1, ..., mn are the 1-bit of the mantissa + # convert it to normal repr: ((-1.0)**sign) * (2.0**(1 + m0 - exp_bias)) * (1 + 2^(m1 - m0) + ... + 2^(mn - m0)) + bit_pos = np.zeros_like(input_bin, dtype=np.int32) + # Find the most significant bit of the mantissa in the significand + for i in range(input_dtype.fp_mantissa_width): + bit_index = ((significand >> i) & 0x01) + # pos should be >= 1 + bit_pos[bit_index == 1] = input_dtype.fp_mantissa_width - i + zero_significand_index = significand == 0 + exponent[subnormal_index] = 1 - bit_pos[subnormal_index] + # 0 significand and subnormal should be treated as 0 + exponent[zero_significand_index & subnormal_index] = bias_input - bias_output + significand[subnormal_index] = (significand[subnormal_index] << bit_pos[subnormal_index]) & ( + (1 << input_dtype.fp_mantissa_width) - 1) + # Prevent overflow and underflow + exponent_output = np.maximum(0, np.minimum((exponent - bias_input + bias_output), (1 << output_exponent_width) - 1)) + exponent_output = exponent_output.astype(output_unint_dtype) + sign_output = sign.astype(output_unint_dtype) + if input_dtype.primitive_bitwidth > output_dtype.primitive_bitwidth: # Downcast + significand_output = (significand >> (input_dtype.fp_mantissa_width - output_dtype.fp_mantissa_width)) & ( + (1 << output_dtype.fp_mantissa_width) - 1) + if rounding_mode == _ir.ROUNDING_MODE.RTNE: # Round to nearst even + # find the cut-off bit + cut_off = significand & (1 << (input_dtype.fp_mantissa_width - output_dtype.fp_mantissa_width - 1)) + significand_output = significand_output + (cut_off > 0) + significand_output = significand_output.astype(output_unint_dtype) + else: # Upcast + significand_output = (significand.astype(output_unint_dtype) << + (output_dtype.fp_mantissa_width - input_dtype.fp_mantissa_width)) & ( + (1 << output_dtype.fp_mantissa_width) - 1) + subnormal_index = exponent_output == 0 + if np.any(subnormal_index): # underflow + # normal repr: ((-1.0)**sign) * (2.0**(exp - exp_bias_input)) * (1 + 2^(m0) + 2^(m1) + ... + 2^(mn)) + # where m0, m1, ..., mn are the 1-bit of the mantissa + # shift = (1 - exp_bias_output) - (exp - exp_bias_input) + # convert it to subnormal repr: ((-1.0)**sign) * (2.0**(1 - exp_bias_output)) * (2^(-shift) + 2^(m0 - shift) + 2^(m1 - shift) + ... + 2^(mn - shift)) + exponent = ((input_bin >> input_dtype.fp_mantissa_width) & ((1 << input_exponent_width) - 1)).astype(np.int32) + non_zero_exponent_index = exponent != 0 + # If the original exponent is not zero, we still need to shift the significand and consider the 1.0 part in mantissa + subnormal_index = subnormal_index & non_zero_exponent_index + shift = np.zeros_like(input_bin, dtype=np.int32) + shift[subnormal_index] = (1 - bias_output) - (exponent[subnormal_index] - bias_input) + significand_output[subnormal_index] = (significand_output[subnormal_index] >> shift[subnormal_index]) | ( + 1 << (output_dtype.fp_mantissa_width - shift[subnormal_index])) + output = (sign_output << (output_dtype.primitive_bitwidth - 1)) | ( + exponent_output << output_dtype.fp_mantissa_width) | significand_output + return output.reshape(input.shape) + + +def _erf(x): + # Numpy does not support erf + return math.erf(x) + + +def _umulhi_64(a, b): + # Numpy does not support 128-bit multiplication + # So we have to implement it manually + return (int(a) * int(b)) >> 64 + + +np_erf_fp32 = np.vectorize(_erf, otypes=[np.float32]) +np_erf_fp64 = np.vectorize(_erf, otypes=[np.float64]) +np_umulhi_u64 = np.vectorize(_umulhi_64, otypes=[np.uint64]) + + +class ExtraFunctions: + + @staticmethod + def _convert_custom_types(input, dst_ty, fp_downcast_rounding, _semantic): + return tl.tensor(_semantic.builder.create_fp_to_fp(input.handle, dst_ty, fp_downcast_rounding), dst_ty) + + +class InterpreterBuilder: + ir_sem_to_interpreter_sem = { + _ir.MEM_SEMANTIC.ACQUIRE: _interpreter.MEM_SEMANTIC.ACQUIRE, + _ir.MEM_SEMANTIC.RELEASE: _interpreter.MEM_SEMANTIC.RELEASE, + _ir.MEM_SEMANTIC.RELAXED: _interpreter.MEM_SEMANTIC.RELAXED, + _ir.MEM_SEMANTIC.ACQUIRE_RELEASE: _interpreter.MEM_SEMANTIC.ACQUIRE_RELEASE, + } + + ir_rmw_op_to_interpreter_rmw_op = { + _ir.ATOMIC_OP.ADD: _interpreter.RMW_OP.ADD, + _ir.ATOMIC_OP.FADD: _interpreter.RMW_OP.FADD, + _ir.ATOMIC_OP.MIN: _interpreter.RMW_OP.MIN, + _ir.ATOMIC_OP.UMIN: _interpreter.RMW_OP.UMIN, + _ir.ATOMIC_OP.MAX: _interpreter.RMW_OP.MAX, + _ir.ATOMIC_OP.UMAX: _interpreter.RMW_OP.UMAX, + _ir.ATOMIC_OP.AND: _interpreter.RMW_OP.AND, + _ir.ATOMIC_OP.OR: _interpreter.RMW_OP.OR, + _ir.ATOMIC_OP.XOR: _interpreter.RMW_OP.XOR, + _ir.ATOMIC_OP.XCHG: _interpreter.RMW_OP.XCHG, + } + + def __init__(self) -> None: + self.arch = None + self.options = InterpreterOptions() + self.codegen_fns = {} + self.codegen_fns["convert_custom_types"] = ExtraFunctions._convert_custom_types + self.codegen_fns["min_dot_size"] = lambda lhsType, rhsType: (1, 1, 1) + + def set_grid_idx(self, x, y, z): + if not x < self.grid_dim[0]: + raise ValueError("x >= grid_dim[0]") + if not y < self.grid_dim[1]: + raise ValueError("y >= grid_dim[1]") + if not z < self.grid_dim[2]: + raise ValueError("z >= grid_dim[2]") + self.grid_idx = (x, y, z) + + def set_grid_dim(self, nx, ny, nz): + self.grid_dim = (nx, ny, nz) + + # constants + + def get_half_ty(self): + return tl.float16 + + def get_bf16_ty(self): + return tl.bfloat16 + + def get_float_ty(self): + return tl.float32 + + def get_double_ty(self): + return tl.float64 + + def get_int1_ty(self): + return tl.int1 + + def get_int8_ty(self): + return tl.int8 + + def get_uint8_ty(self): + return tl.uint8 + + def get_int16_ty(self): + return tl.int16 + + def get_uint16_ty(self): + return tl.uint16 + + def get_int32_ty(self): + return tl.int32 + + def get_uint32_ty(self): + return tl.uint32 + + def get_int64_ty(self): + return tl.int64 + + def get_uint64_ty(self): + return tl.uint64 + + def get_fp8e4nv_ty(self): + return tl.float8e4nv + + def get_fp8e4b15_ty(self): + return tl.float8e4b15 + + def get_fp8e4b8_ty(self): + return tl.float8e4b8 + + def get_fp8e5_ty(self): + return tl.float8e5 + + def get_fp8e5b16_ty(self): + return tl.float8e5b16 + + def get_ptr_ty(self, elt_ty, addr_space): + return tl.pointer_type(elt_ty, addr_space) + + def get_block_ty(self, dtype, shape): + return tl.block_type(dtype, shape) + + def get_int1(self, value): + return TensorHandle(np.array([value], dtype=np.bool_), tl.int1) + + def get_uint8(self, value): + return TensorHandle(np.array([value], dtype=np.uint8), tl.uint8) + + def get_int8(self, value): + return TensorHandle(np.array([value], dtype=np.int8), tl.int8) + + def get_uint16(self, value): + return TensorHandle(np.array([value], dtype=np.uint16), tl.uint16) + + def get_int16(self, value): + return TensorHandle(np.array([value], dtype=np.int16), tl.int16) + + def get_uint32(self, value): + return TensorHandle(np.array([value], dtype=np.uint32), tl.uint32) + + def get_int32(self, value): + return TensorHandle(np.array([value], dtype=np.int32), tl.int32) + + def get_uint64(self, value): + return TensorHandle(np.array([value], dtype=np.uint64), tl.uint64) + + def get_int64(self, value): + return TensorHandle(np.array([value], dtype=np.int64), tl.int64) + + def get_fp16(self, value): + return TensorHandle(np.array([value], dtype=np.float16), tl.float16) + + def get_fp32(self, value): + return TensorHandle(np.array([value], dtype=np.float32), tl.float32) + + def get_fp64(self, value): + return TensorHandle(np.array([value], dtype=np.float64), tl.float64) + + def get_null_value(self, type): + return TensorHandle(np.array([0], dtype=_get_np_dtype(type)), type) + + # programming model + def create_get_program_id(self, axis): + if self.grid_idx is None: + raise ValueError("grid_idx is None") + return TensorHandle(np.array([self.grid_idx[axis]], dtype=np.int32), tl.int32) + + def create_get_num_programs(self, axis): + return TensorHandle(np.array([self.grid_dim[axis]], dtype=np.int32), tl.int32) + + # memory ops + def create_load(self, ptr, _0, _1, is_volatile): + mask = TensorHandle(np.ones_like(ptr.data, dtype=bool), tl.int1) + other = None + return self.create_masked_load(ptr, mask, other, _0, _1, is_volatile) + + def create_store(self, ptr, val, _0, _1): + mask = TensorHandle(np.ones_like(ptr.data, dtype=bool), tl.int1) + return self.create_masked_store(ptr, val, mask, None, None) + + def create_masked_load(self, ptrs, mask, other, cache_modifier, eviction_policy, is_volatile): + dtype_tt = ptrs.get_element_ty() + dtype_np = _get_np_dtype(dtype_tt) + if other is None: + other = TensorHandle(np.zeros_like(ptrs.data, dtype=dtype_np), dtype_tt) + ret = _interpreter.load(ptrs.data, mask.data, other.data, dtype_np) + return TensorHandle(ret, dtype_tt) + + def create_masked_store(self, ptrs, value, mask, cache_modifier, eviction_policy): + return _interpreter.store(ptrs.data, value.data, mask.data) + + # casting ops + def cast_impl(self, src, dst_type): + src_element_type = src.dtype.scalar + dst_element_type = dst_type.scalar + if (src_element_type == tl.bfloat16 and dst_element_type == tl.float32) or \ + (src_element_type == tl.float32 and dst_element_type == tl.bfloat16): + data = _convert_float(src.data, src_element_type, dst_element_type, None).view(_get_np_dtype(dst_type)) + return TensorHandle(data, dst_type.scalar) + else: + return TensorHandle(src.data.astype(_get_np_dtype(dst_type)), dst_type.scalar) + + create_si_to_fp = lambda self, src, dst_type: self.cast_impl(src, dst_type) + create_ui_to_fp = lambda self, src, dst_type: self.cast_impl(src, dst_type) + create_fp_to_si = lambda self, src, dst_type: self.cast_impl(src, dst_type) + create_fp_to_ui = lambda self, src, dst_type: self.cast_impl(src, dst_type) + create_fp_ext = lambda self, src, dst_type: self.cast_impl(src, dst_type) + create_fp_trunc = lambda self, src, dst_type: self.cast_impl(src, dst_type) + create_int_cast = lambda self, src, dst_type, is_signed: self.cast_impl(src, dst_type) + + def create_fp_to_fp(self, src, dst_type, rounding_mode): + src_element_type = src.dtype.scalar + dst_element_type = dst_type.scalar + data = _convert_float(src.data, src_element_type, dst_element_type, rounding_mode).view(_get_np_dtype(dst_type)) + return TensorHandle(data, dst_type.scalar) + + def create_bitcast(self, src, dst_type): + return TensorHandle(src.data.view(_get_np_dtype(dst_type)), dst_type.scalar) + + # binary operators + def binary_op(self, lhs, rhs, op): + return TensorHandle(op(lhs.data, rhs.data), lhs.dtype.scalar) + + create_fadd = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.add) + create_fmul = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.multiply) + create_fdiv = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.divide) + create_frem = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.fmod) + create_fsub = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.subtract) + create_mul = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.multiply) + create_precise_divf = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.divide) + create_sdiv = lambda self, lhs, rhs: self.create_idiv(lhs, rhs) + create_udiv = lambda self, lhs, rhs: self.create_idiv(lhs, rhs) + # LLVM has 'numpy.fmod', not 'numpy.remainder', semantics on integer remainders. + create_srem = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.fmod) + create_urem = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.fmod) + create_add = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.add) + create_sub = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.subtract) + create_shl = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.left_shift) + create_lshr = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.right_shift) + create_minsi = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.minimum) + create_minui = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.minimum) + create_minimumf = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.minimum) + create_minnumf = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.minimum) + create_maxsi = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.maximum) + create_maxui = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.maximum) + create_maximumf = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.maximum) + create_maxnumf = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.maximum) + create_icmpSLE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less_equal) + create_icmpSLT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less) + create_icmpSGE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater_equal) + create_icmpSGT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater) + create_icmpULE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less_equal) + create_icmpULT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less) + create_icmpUGE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater_equal) + create_icmpUGT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater) + create_icmpEQ = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.equal) + create_icmpNE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.not_equal) + create_fcmpOLT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less) + create_fcmpOGT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater) + create_fcmpOLE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less_equal) + create_fcmpOGE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater_equal) + create_fcmpOEQ = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.equal) + create_fcmpONE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.not_equal) + create_fcmpULT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less) + create_fcmpUGT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater) + create_fcmpULE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less_equal) + create_fcmpUGE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater_equal) + create_fcmpUEQ = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.equal) + create_fcmpUNE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.not_equal) + create_and = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.bitwise_and) + create_xor = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.bitwise_xor) + create_or = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.bitwise_or) + create_int_to_ptr = create_bitcast + create_ptr_to_int = create_bitcast + + def create_idiv(self, lhs, rhs): + # Triton has IEEE, not numpy/torch, semantics for %, and those carry + # through to //, so we have to use a nonstandard expression to get a + # reference result for //. + return TensorHandle((lhs.data - np.fmod(lhs.data, rhs.data)) // rhs.data, lhs.dtype.scalar) + + def create_ashr(self, lhs, rhs): + # Triton's rshift operator depends on the signedness of the left operand + lhs_dtype = _get_signed_np_dtype(lhs.data.dtype) + rhs_dtype = _get_signed_np_dtype(rhs.data.dtype) + lhs.data = lhs.data.astype(lhs_dtype) + rhs.data = rhs.data.astype(rhs_dtype) + return self.binary_op(lhs, rhs, np.right_shift) + + def create_umulhi(self, lhs, rhs): + dtype = lhs.data.dtype + if dtype == np.int64 or dtype == np.uint64: + return TensorHandle(np_umulhi_u64(lhs.data, rhs.data), lhs.dtype.scalar) + else: + compute_dtype = getattr(np, f"uint{dtype.itemsize * 8 * 2}") + lhs_data = lhs.data.astype(compute_dtype) + rhs_data = rhs.data.astype(compute_dtype) + ret_data = np.multiply(lhs_data, rhs_data) >> (dtype.itemsize * 8) + return TensorHandle(ret_data.astype(dtype), lhs.dtype.scalar) + + # ternary functions + def ternary_op(self, lhs, rhs, other, op): + return TensorHandle(op(lhs.data, rhs.data, other.data), other.dtype.scalar) + + create_clampf = lambda self, arg, lo, hi, propagate_nans: self.ternary_op(arg, lo, hi, np.clip) + create_select = lambda self, cond, lhs, rhs: self.ternary_op(cond, lhs, rhs, np.where) + + def create_fma(self, x, y, z): + return TensorHandle(x.data * y.data + z.data, z.dtype.scalar) + + # unary functions + def unary_op(self, arg, op): + return TensorHandle(op(arg.data), arg.dtype.scalar) + + def create_fabs(self, arg): + # Mask out the sign bit based on the primitive length + dtype_tt = arg.dtype + mask_bitwidth = dtype_tt.primitive_bitwidth - 1 + np_uint_dtype = getattr(np, f"uint{dtype_tt.primitive_bitwidth}") + data = arg.data.view(np_uint_dtype) + mask = (1 << mask_bitwidth) - 1 + ret = (data & mask).view(_get_np_dtype(dtype_tt)) + return TensorHandle(ret, arg.dtype.scalar) + + create_cos = lambda self, arg: self.unary_op(arg, np.cos) + create_exp = lambda self, arg: self.unary_op(arg, np.exp) + create_exp2 = lambda self, arg: self.unary_op(arg, np.exp2) + create_iabs = lambda self, arg: self.unary_op(arg, np.abs) + create_floor = lambda self, arg: self.unary_op(arg, np.floor) + create_ceil = lambda self, arg: self.unary_op(arg, np.ceil) + create_log = lambda self, arg: self.unary_op(arg, np.log) + create_log2 = lambda self, arg: self.unary_op(arg, np.log2) + create_precise_sqrt = lambda self, arg: self.unary_op(arg, np.sqrt) + create_sqrt = lambda self, arg: self.unary_op(arg, np.sqrt) + create_sin = lambda self, arg: self.unary_op(arg, np.sin) + + def create_erf(self, arg): + ret = np_erf_fp32(arg.data) if arg.data.dtype == np.float32 else np_erf_fp64(arg.data) + return TensorHandle(ret, arg.dtype.scalar) + + def create_rsqrt(self, arg): + return TensorHandle(1 / np.sqrt(arg.data), arg.dtype.scalar) + + # tensor operators + create_reshape = lambda self, arg, shape, allow_reorder: TensorHandle(arg.data.reshape(shape), arg.dtype.scalar) + + def create_trans(self, arg, perm): + return TensorHandle(np.transpose(arg.data, perm), arg.dtype.scalar) + + def create_dot(self, a, b, d, input_precision, max_num_imprecise_acc): + a_data = a.data + b_data = b.data + if (a.dtype.primitive_bitwidth == 8 and a.dtype.is_floating()) or \ + (b.dtype.primitive_bitwidth == 8 and b.dtype.is_floating()): + a_data = _convert_float(a_data, a.dtype, tl.float16, None).view(np.float16) + b_data = _convert_float(b_data, b.dtype, tl.float16, None).view(np.float16) + return TensorHandle(np.matmul(a_data, b_data, dtype=d.data.dtype) + d.data, d.dtype.scalar) + + def create_make_range(self, ret_ty, start, stop): + return TensorHandle(np.arange(start, stop, dtype=np.int32), tl.int32) + + def create_histogram(self, data, bins, mask): + if mask is None: + mask = TensorHandle(np.ones_like(data.data, dtype=bool), tl.int1) + # force all masked elements to zero + data = np.where(mask.data, data.data, np.zeros_like(data.data)) + histogram = np.histogram(data, bins=bins, range=(0, bins))[0] + # remove overcounted elements + histogram[0] -= np.logical_not(mask.data).sum() + return TensorHandle(histogram, tl.int32) + + def create_gather(self, src, indices, axis): + return TensorHandle(np.take_along_axis(src.data, indices.data, axis=axis), src.dtype.scalar) + + # pointer arithmetic + + def create_addptr(self, ptr, offset): + dtype_tt = ptr.get_element_ty() + element_bitwidth = dtype_tt.primitive_bitwidth + # int1's bitwidth is 1, but we need to use 8 for pointer arithmetic + element_bytewidth = max(1, element_bitwidth // 8) + return TensorHandle(ptr.data + element_bytewidth * offset.data.astype(np.uint64), ptr.dtype) + + def create_tensor_pointer_load(self, ptr, boundary_check, padding_option, cache_modifier, eviction_policy, + is_volatile): + ptrs, masks = ptr.materialize_pointers(boundary_check) + dtype_tt = ptrs.get_element_ty() + dtype_np = _get_np_dtype(dtype_tt) + if padding_option is None: + other = None + elif padding_option == _ir.PADDING_OPTION.PAD_ZERO: + other = TensorHandle(np.zeros_like(ptrs.data, dtype=dtype_np), dtype_tt) + elif padding_option == _ir.PADDING_OPTION.PAD_NAN: + other = TensorHandle(np.full_like(ptrs.data, float('nan'), dtype=dtype_np), dtype_tt) + else: + raise ValueError(f"unsupported padding option {padding_option}") + return self.create_masked_load(ptrs, masks, other, cache_modifier, eviction_policy, is_volatile) + + def create_tensor_pointer_store(self, ptr, value, boundary_check, cache_modifier, eviction_policy): + ptrs, masks = ptr.materialize_pointers(boundary_check) + return self.create_masked_store(ptrs, value, masks, cache_modifier, eviction_policy) + + def create_expand_dims(self, arg, axis): + return TensorHandle(np.expand_dims(arg.data, axis), arg.dtype.scalar) + + def create_broadcast(self, arg, shape): + return TensorHandle(np.broadcast_to(arg.data, shape), arg.dtype.scalar) + + def create_cat(self, lhs, rhs): + return TensorHandle(np.concatenate([lhs.data, rhs.data]), lhs.dtype.scalar) + + def create_join(self, lhs, rhs): + # Triton only supports joining two original tensors into a new one along the last axis + return TensorHandle(np.stack([lhs.data, rhs.data], axis=-1), lhs.dtype.scalar) + + def create_split(self, val): + # Triton only supports splitting the original tensor into two along the last axis + return (TensorHandle(val.data[..., 0], val.dtype.scalar), TensorHandle(val.data[..., 1], val.dtype.scalar)) + + def create_splat(self, ret_ty, arg): + shape = ret_ty.shape + if isinstance(arg.dtype, tl.block_type): + return TensorHandle(np.full(shape, arg.data[0], dtype=_get_np_dtype(arg.dtype)), arg.dtype.scalar) + else: # scalar + return TensorHandle(np.full(shape, arg.data, dtype=_get_np_dtype(arg.dtype)), arg.dtype.scalar) + + def create_unsplat(self, arg): + return TensorHandle(np.full((1, ), arg.data[0], dtype=_get_np_dtype(arg.dtype)), arg.dtype.scalar) + + def create_atomic_cas(self, ptr, cmp, val, sem, scope): + if sem not in self.ir_sem_to_interpreter_sem: + raise ValueError(f"unsupported semantic {sem}") + sem = self.ir_sem_to_interpreter_sem[sem] + return TensorHandle(_interpreter.atomic_cas(ptr.data, cmp.data, val.data, sem), cmp.dtype.scalar) + + def create_atomic_rmw(self, rmwOp, ptr, val, mask, sem, scope): + if rmwOp not in self.ir_rmw_op_to_interpreter_rmw_op: + raise ValueError(f"unsupported rmwOp {rmwOp}") + if sem not in self.ir_sem_to_interpreter_sem: + raise ValueError(f"unsupported semantic {sem}") + rmwOp = self.ir_rmw_op_to_interpreter_rmw_op[rmwOp] + sem = self.ir_sem_to_interpreter_sem[sem] + return TensorHandle(_interpreter.atomic_rmw(rmwOp, ptr.data, val.data, mask.data, sem), val.dtype.scalar) + + def create_extern_elementwise(self, libName, libPath, symbol, argList, retType, isPure): + raise NotImplementedError("extern_elementwise not supported in interpreter mode") + + def create_inline_asm(self, inlineAsm, constraints, values, type, isPure, pack): + raise NotImplementedError("inline_asm not supported in interpreter mode") + + def create_print(self, prefix, hex, values, isSigned): + # NOTE: the `isSigned` variable is not really used here; because Signness is already known + # by `values` themselves in python interpreter, thus not really needed here; + # it is only used for triton PrintOpToLLVM to correctly construct the format specifier. + # Interpreter's device_print function has a different format than Triton's device_print + msg = f"({self.grid_idx[0]}, {self.grid_idx[1]}, {self.grid_idx[2]})" + if prefix: + msg += f" {prefix}" + if hex: + np.set_printoptions(formatter={'all': lambda x: f"0x{x:02x}"}) + for value in values: + print(msg + f" {value.data}") + if hex: + np.set_printoptions(formatter=None) + + def create_assert(self, condition, message): + # Interpreter's device_assert function has a different format than Triton's device_assert + assert condition, f"{message}" + + def create_assume(self, condition): + assert condition, "Assume failed" + + def create_barrier(self): + # Triton's barrier applies to each program in a grid, so it's a no-op in the interpreter + pass + + def create_make_block_ptr(self, base, shape, strides, offsets, block_shape, order): + # Create new offsets to avoid modifying the original + new_offsets = [offset.clone() for offset in offsets] + return BlockPointerHandle(base, shape, strides, new_offsets, block_shape, order) + + def create_advance(self, ptr, offsets): + if len(ptr.offsets) != len(offsets): + raise ValueError("len(ptr.offsets) != len(offsets)") + # Create new offsets to avoid modifying the original + new_offsets = [offset.clone() for offset in ptr.offsets] + ret = BlockPointerHandle(ptr.base, ptr.shape, ptr.strides, new_offsets, ptr.block_shape, ptr.order) + for i in range(len(offsets)): + ret.offsets[i].data += offsets[i].data + return ret + + def create_make_tensor_descriptor(self, base: TensorHandle, shape: List[TensorHandle], strides: List[TensorHandle], + tensor_shape: List[int], is_signed: bool, padding: str = "zero"): + desc = TensorDescHandle(base, shape, strides, tensor_shape, padding) + desc.validate() + return desc + + def create_descriptor_load(self, desc: TensorDescHandle, indices: List[TensorHandle], cache_modifier, + eviction_policy): + assert isinstance(desc, TensorDescHandle) + ptrs, mask = desc.materialize_pointers(indices) + dtype_tt = ptrs.get_element_ty() + dtype_np = _get_np_dtype(dtype_tt) + padding = desc.padding + if padding == _ir.PADDING_OPTION.PAD_ZERO: + other = TensorHandle(np.zeros_like(ptrs.data, dtype=dtype_np), dtype_tt) + elif padding == _ir.PADDING_OPTION.PAD_NAN: + other = TensorHandle(np.full_like(ptrs.data, float('nan'), dtype=dtype_np), dtype_tt) + else: + raise ValueError(f"unsupported padding {padding}") + return self.create_masked_load(ptrs, mask, other, cache_modifier=cache_modifier, + eviction_policy=eviction_policy, is_volatile=False) + + def create_descriptor_store(self, desc: TensorDescHandle, value: TensorHandle, indices: List[TensorHandle]): + ptrs, mask = desc.materialize_pointers(indices) + return self.create_masked_store(ptrs, value, mask, None, None) + + def create_descriptor_gather(self, desc: TensorDescHandle, x_offsets: TensorHandle, y_offset: TensorHandle, type): + dtype = desc.base.dtype.element_ty + np_dtype = _get_np_dtype(dtype) + result = np.zeros([x_offsets.data.shape[0], desc.block_shape[-1]], dtype=np_dtype) + cache_modifier = None + eviction_policy = None + for i, x_offset in enumerate(x_offsets.data): + indices = [TensorHandle(x_offset, tl.int32), y_offset] + result[i, :] = self.create_descriptor_load(desc, indices, cache_modifier, eviction_policy).data + return TensorHandle(result, dtype) + + def create_descriptor_scatter(self, desc: TensorDescHandle, value: TensorHandle, x_offsets: TensorHandle, + y_offset: TensorHandle): + for i, x_offset in enumerate(x_offsets.data): + slice = TensorHandle(value.data[i], value.dtype) + indices = [TensorHandle(x_offset, tl.int32), y_offset] + self.create_descriptor_store(desc, slice, indices) + + def get_all_ones_value(self, type): + np_type = _get_np_dtype(type) + if "int" in np_type.name: + return TensorHandle(np.full(1, -1, dtype=np_type), type.scalar) + elif np_type == np.bool_: + return TensorHandle(np.full(1, True, dtype=np_type), type.scalar) + else: + raise TypeError(f"unsupported type {type}") + + +def _patch_attr(obj, name, member, builder): + semantic = TritonSemantic(builder) + new_member = lambda *args, member=member, **kwargs: (member(*args, ** + {k: v + for k, v in kwargs.items() + if k != "_semantic"}, _semantic=semantic)) + setattr(obj, name, new_member) + + +def _patch_builtin(pkg, builder): + for name, member in inspect.getmembers(pkg): + if tl.core.is_builtin(member): + _patch_attr(pkg, name, member, builder) + + +def _patch_lang_tensor(tensor): + + def _get_bool(self): + data = self.handle.data + # in triton, only scalars can be converted to booleans + # here we need this hack because all scalars are tensors + return bool(data) if data.size == 1 else True + + def _get_transpose(self): + handle = TensorHandle(np.transpose(self.handle.data), self.handle.dtype) + assert self.type.is_block() + block_shape = list(self.type.shape) + block_shape[-1], block_shape[-2] = block_shape[-2], block_shape[-1] + res_ty = tl.core.block_type(self.dtype, block_shape) + return tl.core.tensor(handle, res_ty) + + tensor.__index__ = lambda self: int(self.handle.data) + tensor.__bool__ = lambda self: _get_bool(self) + tensor.__repr__ = lambda self: repr(self.handle.data) + tensor.__str__ = lambda self: str(self.handle.data) + tensor.T = property(_get_transpose) + + +class ReduceScanOpInterface: + + def __init__(self, axis, combine_fn): + self.axis = axis + self.combine_fn = combine_fn + + def check_axis(self, shape, axis): + if axis is not None and axis >= len(shape): + raise ValueError(f"axis {axis} out of bounds for shape {shape}") + + def check_tensor(self, input): + for arg in input: + if not isinstance(arg, tl.core.tensor): + raise ValueError(f"input must be a tensor, got {type(arg)}") + self.check_axis(arg.shape, self.axis) + + def to_tensor(self, ret, dtype): + np_dtype = _get_np_dtype(dtype) + if hasattr(ret, "shape") and ret.shape: + ret = ret.astype(np_dtype) + ret_type = tl.block_type(dtype, list(ret.shape)) + else: + ret = np.array([ret], dtype=np_dtype) + ret_type = dtype + return tl.core.tensor(TensorHandle(ret, dtype.scalar), ret_type) + + def apply(self, input): + if not isinstance(input, tuple): + return self.apply((input, ))[0] + self.check_tensor(input) + ret = self.apply_impl(input) + return tuple(ret) if isinstance(ret, (list, tuple)) else (ret, ) + + +class ReduceOps(ReduceScanOpInterface): + + def __init__(self, axis, combine_fn, keep_dims): + super().__init__(axis, combine_fn) + self.keep_dims = keep_dims + + def unravel(self, input, axis): + ret = [] + for data in input: + if axis is not None: + ret.append(data) + else: + axis = 0 + ret.append(self.to_tensor(data.handle.data.flatten(), data.dtype)) + return tuple(ret), axis + + def generic_reduce(self, input): + original_axis = self.axis + input, axis = self.unravel(input, self.axis) + input_data = [] + output_data = [] + input_shape = input[0].handle.data.shape + output_shape = input_shape[0:axis] + input_shape[axis + 1:] + for arg in input: + input_data.append(arg.handle.data) + output_data.append(np.zeros(output_shape, dtype=arg.handle.data.dtype)) + # Reduce on axis + for i in range(input_data[0].size): + # Recover input_index from i using input_shape + input_index = np.unravel_index(i, input_shape) + output_index = input_index[0:axis] + input_index[axis + 1:] + input_tuple = tuple(self.to_tensor(d[input_index], input[ii].dtype) for ii, d in enumerate(input_data)) + if input_index[axis] == 0: + # First element + for j in range(len(output_data)): + output_data[j][output_index] = input_tuple[j].handle.data.item() + else: + acc_tuple = tuple(self.to_tensor(o[output_index], input[oi].dtype) for oi, o in enumerate(output_data)) + combine_fn_ret = self.combine_fn.fn(*acc_tuple, *input_tuple) + acc_tuple = (combine_fn_ret, ) if not isinstance(combine_fn_ret, tuple) else combine_fn_ret + for j in range(len(output_data)): + output_data[j][output_index] = acc_tuple[j].handle.data.item() if isinstance( + acc_tuple[j], tl.core.tensor) else acc_tuple[j] + # Pack output + ret = [] + for i, data in enumerate(output_data): + if self.keep_dims: + if original_axis is not None: + data = np.expand_dims(data, axis) + else: + for _ in range(len(input_shape)): + data = np.expand_dims(data, 0) + + elif original_axis is None: + # Take a scalar + data = data.item() + ret.append(self.to_tensor(data, input[i].dtype)) + return ret + + def min_max(self, input, val_reduce_op, idx_reduce_op=None): + # If input is a tuple, it must be (val, index), and we only take val + input = input[0] if isinstance(input, tuple) else input + val = None + idx = None + if val_reduce_op: + val = self.to_tensor(val_reduce_op(input.handle.data, axis=self.axis, keepdims=self.keep_dims), input.dtype) + if idx_reduce_op: + idx = self.to_tensor(idx_reduce_op(input.handle.data, axis=self.axis, keepdims=self.keep_dims), tl.int32) + if val is not None and idx is not None: + return val, idx + elif val is not None: + return val + elif idx is not None: + return idx + else: + raise ValueError("val_reduce_op and idx_reduce_op are both None") + + def sum(self, input): + return self.to_tensor(np.sum(input.handle.data, axis=self.axis, keepdims=self.keep_dims), input.dtype) + + def apply_impl(self, input): + if self.combine_fn == tl.standard._argmin_combine_tie_break_left: + return self.min_max(input[0], val_reduce_op=np.min, idx_reduce_op=np.argmin) + elif self.combine_fn == tl.standard._argmax_combine_tie_break_left: + return self.min_max(input[0], val_reduce_op=np.max, idx_reduce_op=np.argmax) + elif self.combine_fn == tl.standard._elementwise_max: + return self.min_max(input[0], val_reduce_op=np.nanmax, idx_reduce_op=None) + elif self.combine_fn == tl.standard._elementwise_min: + return self.min_max(input[0], val_reduce_op=np.nanmin, idx_reduce_op=None) + elif self.combine_fn == tl.standard._sum_combine: + return self.sum(input[0]) + else: + # Fall back to the slow mode + return self.generic_reduce(input) + + +class ScanOps(ReduceScanOpInterface): + + def __init__(self, axis, combine_fn, reverse): + super().__init__(axis, combine_fn) + self.reverse = reverse + + def cumsum(self, input): + return [self.to_tensor(np.cumsum(input.handle.data, axis=self.axis), dtype=input.dtype)] + + def cumprod(self, input): + return [self.to_tensor(np.cumprod(input.handle.data, axis=self.axis), dtype=input.dtype)] + + def generic_scan(self, input): + input_data = [] + output_data = [] + shape = input[0].handle.data.shape + for arg in input: + input_data.append(arg.handle.data) + output_data.append(np.zeros(shape, dtype=arg.handle.data.dtype)) + # Scan on axis + for i in range(input_data[0].size): + # Recover index from i using shape + index = np.unravel_index(i, shape) + data = tuple(self.to_tensor(d[index], input[ii].dtype) for ii, d in enumerate(input_data)) + if index[self.axis] == 0: + # First element + for j in range(len(output_data)): + output_data[j][index] = data[j].handle.data.item() + else: + prev_index = tuple(index[i] - 1 if i == self.axis else index[i] for i in range(len(index))) + acc_tuple = tuple(self.to_tensor(o[prev_index], input[oi].dtype) for oi, o in enumerate(output_data)) + combine_fn_ret = self.combine_fn.fn(*acc_tuple, *data) + acc_tuple = (combine_fn_ret, ) if not isinstance(combine_fn_ret, tuple) else combine_fn_ret + for j in range(len(output_data)): + output_data[j][index] = acc_tuple[j].handle.data.item() if isinstance( + acc_tuple[j], tl.core.tensor) else acc_tuple[j] + # Pack output + ret = [] + for i, data in enumerate(output_data): + ret.append(self.to_tensor(data, input[i].dtype)) + return ret + + def apply_impl(self, input): + new_input = [] + if self.reverse: + for arg in input: + new_input.append(self.to_tensor(np.flip(arg.handle.data, axis=self.axis), arg.dtype)) + else: + new_input = input + if self.combine_fn == tl.standard._sum_combine: + ret = self.cumsum(new_input[0]) + elif self.combine_fn == tl.standard._prod_combine: + ret = self.cumprod(new_input[0]) + else: + # Fall back to the slow mode + ret = self.generic_scan(new_input) + if self.reverse: + for arg in ret: + arg.handle.data = np.flip(arg.handle.data, axis=self.axis) + return ret + + +def _patch_reduce_scan(): + # Because interpreter doesn't support region_builder_fn, we cannot patch the builder + # to use the new reduce and scan functions. + # Instead, we need to patch reduce and reduce functions in tl and tl.core + def _new_reduce(input, axis, combine_fn, keep_dims=False, **kwargs): + return ReduceOps(axis, combine_fn, keep_dims).apply(input) + + def _new_scan(input, axis, combine_fn, reverse=False, **kwargs): + return ScanOps(axis, combine_fn, reverse).apply(input) + + tl.reduce = _new_reduce + tl.associative_scan = _new_scan + tl.core.reduce = _new_reduce + tl.core.associative_scan = _new_scan + + +def _patch_lang_core(lang): + + def _new_to_ir(self, builder): + # We need to specify signedness for integer types in the numpy mode + if self.name == 'void': + return builder.get_void_ty() + elif self.name == 'int1': + return builder.get_int1_ty() + elif self.name == 'int8': + return builder.get_int8_ty() + elif self.name == 'uint8': + return builder.get_uint8_ty() + elif self.name == 'int16': + return builder.get_int16_ty() + elif self.name == 'uint16': + return builder.get_uint16_ty() + elif self.name == 'int32': + return builder.get_int32_ty() + elif self.name == 'uint32': + return builder.get_uint32_ty() + elif self.name == 'int64': + return builder.get_int64_ty() + elif self.name == 'uint64': + return builder.get_uint64_ty() + elif self.name == 'fp8e5': + return builder.get_fp8e5_ty() + elif self.name == 'fp8e4nv': + return builder.get_fp8e4nv_ty() + elif self.name == 'fp8e4b15': + return builder.get_fp8e4b15_ty() + elif self.name == 'fp16': + return builder.get_half_ty() + elif self.name == 'bf16': + return builder.get_bf16_ty() + elif self.name == 'fp32': + return builder.get_float_ty() + elif self.name == 'fp64': + return builder.get_double_ty() + raise ValueError(f'fail to convert {self} to ir type') + + # can't just map lang.static_range to `range`, because `tl.static_range` + # can get `step` passed by keyword + def _new_range(arg1, arg2=None, step=None, **kwargs): + if step is None: + step = 1 + if arg2 is None: + start, end = 0, arg1 + else: + start, end = arg1, arg2 + return range(start, end, step) + + def _new_static_assert(cond, msg=""): + assert cond, msg + + def _set_attr(input, values, name): + # skip non tensor types. This may happen for induction variables. + if not isinstance(input, tl.tensor): + return input + # Unwrap constexpr + values = [values] if not isinstance(values, (list, tuple)) else values + values = [v.value if isinstance(v, tl.constexpr) else v for v in values] + if len(values) != max(1, len(input.shape)): + raise ValueError(f"len(values) != len(input.shape) for {name}") + input.handle.set_attr(name, values) + return input + + lang.range = _new_range + lang.static_range = _new_range + lang.static_assert = _new_static_assert + lang.static_print = print + lang.dtype.to_ir = _new_to_ir + lang.multiple_of = partial(_set_attr, name="tt.divisibility") + lang.max_contiguous = partial(_set_attr, name="tt.contiguity") + lang.max_constancy = partial(_set_attr, name="tt.constancy") + + _patch_reduce_scan() + + +def _patch_lang(fn): + langs = [value for _, value in fn.__globals__.items() if inspect.ismodule(value) and value in [tl, tl.core]] + assert len(langs) >= 1, "triton.language must be visible from within jit'd function" + for lang in langs: + _patch_builtin(lang, interpreter_builder) + _patch_builtin(lang.tensor, interpreter_builder) + if lang == tl: + _patch_builtin(lang.math, interpreter_builder) + _patch_lang_tensor(lang.tensor) + _patch_lang_core(lang) + _patch_builtin(tl.core.tensor_descriptor_base, interpreter_builder) + + +def _tuple_create(arg, contents): + # NamedTuples and tuples have different construction semantics. NamedTuple + # has a constructor that takes individual arguments, while tuple takes an + # iterable. Both have type "tuple" making it difficult to distinguish + # between them, but only NamedTuple has "_fields" and apparently this is how + # everyone does the check. + return type(arg)(*contents) if hasattr(arg, "_fields") else type(arg)(contents) + + +# TODO: wrap everything in triton tensors +def _implicit_cvt(arg): + if isinstance(arg, int): + ty = tl.str_to_ty(triton.runtime.jit.mangle_type(arg), None) + dtype = np.int32 + if -2**31 <= arg < 2**31: + dtype = np.int32 + elif 2**31 <= arg < 2**32: + dtype = np.uint32 + elif -2**63 <= arg < 2**63: + dtype = np.int64 + elif 2**63 <= arg < 2**64: + dtype = np.uint64 + else: + raise ValueError(f"Unsupported integer value {arg}") + handle = TensorHandle(np.array([arg], dtype=dtype), ty) + return tl.tensor(handle, ty) + if hasattr(arg, "data_ptr"): + ty = tl.str_to_ty(triton.runtime.jit.mangle_type(arg), None) + handle = TensorHandle(np.array([arg.data_ptr()], dtype=np.uint64), ty) + return tl.tensor(handle, ty) + elif isinstance(arg, tuple): + return _tuple_create(arg, map(_implicit_cvt, arg)) + elif isinstance(arg, TensorDescriptor): + strides = [_implicit_cvt(s) for s in arg.strides] + assert arg.strides[-1] == 1 + strides[-1] = tl.constexpr(1) + semantic = TritonSemantic(InterpreterBuilder()) + return semantic.make_tensor_descriptor(base=_implicit_cvt(arg.base), + shape=[_implicit_cvt(s) for s in arg.shape], strides=strides, + block_shape=[tl.constexpr(b) + for b in arg.block_shape], padding_option=arg.padding) + return arg + + +interpreter_builder = InterpreterBuilder() +interpreter_semantic = TritonSemantic(interpreter_builder) + + +def _unwrap_tensor(t): + if isinstance(t, triton.runtime.jit.TensorWrapper): + return t.base + return t + + +def _rewrap_tensor(t, original_tensor): + if isinstance(original_tensor, triton.runtime.jit.TensorWrapper): + return triton.runtime.jit.TensorWrapper(t, original_tensor.dtype) + return t + + +class GridExecutor: + + def __init__(self, fn, arg_names, grid): + from .jit import _normalize_ty # TODO: modularize + + self.fn = fn + self.arg_names = arg_names + self.grid = grid + __annotations__ = {name: _normalize_ty(ty) for name, ty in fn.__annotations__.items()} + self.constexprs = [name for name in arg_names if __annotations__.get(name) == "constexpr"] + + def _init_args_hst(self, args_dev, kwargs): + storages = {} + + def _to_cpu(arg): + if isinstance(arg, tuple): + return _tuple_create(arg, map(_to_cpu, arg)) + elif isinstance(arg, TensorDescriptor): + return TensorDescriptor( + _to_cpu(arg.base), + arg.shape, + arg.strides, + arg.block_shape, + arg.padding, + ) + elif not hasattr(arg, "data_ptr"): + return arg + + unwrapped_arg = _unwrap_tensor(arg) + if unwrapped_arg.untyped_storage().data_ptr() not in storages: + storage = unwrapped_arg.untyped_storage() + storages[storage.data_ptr()] = storage.cpu() + + storage = storages[unwrapped_arg.untyped_storage().data_ptr()] + cpu_arg = unwrapped_arg.new_empty(0, device='cpu') + cpu_arg.set_(storage, unwrapped_arg.storage_offset(), unwrapped_arg.size(), unwrapped_arg.stride()) + cpu_arg = _rewrap_tensor(cpu_arg, original_tensor=arg) + return cpu_arg + + args_hst = [_to_cpu(arg) for arg in args_dev] + + # Process keyword arguments + kwargs_hst = {} + for key, value in kwargs.items(): + kwargs_hst[key] = _to_cpu(value) + return args_hst, kwargs_hst + + def _restore_args_dev(self, args_dev, args_hst, kwargs, kwargs_hst): + storages = {} + + def _from_cpu(arg_dev, arg_hst): + if hasattr(arg_dev, "data_ptr"): + # No need to rewrap because this just modifies internal + arg_dev, arg_hst = _unwrap_tensor(arg_dev), _unwrap_tensor(arg_hst) + storages[arg_dev.untyped_storage().data_ptr()] = (arg_dev.untyped_storage(), arg_hst.untyped_storage()) + elif isinstance(arg_dev, tuple): + for (arg_dev, arg_hst) in zip(arg_dev, arg_hst): + _from_cpu(arg_dev, arg_hst) + elif isinstance(arg_dev, TensorDescriptor): + _from_cpu(arg_dev.base, arg_hst.base) + + for arg_dev, arg_hst in zip(args_dev, args_hst): + _from_cpu(arg_dev, arg_hst) + + # Restore keyword arguments + for key, kwarg_dev in kwargs.items(): + kwarg_hst = kwargs_hst[key] + _from_cpu(kwarg_dev, kwarg_hst) + + for (arg_dev, arg_hst) in storages.values(): + arg_dev.copy_(arg_hst) + + def __call__(self, *args_dev, **kwargs): + if kwargs.pop("warmup", False): + return + # Removes not used reserved keywords from kwargs + # Triton doesn't support keyword-only, variable positional or variable keyword arguments + # It's safe to inspect only positional or keyword arguments (i.e., argspec.args) + argspec = inspect.getfullargspec(self.fn) + kwargs = {k: v for k, v in kwargs.items() if k in argspec.args} + # copy arguments to the host + args_hst, kwargs_hst = self._init_args_hst(args_dev, kwargs) + # remaps core language functions to interpreted ones + _patch_lang(self.fn) + # we need to copy arguments to the host for the interpreter + # implicitly convert tensor arguments to their base pointers + args = inspect.getcallargs(self.fn, *args_hst, **kwargs_hst) + args = {name: arg if name in self.constexprs else _implicit_cvt(arg) for name, arg in args.items()} + # iterate through grid + grid = self.grid(args) if callable(self.grid) else self.grid + assert len(grid) <= 3, "grid must have at most 3 dimensions" + grid = grid + (1, ) * (3 - len(grid)) + interpreter_builder.set_grid_dim(*grid) + try: + for x in range(grid[0]): + for y in range(grid[1]): + for z in range(grid[2]): + interpreter_builder.set_grid_idx(x, y, z) + self.fn(**args) + except Exception as e: + if triton.knobs.compilation.front_end_debugging: + raise + raise InterpreterError(repr(e)) from e + # copy arguments back to propagate side-effects + self._restore_args_dev(args_dev, args_hst, kwargs, kwargs_hst) + + +class ASTTransformer(ast.NodeTransformer): + + def visit_Assign(self, node): + names = [] + for target in node.targets: + names += [self.visit(target)] + if len(names) > 1: + raise ValueError("Multiple assignments are not supported") + # Modify the assignment x = value to + # interpreter_semantic.to_tensor(value, False) + node.value = ast.Call( + func=ast.Attribute(value=ast.Name(id="interpreter_semantic", ctx=ast.Load()), attr="to_tensor", + ctx=ast.Load()), args=[node.value, ast.Constant(value=False)], keywords=[]) + return node + + +class FunctionRewriter: + ast_transformer = ASTTransformer() + + def __init__(self, fn, **kwargs): + self.fn = fn + self.kwargs = kwargs + self.filename: str = "" + # Absolute line number in the file + self.def_file_lineno: int = 0 + + def rewrite_ast(self): + # If exception is raise, it means the function does not have source code available, + # e.g., dynamically generated functions, we cannot rewrite it so just return the original function + try: + lines, _ = inspect.getsourcelines(self.fn) + except Exception: + return self.fn + + # truncate lines before def + # @triton.autotune(...) + # ... + # @triton.jit + # ... + # def foo(...): <- this line is the function definition + self.filename, self.def_file_lineno = self._get_jit_fn_file_line() + self.def_lineno = self._find_def(lines) + src = self._prepare_source(lines) + transformed_ast = self._transform_ast(src) + return self._compile_and_exec(transformed_ast) + + def _get_jit_fn_file_line(self): + from .jit import get_jit_fn_file_line, JITFunction + return get_jit_fn_file_line(JITFunction(self.fn)) + + def _find_def(self, lines): + def_lineno = 0 + # Line numbers start from 1 + for i, line in enumerate(lines): + if line.strip().startswith("def "): + def_lineno = i + 1 + return def_lineno + + def _prepare_source(self, lines): + lines = lines[self.def_lineno - 1:] + src = ''.join(lines) + return textwrap.dedent(src) + + def _transform_ast(self, src): + # src is like: + # 1: def foo(...): + # 2: ... + parsed_ast = ast.parse(src) + transformed_ast = self.ast_transformer.visit(parsed_ast) + ast.fix_missing_locations(transformed_ast) + inc_lineno = self.def_file_lineno - 1 + ast.increment_lineno(transformed_ast, inc_lineno) + return transformed_ast + + def _compile_and_exec(self, transformed_ast): + compiled_code = compile(transformed_ast, filename=self.filename, mode='exec') + local_namespace = {**self.kwargs} + fn_globals = self.fn.__globals__ + for key, value in globals().items(): + if key not in fn_globals: + fn_globals[key] = value + exec(compiled_code, fn_globals, local_namespace) + return local_namespace[self.fn.__name__] + + +class InterpretedFunction: + # Cache all rewritten functions + rewritten_fn: Dict[Callable, Callable] = {} + + def __init__(self, fn, **kwargs) -> None: + self.fn = fn + self.rewriter = FunctionRewriter(fn, **kwargs) + self.kwargs = kwargs + + def run(*args, **kwargs): + grid = kwargs["grid"] + fn = self.rewrite() + return GridExecutor(fn, self.arg_names, grid)(*args, **kwargs) + + self.run = run + signature = inspect.signature(fn) + self.arg_names = [v.name for v in signature.parameters.values()] + + def rewrite(self): + if self.fn not in self.rewritten_fn: + self.rewritten_fn[self.fn] = self.rewriter.rewrite_ast() + return self.rewritten_fn[self.fn] + + @property + def __name__(self): + return self.fn.__name__ + + def __getitem__(self, grid): + fn = self.rewrite() + return GridExecutor(fn, self.arg_names, grid) + + def __call__(self, *args, **kwargs): + # This is a device function call + _patch_lang(self.fn) + fn = self.rewrite() + try: + return fn(*args, **kwargs) + except Exception as e: + raise InterpreterError(repr(e)) from e diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/jit.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/jit.py new file mode 100644 index 0000000000000000000000000000000000000000..1cdaf1dfcf7a496737f634eb59b34e51e06794e5 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/runtime/jit.py @@ -0,0 +1,1107 @@ +from __future__ import annotations, division +import ast +import copy +import hashlib +import inspect +import itertools +import threading +import re +import textwrap +from collections import defaultdict +from dataclasses import dataclass +from functools import cached_property +from typing import Callable, Generic, Iterable, Optional, TypeVar, Union, overload, Dict, Any, Tuple + +from triton.tools.tensor_descriptor import TensorDescriptor +from types import ModuleType +from .. import knobs +from .driver import driver +from . import _async_compile +from .._utils import find_paths_if, get_iterable_path, type_canonicalisation_dict, canonicalize_dtype +from .cache import get_cache_key +from triton._C.libtriton import get_cache_invalidating_env_vars + +TRITON_MODULE = "triton.language" +GLUON_MODULE = "triton.experimental.gluon.language" + +T = TypeVar("T") + +# ----------------------------------------------------------------------------- +# Dependencies Finder +# ----------------------------------------------------------------------------- + + +class DependenciesFinder(ast.NodeVisitor): + """ + This AST visitor is used to find dependencies of a JITFunction. This can + be used to invalidate a JITFunction's hash when its source code -- or + that of its dependencies -- changes. + + This visitor also keeps track of the global variables touched by the + JITFunction. When we launch the kernel, we check that these have the same + values as they did when we ran this visitor. If not, we raise an error (or + otherwise we could recompile). + """ + + def __init__(self, name, globals, nonlocals, src) -> None: + super().__init__() + self.name = name + self.hasher = hashlib.sha256(src.encode("utf-8")) + + # This function's __globals__ dict. + self.globals = globals + self.nonlocals = nonlocals + + # Python builtins that can be accessed from Triton kernels. + self.supported_python_builtins = { + 'float', + 'getattr', + 'int', + 'isinstance', + 'len', + 'list', + 'max', + 'min', + 'print', + 'range', + } + self.supported_modules = { + GLUON_MODULE, + TRITON_MODULE, + "copy", + "math", + } + + # used_global_vals tells us which global variables are used by this + # function and all those it transitively calls, plus the values of those + # variables when each function was initially run. (That is, if A calls + # C, and B calls C, then the values for C in used_global_vals will be + # from the first time C was run, either by A or B.) + # + # Each function may have a different __globals__ dict, so the global + # variable `foo` may actually have a different value in the different + # functions. Thus this map is actually + # (var_name, id(__globals__)) -> (var_value, __globals__). + self.used_global_vals: Dict[Tuple[str, int], Tuple[Any, Dict[str, Any]]] = {} + + self.visiting_arg_default_value = False + + @property + def ret(self): + return self.hasher.hexdigest() + + def _is_triton_builtin(self, node, func): + if inspect.isbuiltin(node.func): + return True + module = getattr(func, "__module__", "") + return module.startswith(TRITON_MODULE) + + def _update_hash(self, func): + assert isinstance(func, JITCallable) + # Merge our used_global_vals with those of the called function, + # after checking that all overlapping values are consistent. + for k in self.used_global_vals.keys() & func.used_global_vals.keys(): + var_name, _ = k + v1, _ = self.used_global_vals[k] + v2, _ = func.used_global_vals[k] + if v1 != v2: + raise RuntimeError( + f"Global variable {var_name} has value {v1} when compiling {self.name}, but inner kernel {func.__name__} has conflicting value {v2} from when it was first compiled. This is not allowed." + ) + self.used_global_vals.update(func.used_global_vals) + # update hash + func_key = func.cache_key + func_key += str(getattr(func, "noinline", False)) + self.hasher.update(func_key.encode("utf-8")) + + def record_reference(self, val, var_dict=None, name=None): + from ..language.core import constexpr + # Only keep track of "interesting" global variables, that non-evil users + # might change. Don't consider functions, modules, builtins, etc. This + # helps keep the list of vars we have to check small. + if val is None or type(val) is ModuleType: + return + + if getattr(val, "__triton_builtin__", False): + return + + # Stubs that aren't real functions + if getattr(val, "__module__", "") == "triton.language.extra.libdevice": + return + + if isinstance(val, JITCallable): + self._update_hash(val) + return + + if callable(val) and not isinstance(val, type) and not isinstance(val, constexpr): + raise RuntimeError(f"Unsupported function referenced: {val}") + + # Python default arguments are resolved only once, when the + # function is defined. So if you do `foo(a=A)` and the value of + # A changes, foo will still use the old value of A. + # It would be pretty evil if someone did `import x` and then + # `x = blah`. + if self.visiting_arg_default_value: + return + + if var_dict is not None: + self.used_global_vals[(name, id(var_dict))] = (copy.deepcopy(val), var_dict) + return + + def visit_Name(self, node): + if type(node.ctx) is ast.Store: + return node.id + + if node.id in self.local_names: + # The global name is hidden by the local name. + return None + + def name_lookup(name): + val = self.globals.get(name, None) + if val is not None: + return val, self.globals + val = self.nonlocals.get(name, None) + if val is not None: + return val, self.nonlocals + return None, None + + val, var_dict = name_lookup(node.id) + if node.id in self.supported_python_builtins: + return val + + self.record_reference(val, var_dict, node.id) + return val + + def visit_Tuple(self, node): + # We need to explicitly return the tuple values so that visit_Assign can + # access them in the case of `a, b = ...`. + return [self.visit(elt) for elt in node.elts] + + def visit_Attribute(self, node): + lhs = self.visit(node.value) + while isinstance(lhs, ast.Attribute): + lhs = self.visit(lhs.value) + lhs_name = getattr(lhs, "__name__", "") + if lhs is None or lhs_name in self.supported_modules: + return None + ret = getattr(lhs, node.attr) + self.record_reference(ret) + return ret + + def visit_FunctionDef(self, node): + # Save the local name, which may hide the global name. + self.local_names = {arg.arg for arg in node.args.args} + self.generic_visit(node) + + def visit_arguments(self, node): + # The purpose of this function is to visit everything in `arguments` + # just like `generic_visit`, except when we're visiting default values + # (i.e. the `foo` part of `def fn(x = foo)`), we set + # self.visiting_arg_default_value = True. This allows visit_Name to be + # aware that we're inside function default values, which have special + # semantics. + + # According to the AST docs, the arguments node has the following structure. + # + # arguments = (arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs, + # expr* kw_defaults, arg? kwarg, expr* defaults) + def visit_defaults(defaults): + try: + assert not self.visiting_arg_default_value + self.visiting_arg_default_value = True + for expr in defaults: + if expr is not None: + self.visit(expr) + finally: + self.visiting_arg_default_value = False + + for arg in itertools.chain(node.posonlyargs, node.args, [node.vararg] if node.vararg else [], node.kwonlyargs): + self.visit(arg) + + visit_defaults(node.kw_defaults) + + if node.kwarg is not None: + self.visit(node.kwarg) + + visit_defaults(node.defaults) + + def visitAssnTarget(self, node): + # Target is either a single string, or a list of strings (if the assn + # target is a tuple). + target = self.visit(node) + if isinstance(target, list): + self.local_names |= set(target) + else: + self.local_names.add(target) + + def visit_Assign(self, node): + if len(node.targets) != 1: + # TODO(jlebar): I don't actually know how to hit this. You don't + # get it from `a, b = ...` -- in that case, node.targets is a single + # Tuple, and in fact we *do* need to handle that case if we want + # existing code to work. + raise TypeError("Simultaneous multiple assignment is not supported.") + + self.visitAssnTarget(node.targets[0]) + + # This will re-visit the target, but that's OK. + self.generic_visit(node) + + def visit_AnnAssign(self, node): + self.visitAssnTarget(node.target) + + # This will re-visit the target, but that's OK. + self.generic_visit(node) + + def visit_For(self, node): + self.visitAssnTarget(node.target) + + # This will re-visit the target, but that's fine. + self.generic_visit(node) + + +# ----------------------------------------------------------------------------- +# JITFunction +# ----------------------------------------------------------------------------- + + +def _normalize_ty(ty) -> str: + import triton.language.core as core + if isinstance(ty, str): + ty = ty.strip() + if ty.startswith("const "): + ty = ty.removeprefix("const") + ty = _normalize_ty(ty) + assert ty.startswith("*") + return "*k" + ty[1:] + if ty.endswith("*"): + return "*" + _normalize_ty(ty[:-1]) + if ty.startswith("*"): + return "*" + _normalize_ty(ty[1:]) + if ty.startswith("tl."): + return _normalize_ty(ty.removeprefix("tl.")) + elif isinstance(ty, core.pointer_type): + return f"*{_normalize_ty(ty.element_ty)}" + elif isinstance(ty, core.dtype): + ty = ty.name + elif isinstance(ty, type): + ty = ty.__name__ + else: + ty = str(ty) + return type_canonicalisation_dict.get(ty.replace("_t", ""), ty) + + +class KernelParam: + """Represents a parameter (name plus metadata) to a @jit'ed function.""" + + def __init__(self, num: int, param: inspect.Parameter, do_not_specialize: bool, + do_not_specialize_on_alignment: bool): + self.num = num + self._param = param + self.do_not_specialize = do_not_specialize + self.do_not_specialize_on_alignment = do_not_specialize_on_alignment + + @cached_property + def name(self): + return self._param.name + + @cached_property + def annotation(self) -> str: + if not self._param.annotation or self._param.annotation == inspect.Parameter.empty: + return "" + return _normalize_ty(self._param.annotation) + + @cached_property + def annotation_type(self) -> str: + a = self.annotation + if a.startswith("*k"): + a = a[2:] + elif a.startswith("*"): + a = a[1:] + if a in set(type_canonicalisation_dict.values()): + return self.annotation + return "" + + @cached_property + def is_constexpr(self): + return "constexpr" in self.annotation + + @cached_property + def is_const(self): + if self.is_constexpr: + return False + return "const" in self.annotation or self.annotation.startswith("*k") + + @property + def default(self): + return self._param.default + + @property + def has_default(self): + return self._param.default != inspect.Parameter.empty + + +dtype2str = {} +specialize_impl_cache = [] + + +def create_specialize_impl(specialize_extra): + + from ..language import constexpr + from triton.experimental.gluon.nvidia.hopper import TensorDescriptor as GluonTensorDescriptor + + def specialize_impl(arg, is_const=False, specialize_value=True, align=True): + if arg is None: + return ("constexpr", None) + elif isinstance(arg, bool): + return ("u1", None) + elif isinstance(arg, int): + key = specialize_extra(arg, "int", align=align) if specialize_value else None + if arg == 1 and specialize_value: + return ("constexpr", 1) + elif -(2**31) <= arg and arg <= 2**31 - 1: + return ("i32", key) + elif 2**63 <= arg and arg <= 2**64 - 1: + return ("u64", key) + else: + return ("i64", key) + elif isinstance(arg, float): + return ("fp32", None) + elif hasattr(arg, "data_ptr"): + # dtypes are hashable so we can memoize this mapping: + dsk = (arg.dtype, is_const) + res = dtype2str.get(dsk, None) + if res is None: + res = ("*k" if dsk[1] else "*") + canonicalize_dtype(dsk[0]) + dtype2str[dsk] = res + key = specialize_extra(arg, "tensor", align=align) if specialize_value else None + return (res, key) + elif isinstance(arg, JITCallable): + return ("constexpr", arg.cache_key) + elif isinstance(arg, constexpr): + return ("constexpr", arg) + elif isinstance(arg, tuple): + spec = [specialize_impl(x) for x in arg] + make_tuple = lambda vals: type(arg)(*vals) if hasattr(arg, "_fields") else tuple(vals) + tys = make_tuple([x[0] for x in spec]) + keys = make_tuple([x[1] for x in spec]) + return (tys, keys) + elif isinstance(arg, TensorDescriptor): + assert hasattr(arg.base, "data_ptr") + inner = canonicalize_dtype(arg.base.dtype) + return (f"tensordesc<{inner}{list(arg.block_shape)}>", None) + elif isinstance(arg, GluonTensorDescriptor): + assert hasattr(arg.base, "data_ptr") + inner = canonicalize_dtype(arg.base.dtype) + return (f"tensordesc<{inner}{list(arg.block_shape)},{arg.layout!r}>", None) + else: + raise TypeError("Unsupported type: %s" % type(arg)) + + return specialize_impl + + +def mangle_type(arg, specialize=False): + if len(specialize_impl_cache) == 0: + specialize_impl_cache.append(create_specialize_impl(lambda _, **kwargs: None)) + specialize_impl = specialize_impl_cache[0] + return specialize_impl(arg, specialize_value=specialize)[0] + + +class KernelInterface(Generic[T]): + run: T + + def __getitem__(self, grid) -> T: + """ + A JIT function is launched with: fn[grid](*args, **kwargs). + Hence JITFunction.__getitem__ returns a callable proxy that + memorizes the grid. + """ + return lambda *args, **kwargs: self.run(grid=grid, warmup=False, *args, **kwargs) + # return cast(T, functools.partial(cast(Callable, self.run), grid=grid)) + + +def serialize_specialization_data(name, signature, constants, attrs, options, key): + constants = {key: str(value) if value.__class__.__name__ == "dtype" else value for key, value in constants.items()} + import json + obj = { + 'name': name, 'signature': signature, 'constant_keys': [list(x) for x in constants.keys()], 'constant_vals': + list(constants.values()), 'attrs_keys': [list(x) for x in attrs.keys()], 'attrs_vals': list(attrs.values()), + 'options': options.__dict__, 'key': key + } + serialized_obj = json.dumps(obj) + return serialized_obj + + +def create_function_from_signature(sig, kparams, backend): + """ + Equivalent to sig.bind followed by apply_defaults. This generates a + native Python function (using exec) which can be memoized on a per-kernel + basis to avoid having to run these expensive functions -- which constitute + much of the kernel launch overhead -- every time we run the kernel. + """ + assert len(sig.parameters) == len(kparams) + # Create the function argument list and the dict entries for the return statement + specialization = [] + # signature + for name, kp in zip(sig.parameters.keys(), kparams): + if kp.is_constexpr: + specialization.append(f'("constexpr", {name})') + else: + is_const = 'True' if kp.is_const else 'False' + specialize = 'False' if kp.do_not_specialize else 'True' + align = 'False' if kp.do_not_specialize_on_alignment else 'True' + ret = f"specialize_impl({name}, {is_const}, {specialize}, {align})" + if kp.annotation_type: + if isinstance(kp.annotation_type, str): + if kp.annotation_type == "u1" or kp.annotation_type[:2] in ["fp", "bf"]: + # we do not specialize non-constexpr floats and bools: + specialize = False + if specialize: + specialization.append(f'("{kp.annotation_type}",) + {ret}[1:]') + else: + # skip runtime specialization: + specialization.append(f'("{kp.annotation_type}", None)') + else: + specialization.append(f"{ret}") + + # compute argument string for a given parameter + arg = lambda x: x[0] if x[1].default is inspect.Parameter.empty else f"{x[0]}=default_{x[0]}" + # Join all arguments into a function definition string + func_body = f""" +def dynamic_func({", ".join(list(map(arg, sig.parameters.items())) + ["**options"])}): + params = {{{', '.join([f"'{name}': {name}" for name in sig.parameters.keys()])}}} + specialization = [{','.join(specialization)}] + return params, specialization, options +""" + # Prepare defaults to be inserted into function namespace + func_namespace = { + f"default_{name}": param.default + for name, param in sig.parameters.items() + if param.default is not inspect.Parameter.empty + } + + func_namespace["JITCallable"] = JITCallable + func_namespace["specialize_impl"] = create_specialize_impl(backend.get_arg_specialization) + + # Execute the function string in func_namespace to create the function + exec(func_body, func_namespace) + + # Extract the newly created function from the namespace + return func_namespace['dynamic_func'] + + +def get_full_name(fn): + return f"{fn.__module__}.{fn.__qualname__}" + + +class JITCallable: + + def __init__(self, fn): + self.fn = fn + self.signature = inspect.signature(fn) + try: + self.raw_src, self.starting_line_number = inspect.getsourcelines(fn) + except OSError as e: + raise ValueError("@jit functions should be defined in a Python file") from e + self._fn_name = get_full_name(fn) + self._hash_lock = threading.RLock() + + # function source code (without decorators) + src = textwrap.dedent("".join(self.raw_src)) + src = src[re.search(r"^def\s+\w+\s*\(", src, re.MULTILINE).start():] + self._src = src + self.hash = None + + # Map of global variables used by the function and any functions it + # transitively calls, plus their values. The values are collected when + # the function is first compiled. Then every time we run the function, + # we check that the values of the globals match what's expected, + # otherwise we raise an error. + # + # Different functions can have different __globals__ maps, so the map + # key is actually (var name, id(__globals__)), and the map value is + # (value, __globals__). + self.used_global_vals: Dict[Tuple[str, int], Tuple[Any, Dict[str, Any]]] = {} + + # reuse docs of wrapped function + self.__doc__ = fn.__doc__ + self.__name__ = fn.__name__ + self.__qualname__ = fn.__qualname__ + self.__globals__ = fn.__globals__ + self.__module__ = fn.__module__ + + def get_capture_scope(self): + return self.__globals__ | inspect.getclosurevars(self.fn).nonlocals + + @property + def cache_key(self): + # TODO : hash should be attribute of `self` + with self._hash_lock: + if self.hash is not None: + return self.hash + # Set a placeholder hash to break recursion in case the function + # transitively calls itself. The full hash is set after. + self.hash = f"recursion:{self._fn_name}" + nonlocals = inspect.getclosurevars(self.fn).nonlocals + dependencies_finder = DependenciesFinder(name=self._fn_name, globals=self.__globals__, nonlocals=nonlocals, + src=self.src) + dependencies_finder.visit(self.parse()) + self.hash = dependencies_finder.ret + str(self.starting_line_number) + self.used_global_vals = dict(sorted(dependencies_finder.used_global_vals.items())) + + from triton.language.core import constexpr + self.hash += str([(name, val) + for (name, _), (val, _) in self.used_global_vals.items() + if isinstance(val, constexpr)]) + self.hash = hashlib.sha256(self.hash.encode("utf-8")).hexdigest() + return self.hash + + # we do not parse `src` in the constructor because + # the user might want to monkey-patch self.src dynamically. + # Our unit tests do this, for example. + def parse(self): + tree = ast.parse(self._src) + assert isinstance(tree, ast.Module) + assert len(tree.body) == 1 + assert isinstance(tree.body[0], ast.FunctionDef) + return tree + + @property + def type(self): + from triton.language.core import constexpr_type + return constexpr_type(self) + + def _unsafe_update_src(self, new_src): + """ + The only method allowed to modify src. + Bypasses the __setattr__ restriction by calling super().__setattr__ directly. + + Note that it is the callers responsibility to make sure any triton functions that call this function have the `.hash` value reset to None. + """ + self.hash = None + self._src = new_src + + def _set_src(self): + raise AttributeError("Cannot set attribute 'src' directly. " + "Use '_unsafe_update_src()' and manually clear `.hash` of all callers" + "instead.") + + def _get_src(self): + return self._src + + src = property(fget=_get_src, fset=_set_src) + + +@dataclass +class JitFunctionInfo: + module: ModuleType + name: str + jit_function: JITFunction + + +def compute_cache_key(kernel_key_cache, specialization, options): + key = (tuple(specialization), str(options)) + cache_key = kernel_key_cache.get(key, None) + if cache_key is not None: + return cache_key + + cache_key = str(specialization) + str(options) + kernel_key_cache[key] = cache_key + return cache_key + + +class JITFunction(JITCallable, KernelInterface[T]): + + def is_gluon(self): + return False + + def _call_hook( + self, + hook, + key, + signature, + device, + constants, + options, + configs, + is_warmup, + ) -> bool | None: + if not hook: + return None + + name = self.fn.__qualname__ + module = self.fn.__module__ + arg_reprs = ", ".join([f"{param.name}: {ty}" for param, ty in zip(self.params, key[1])]) + repr = f"{name}[num_warps={options.num_warps}, num_ctas={options.num_ctas}, num_stages={options.num_stages}, enable_fp_fusion={options.enable_fp_fusion}, launch_cooperative_grid={options.launch_cooperative_grid}]({arg_reprs})" + full_name = get_full_name(self.fn) + + specialization_data = serialize_specialization_data(full_name, signature, constants, configs[0], options, key) + + kwargs = { + 'signature': signature, + 'device': device, + 'constants': constants, + 'num_warps': options.num_warps, + 'num_ctas': options.num_ctas, + 'num_stages': options.num_stages, + 'enable_fp_fusion': options.enable_fp_fusion, + 'launch_cooperative_grid': options.launch_cooperative_grid, + 'extern_libs': options.extern_libs, + 'configs': configs, + 'specialization_data': specialization_data, + 'is_warmup': is_warmup, + } + + return hook( + key=key, + repr=repr, + fn=JitFunctionInfo(module, name, self), + compile={"key": key, **kwargs}, + is_manual_warmup=is_warmup, + already_compiled=False, + ) + + def add_pre_run_hook(self, hook): + ''' + Add a hook that will be executed prior to the execution of run + function with args and kwargs passed into the kernel + ''' + assert callable(hook) + self.pre_run_hooks.append(hook) + + def create_binder(self): + """ + Precompute as much as possible. + """ + from ..compiler import CompiledKernel, compile, ASTSource, make_backend + target = driver.active.get_current_target() + backend = make_backend(target) + self.CompiledKernel = CompiledKernel + self.compile = compile + self.ASTSource = ASTSource + binder = create_function_from_signature(self.signature, self.params, backend) + return {}, {}, target, backend, binder + + def _pack_args(self, backend, kwargs, bound_args, specialization, options): + # options + options = backend.parse_options(kwargs) + # signature + sigkeys = [x.name for x in self.params] + sigvals = [x[0] for x in specialization] + signature = {k: v for (k, v) in zip(sigkeys, sigvals)} + # check arguments + assert "device_type" not in kwargs, "device_type option is deprecated; current target will be used" + assert "device" not in kwargs, "device option is deprecated; current device will be used" + assert "stream" not in kwargs, "stream option is deprecated; current stream will be used" + for k in kwargs: + if k not in options.__dict__ and k not in sigkeys: + raise KeyError("Keyword argument %s was specified but unrecognised" % k) + # constexprs + constexprs = find_paths_if(sigvals, lambda _, val: val == "constexpr") + constexprs = {path: get_iterable_path(list(bound_args.values()), path) for path in constexprs} + # attributes + attrvals = [x[1] for x in specialization] + attrs = find_paths_if(attrvals, lambda _, x: isinstance(x, str)) + attrs = {k: backend.parse_attr(get_iterable_path(attrvals, k)) for k in attrs} + + return options, signature, constexprs, attrs + + def run(self, *args, grid, warmup, **kwargs): + kwargs["debug"] = kwargs.get("debug", self.debug) or knobs.runtime.debug + + # parse options + device = driver.active.get_current_device() + stream = driver.active.get_current_stream(device) + + # Execute pre run hooks with args and kwargs + for hook in self.pre_run_hooks: + hook(*args, **kwargs) + + kernel_cache, kernel_key_cache, target, backend, binder = self.device_caches[device] + # specialization is list[tuple[str, Any]], where first element of tuple is + # the type and the second parameter is the 'specialization' value. + bound_args, specialization, options = binder(*args, **kwargs) + + key = compute_cache_key(kernel_key_cache, specialization, options) + kernel = kernel_cache.get(key, None) + + # Kernel is not cached; we have to compile. + if kernel is None: + options, signature, constexprs, attrs = self._pack_args(backend, kwargs, bound_args, specialization, + options) + + kernel = self._do_compile(key, signature, device, constexprs, options, attrs, warmup) + if kernel is None: + return None + + # Check that used global values have not changed. + not_present = object() + for (name, _), (val, globals_dict) in self.used_global_vals.items(): + if (newVal := globals_dict.get(name, not_present)) != val: + raise RuntimeError( + f"Global variable {name} has changed since we compiled this kernel, from {val} to {newVal}") + + if not warmup: + # canonicalize grid + assert grid is not None + if callable(grid): + grid = grid(bound_args) + grid_size = len(grid) + grid_0 = grid[0] + grid_1 = grid[1] if grid_size > 1 else 1 + grid_2 = grid[2] if grid_size > 2 else 1 + if hasattr(kernel, "result"): + kernel = kernel.result() + # launch kernel + launch_metadata = kernel.launch_metadata(grid, stream, *bound_args.values()) + kernel.run(grid_0, grid_1, grid_2, stream, kernel.function, kernel.packed_metadata, launch_metadata, + knobs.runtime.launch_enter_hook, knobs.runtime.launch_exit_hook, *bound_args.values()) + return kernel + + def repr(self, _): + return self._fn_name if self._repr is None else self._repr(_) + + def __init__(self, fn, version=None, do_not_specialize=None, do_not_specialize_on_alignment=None, debug=None, + noinline=None, repr=None, launch_metadata=None): + do_not_specialize = do_not_specialize if do_not_specialize else [] + do_not_specialize_on_alignment = do_not_specialize_on_alignment if do_not_specialize_on_alignment else [] + + super().__init__(fn) + self.module = fn.__module__ + self.version = version + self.do_not_specialize = do_not_specialize + self.do_not_specialize_on_alignment = do_not_specialize_on_alignment + self._repr = repr + self.launch_metadata = launch_metadata + + self.params = [] + for i, param in enumerate(self.signature.parameters.values()): + dns = i in do_not_specialize or param.name in do_not_specialize + dns_oa = i in do_not_specialize_on_alignment or param.name in do_not_specialize_on_alignment + self.params.append(KernelParam(i, param, dns, dns_oa)) + + # cache of just-in-time compiled kernels + self.device_caches = defaultdict(self.create_binder) + + # JITFunction can be instantiated as kernel + # when called with a grid using __getitem__ + self.kernel = None + self.debug = debug + self.noinline = noinline + + # TODO(jlebar): Remove uses of these fields outside this file, then + # remove the fields here. + self.arg_names = [p.name for p in self.params] + self.constexprs = [p.num for p in self.params if p.is_constexpr] + + # Hooks that will be called prior to executing "run" + self.pre_run_hooks = [] + + def warmup(self, *args, grid, **kwargs): + return self.run(grid=grid, warmup=True, *map(MockTensor.wrap_dtype, args), **kwargs) + + def preload(self, specialization_data): + import json + import triton.language as tl + device = driver.active.get_current_device() + deserialized_obj = json.loads(specialization_data) + if deserialized_obj['name'] != self._fn_name: + raise RuntimeError( + f"Specialization data is for {deserialized_obj['name']} but trying to preload for {self._fn_name}") + constant_keys = map(tuple, deserialized_obj['constant_keys']) + constant_vals = deserialized_obj['constant_vals'] + constexprs = { + key: tl.dtype(value) if tl.dtype.is_dtype(value) else value + for key, value in zip(constant_keys, constant_vals) + } + attrs_keys = map(tuple, deserialized_obj['attrs_keys']) + attrs_vals = deserialized_obj['attrs_vals'] + attrs = dict(zip(attrs_keys, attrs_vals)) + signature = dict(deserialized_obj['signature'].items()) + options = { + key: tuple(value) if isinstance(value, list) else value + for key, value in deserialized_obj['options'].items() + } + key = deserialized_obj['key'] + _, _, _, backend, _ = self.device_caches[device] + options = backend.parse_options(options) + return self._do_compile( + key, + signature, + device, + constexprs, + options, + attrs, + warmup=True, + ) + + def _do_compile(self, key, signature, device, constexprs, options, attrs, warmup): + kernel_cache, _, target, backend, _ = self.device_caches[device] + + if self._call_hook(knobs.runtime.jit_cache_hook, key, signature, device, constexprs, options, [attrs], warmup): + return None + src = self.ASTSource(self, signature, constexprs, attrs) + + async_mode = _async_compile.active_mode.get() + if async_mode is not None: + + env_vars = get_cache_invalidating_env_vars() + cache_key = get_cache_key(src, backend, options, env_vars) + + def async_compile(): + return self.compile(src, target=target, options=options.__dict__, _env_vars=env_vars) + + def finalize_compile(kernel): + kernel_cache[key] = kernel + self._call_hook(knobs.runtime.jit_post_compile_hook, key, signature, device, constexprs, options, + [attrs], warmup) + + kernel = async_mode.submit(cache_key, async_compile, finalize_compile) + else: + kernel = self.compile(src, target=target, options=options.__dict__) + kernel_cache[key] = kernel + self._call_hook(knobs.runtime.jit_post_compile_hook, key, signature, device, constexprs, options, [attrs], + warmup) + return kernel + + def __call__(self, *args, **kwargs): + raise RuntimeError("Cannot call @triton.jit'd outside of the scope of a kernel") + + def __repr__(self): + return f"JITFunction({self.module}:{self.fn.__qualname__})" + + +# ----------------------------------------------------------------------------- +# `jit` decorator +# ----------------------------------------------------------------------------- + + +@overload +def jit(fn: T) -> JITFunction[T]: + ... + + +@overload +def jit( + *, + version=None, + repr: Optional[Callable] = None, + launch_metadata: Optional[Callable] = None, + do_not_specialize: Optional[Iterable[int | str]] = None, + do_not_specialize_on_alignment: Optional[Iterable[int | str]] = None, + debug: Optional[bool] = None, + noinline: Optional[bool] = None, +) -> Callable[[T], JITFunction[T]]: + ... + + +def jit( + fn: Optional[T] = None, + *, + version=None, + repr: Optional[Callable] = None, + launch_metadata: Optional[Callable] = None, + do_not_specialize: Optional[Iterable[int | str]] = None, + do_not_specialize_on_alignment: Optional[Iterable[int | str]] = None, + debug: Optional[bool] = None, + noinline: Optional[bool] = None, +) -> Union[JITFunction[T], Callable[[T], JITFunction[T]]]: + """ + Decorator for JIT-compiling a function using the Triton compiler. + + :note: When a jit'd function is called, arguments are + implicitly converted to pointers if they have a :code:`.data_ptr()` method + and a `.dtype` attribute. + + :note: This function will be compiled and run on the GPU. It will only have access to: + + * python primitives, + * builtins within the triton package, + * arguments to this function, + * other jit'd functions + + :param fn: the function to be jit-compiled + :type fn: Callable + """ + + def decorator(fn: T) -> JITFunction[T]: + assert callable(fn) + if knobs.runtime.interpret: + from .interpreter import InterpretedFunction + return InterpretedFunction(fn, version=version, do_not_specialize=do_not_specialize, + do_not_specialize_on_alignment=do_not_specialize_on_alignment, debug=debug, + noinline=noinline, repr=repr, launch_metadata=launch_metadata) + else: + return JITFunction( + fn, + version=version, + do_not_specialize=do_not_specialize, + do_not_specialize_on_alignment=do_not_specialize_on_alignment, + debug=debug, + noinline=noinline, + repr=repr, + launch_metadata=launch_metadata, + ) + + if fn is not None: + return decorator(fn) + + else: + return decorator + + +# ----------------------------------------------------------------------------- +# Utilities for mocking tensors +# ----------------------------------------------------------------------------- + + +class MockTensor: + """ + Can be used in place of real tensors when calling: + kernel.warmup(MockTensor(torch.float32), ...) + """ + + @staticmethod + def wrap_dtype(arg): + if arg.__class__.__name__ == "dtype" and arg.__module__ == "torch": + return MockTensor(arg) + return arg + + def __init__(self, dtype, shape=None): + if shape is None: + shape = [1] + self.dtype = dtype + self.shape = shape + + def stride(self): + strides = [1] + for size in self.shape[1:]: + strides.append(strides[-1] * size) + return tuple(reversed(strides)) + + @staticmethod + def data_ptr(): + return 0 # optimistically assumes multiple of 16 + + @staticmethod + def ptr_range(): + return 0 # optimistically assumes 32 bit pointer range + + +class TensorWrapper: + + def __init__(self, base, dtype): + self.dtype = dtype + self.base = base + self.data = base.data + self.device = base.device + self.shape = self.base.shape + + def data_ptr(self): + return self.base.data_ptr() + + def stride(self, *args): + return self.base.stride(*args) + + def __str__(self) -> str: + return f"TensorWrapper[{self.dtype}]({self.base})" + + def element_size(self): + return self.base.element_size() + + def cpu(self): + return TensorWrapper(self.base.cpu(), self.dtype) + + def copy_(self, other): + self.base.copy_(other.base) + + def clone(self): + return TensorWrapper(self.base.clone(), self.dtype) + + def to(self, device): + return TensorWrapper(self.base.to(device), self.dtype) + + def new_empty(self, sizes): + return TensorWrapper(self.base.new_empty(sizes), self.dtype) + + +def reinterpret(tensor, dtype): + if isinstance(tensor, TensorWrapper): + if dtype == tensor.base.dtype: + # Reinterpreting to the original interpretation; return the base. + return tensor.base + else: + # Reinterpreting a wrapped tensor to a different type. + return TensorWrapper(tensor.base, dtype) + elif hasattr(tensor, "data_ptr"): + # A new wrapper is needed around an unwrapped tensor. + return TensorWrapper(tensor, dtype) + else: + raise TypeError(f"Cannot reinterpret a {type(tensor)}.") + + +def get_jit_fn_file_line(fn): + base_fn = fn + while not isinstance(base_fn, JITCallable): + base_fn = base_fn.fn + file_name = base_fn.fn.__code__.co_filename + begin_line = base_fn.starting_line_number + # Match the following pattern: + # @triton.autotune(...) <- foo.__code__.co_firstlineno + # @triton.heuristics(...) + # @triton.jit + # def foo(...): <- this line is the first line + for idx, line in enumerate(base_fn.raw_src): + if line.strip().startswith("def "): + begin_line += idx + break + return file_name, begin_line + + +class BoundConstexprFunction(JITCallable): + + def __init__(self, instance, fn): + self.__self__ = instance + self.__func__ = fn + + def __call__(self, *args, **kwargs): + return self.__func__(self.__self__, *args, **kwargs) + + +class ConstexprFunction(JITCallable): + + def __init__(self, fn): + super().__init__(fn) + + def __get__(self, obj, objclass): + # Create a bound function to support constexpr_function methods + if obj is not None: + return BoundConstexprFunction(obj, self) + return self + + def __call__(self, *args, _semantic=None, **kwargs): + from triton.language.core import _unwrap_if_constexpr, constexpr + # de-constexpr arguments and discard the _semantic keyword argument: + args = [_unwrap_if_constexpr(x) for x in args] + kwargs = {k: _unwrap_if_constexpr(v) for (k, v) in kwargs.items()} + + # call the raw Python function f: + res = self.fn(*args, **kwargs) + + if _semantic is None: + # Not called by triton code generator, e.g. in host code, another constexpr function, or even an aggreate's __init__ function + return res + + # convert result back to a Triton constexpr: + if knobs.runtime.interpret: + return res # No constexpr in interpreter + return constexpr(res) + + +def constexpr_function(fn): + """ + Wraps an arbitrary Python function so that it can be called at + compile-time on constexpr arguments in a Triton function and + returns a constexpr result. + """ + return ConstexprFunction(fn) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/testing.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..1fd88c648779f632eb5bf3db3b31f13095208c40 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/testing.py @@ -0,0 +1,543 @@ +import functools +import math +import os +import statistics +import subprocess +import sys +from contextlib import contextmanager +from typing import Any, Dict, List +from . import language as tl +from . import runtime + + +def nvsmi(attrs): + attrs = ','.join(attrs) + cmd = ['nvidia-smi', '-i', '0', '--query-gpu=' + attrs, '--format=csv,noheader,nounits'] + out = subprocess.check_output(cmd) + ret = out.decode(sys.stdout.encoding).split(',') + ret = [int(x) for x in ret] + return ret + + +# pure Python implementation of np.quantile/torch.quantile +# to avoid unnecessary runtime dependency on numpy/torch + + +def _quantile(a, q): + n = len(a) + a = sorted(a) + + def get_quantile(q): + if not (0 <= q <= 1): + raise ValueError("Quantiles must be in the range [0, 1]") + point = q * (n - 1) + lower = math.floor(point) + upper = math.ceil(point) + t = point - lower + return (1 - t) * a[lower] + t * a[upper] + + return [get_quantile(q) for q in q] + + +def _summarize_statistics(times, quantiles, return_mode): + if quantiles is not None: + ret = _quantile(times, quantiles) + if len(ret) == 1: + ret = ret[0] + return ret + if return_mode == "all": + return times + elif return_mode == "min": + return min(times) + elif return_mode == "max": + return max(times) + elif return_mode == "mean": + return statistics.mean(times) + elif return_mode == "median": + return statistics.median(times) + + +def do_bench_cudagraph(fn, rep=20, grad_to_none=None, quantiles=None, return_mode="mean"): + """ + Benchmark the runtime of the provided function. + + :param fn: Function to benchmark + :type fn: Callable + :param rep: Repetition time (in ms) + :type rep: int + :param grad_to_none: Reset the gradient of the provided tensor to None + :type grad_to_none: torch.tensor, optional + :param return_mode: The statistical measure to return. Options are "min", "max", "mean", "median", or "all". Default is "mean". + :type return_mode: str + """ + import torch + assert return_mode in ["min", "max", "mean", "median", "all"] + + with torch.cuda.stream(torch.cuda.Stream()): + # warmup + fn() + if grad_to_none is not None: + for x in grad_to_none: + x.detach_() + x.requires_grad_(True) + x.grad = None + # step 1 - we estimate the amount of time the kernel call takes + # NOTE: this estimate isn't super accurate because the GPU isn't warmed up at this point + # but it is probably good enough + # NOTE: we don't use a graph to estimate the runtime because creating a graph is expensive, + # ~300ms on A100, so we default to the same method used in `do_bench` (minus the L2 + # cache flush). + start_event = torch.cuda.Event(enable_timing=True) + end_event = torch.cuda.Event(enable_timing=True) + start_event.record() + for _ in range(5): + fn() + end_event.record() + torch.cuda.synchronize() + estimate_ms = start_event.elapsed_time(end_event) / 5 + # Rewrite to avoid possible division by 0 issues with fast benchmarks + if estimate_ms == 0: + n_repeat = 1000 + else: + n_repeat = max(1, int(rep / estimate_ms)) + # step 2 - construct a cuda graph with `n_repeat` unrolled function calls to minimize + # host overhead + g = torch.cuda.CUDAGraph() + with torch.cuda.graph(g): + for _ in range(n_repeat): + if grad_to_none is not None: + for x in grad_to_none: + x.grad = None + fn() + torch.cuda.synchronize() + # measure time and return + ret = [] + n_retries = 10 + for _ in range(n_retries): + start_event = torch.cuda.Event(enable_timing=True) + end_event = torch.cuda.Event(enable_timing=True) + start_event.record() + g.replay() + end_event.record() + torch.cuda.synchronize() + ret += [start_event.elapsed_time(end_event) / n_repeat] + return _summarize_statistics(ret, quantiles, return_mode) + + +def do_bench(fn, warmup=25, rep=100, grad_to_none=None, quantiles=None, return_mode="mean"): + """ + Benchmark the runtime of the provided function. By default, return the median runtime of :code:`fn` along with + the 20-th and 80-th performance percentile. + + :param fn: Function to benchmark + :type fn: Callable + :param warmup: Warmup time (in ms) + :type warmup: int + :param rep: Repetition time (in ms) + :type rep: int + :param grad_to_none: Reset the gradient of the provided tensor to None + :type grad_to_none: torch.tensor, optional + :param quantiles: Performance percentile to return in addition to the median. + :type quantiles: list[float], optional + :param return_mode: The statistical measure to return. Options are "min", "max", "mean", "median", or "all". Default is "mean". + :type return_mode: str + """ + assert return_mode in ["min", "max", "mean", "median", "all"] + + di = runtime.driver.active.get_device_interface() + + fn() + di.synchronize() + + cache = runtime.driver.active.get_empty_cache_for_benchmark() + + # Estimate the runtime of the function + start_event = di.Event(enable_timing=True) + end_event = di.Event(enable_timing=True) + start_event.record() + for _ in range(5): + runtime.driver.active.clear_cache(cache) + fn() + end_event.record() + di.synchronize() + estimate_ms = start_event.elapsed_time(end_event) / 5 + + # compute number of warmup and repeat + n_warmup = max(1, int(warmup / estimate_ms)) + n_repeat = max(1, int(rep / estimate_ms)) + start_event = [di.Event(enable_timing=True) for i in range(n_repeat)] + end_event = [di.Event(enable_timing=True) for i in range(n_repeat)] + # Warm-up + for _ in range(n_warmup): + fn() + # Benchmark + for i in range(n_repeat): + # we don't want `fn` to accumulate gradient values + # if it contains a backward pass. So we clear the + # provided gradients + if grad_to_none is not None: + for x in grad_to_none: + x.grad = None + # we clear the L2 cache before each run + runtime.driver.active.clear_cache(cache) + # record time of `fn` + start_event[i].record() + fn() + end_event[i].record() + # Record clocks + di.synchronize() + times = [s.elapsed_time(e) for s, e in zip(start_event, end_event)] + return _summarize_statistics(times, quantiles, return_mode) + + +def assert_close(x, y, atol=None, rtol=None, err_msg=''): + """ + Asserts that two inputs are close within a certain tolerance. + + :param x: The first input. + :type x: scala, list, numpy.ndarray, or torch.Tensor + :param y: The second input. + :type y: scala, list, numpy.ndarray, or torch.Tensor + :param atol: The absolute tolerance. Default value is 1e-2. + :type atol: float, optional + :param rtol: The relative tolerance. Default value is 0. + :type rtol: float, optional + :param err_msg: The error message to use if the assertion fails. + :type err_msg: str + """ + import numpy as np + import torch + + # canonicalize arguments to be tensors + if not isinstance(x, torch.Tensor): + x = torch.tensor(x) + if not isinstance(y, torch.Tensor): + y = torch.tensor(y) + # absolute tolerance + if atol is None: + atol = 1e-2 + atol = atol(x.dtype) if callable(atol) else atol + # relative tolerance hook + if rtol is None: + rtol = 0. + rtol = rtol(x.dtype) if callable(rtol) else rtol + # we use numpy instead of pytorch + # as it seems more memory efficient + # pytorch tends to oom on large tensors + if isinstance(x, torch.Tensor): + if x.dtype == torch.bfloat16: + x = x.float() + x = x.cpu().detach().numpy() + if isinstance(y, torch.Tensor): + if y.dtype == torch.bfloat16: + y = y.float() + y = y.cpu().detach().numpy() + # we handle size==1 case separately as we can + # provide better error message there + if x.size > 1 or y.size > 1: + np.testing.assert_allclose(x, y, atol=atol, rtol=rtol, equal_nan=True) + return + if not np.allclose(x, y, atol=atol, rtol=rtol): + raise AssertionError(f'{err_msg} {x} is not close to {y} (atol={atol}, rtol={rtol})') + + +class Benchmark: + """ + This class is used by the :code:`perf_report` function to generate line plots with a concise API. + """ + + def __init__( + self, + x_names: List[str], + x_vals: List[Any], + line_arg: str, + line_vals: List[Any], + line_names: List[str], + plot_name: str, + args: Dict[str, Any], + xlabel: str = '', + ylabel: str = '', + x_log: bool = False, + y_log: bool = False, + styles=None, + ): + """ + Constructor. + x_vals can be a list of scalars or a list of tuples/lists. If x_vals is a list + of scalars and there are multiple x_names, all arguments will have the same value. + If x_vals is a list of tuples/lists, each element should have the same length as + x_names. + + :param x_names: Name of the arguments that should appear on the x axis of the plot. + :type x_names: List[str] + :param x_vals: List of values to use for the arguments in :code:`x_names`. + :type x_vals: List[Any] + :param line_arg: Argument name for which different values correspond to different lines in the plot. + :type line_arg: str + :param line_vals: List of values to use for the arguments in :code:`line_arg`. + :type line_vals: List[Any] + :param line_names: Label names for the different lines. + :type line_names: List[str] + :param plot_name: Name of the plot. + :type plot_name: str + :param args: Dictionary of keyword arguments to remain fixed throughout the benchmark. + :type args: Dict[str, Any] + :param xlabel: Label for the x axis of the plot. + :type xlabel: str, optional + :param ylabel: Label for the y axis of the plot. + :type ylabel: str, optional + :param x_log: Whether the x axis should be log scale. + :type x_log: bool, optional + :param y_log: Whether the y axis should be log scale. + :type y_log: bool, optional + :param styles: A list of tuples, where each tuple contains two elements: a color and a linestyle. + :type styles: list[tuple[str, str]] + """ + self.x_names = x_names + self.x_vals = x_vals + self.x_log = x_log + self.line_arg = line_arg + self.line_vals = line_vals + self.line_names = line_names + self.y_log = y_log + self.styles = styles + # plot info + self.xlabel = xlabel + self.ylabel = ylabel + self.plot_name = plot_name + self.args = args + + +class Mark: + + def __init__(self, fn, benchmarks): + self.fn = fn + self.benchmarks = benchmarks + + def _run(self, bench: Benchmark, save_path: str, show_plots: bool, print_data: bool, diff_col=False, + save_precision=6, **kwrags): + import os + + import matplotlib.pyplot as plt + import pandas as pd + y_mean = bench.line_names + y_min = [f'{x}-min' for x in bench.line_names] + y_max = [f'{x}-max' for x in bench.line_names] + x_names = list(bench.x_names) + df = pd.DataFrame(columns=x_names + y_mean + y_min + y_max) + for x in bench.x_vals: + # x can be a single value or a sequence of values. + if not isinstance(x, (list, tuple)): + x = [x for _ in x_names] + + if len(x) != len(x_names): + raise ValueError(f"Expected {len(x_names)} values, got {x}") + x_args = dict(zip(x_names, x)) + + row_mean, row_min, row_max = [], [], [] + for y in bench.line_vals: + ret = self.fn(**x_args, **{bench.line_arg: y}, **bench.args, **kwrags) + try: + y_mean, y_min, y_max = ret + except TypeError: + y_mean, y_min, y_max = ret, None, None + row_mean += [y_mean] + row_min += [y_min] + row_max += [y_max] + df.loc[len(df)] = list(x) + row_mean + row_min + row_max + + if bench.plot_name: + plt.figure() + ax = plt.subplot() + # Plot first x value on x axis if there are multiple. + first_x = x_names[0] + for i, y in enumerate(bench.line_names): + y_min, y_max = df[y + '-min'], df[y + '-max'] + col = bench.styles[i][0] if bench.styles else None + sty = bench.styles[i][1] if bench.styles else None + ax.plot(df[first_x], df[y], label=y, color=col, ls=sty) + if not y_min.isnull().all() and not y_max.isnull().all(): + y_min = y_min.astype(float) + y_max = y_max.astype(float) + ax.fill_between(df[first_x], y_min, y_max, alpha=0.15, color=col) + ax.legend() + ax.set_xlabel(bench.xlabel or first_x) + ax.set_ylabel(bench.ylabel) + # ax.set_title(bench.plot_name) + ax.set_xscale("log" if bench.x_log else "linear") + ax.set_yscale("log" if bench.y_log else "linear") + if show_plots: + plt.show() + if save_path: + plt.savefig(os.path.join(save_path, f"{bench.plot_name}.png")) + df = df[x_names + bench.line_names] + if diff_col and df.shape[1] == 2: + col0, col1 = df.columns.tolist() + df['Diff'] = df[col1] - df[col0] + + if print_data: + print(bench.plot_name + ':') + print(df.to_string()) + if save_path: + df.to_csv(os.path.join(save_path, f"{bench.plot_name}.csv"), float_format=f"%.{save_precision}f", + index=False) + return df + + def run(self, show_plots=False, print_data=False, save_path='', return_df=False, **kwargs): + has_single_bench = isinstance(self.benchmarks, Benchmark) + benchmarks = [self.benchmarks] if has_single_bench else self.benchmarks + result_dfs = [] + try: + for bench in benchmarks: + result_dfs.append(self._run(bench, save_path, show_plots, print_data, **kwargs)) + finally: + if save_path: + # Create directory if it doesn't exist + os.makedirs(save_path, exist_ok=True) + with open(os.path.join(save_path, "results.html"), "w") as html: + html.write("\n") + for bench in benchmarks[:len(result_dfs)]: + html.write(f"\n") + html.write("\n") + if return_df: + if has_single_bench: + return result_dfs[0] + else: + return result_dfs + return None + + +def perf_report(benchmarks): + """ + Mark a function for benchmarking. The benchmark can then be executed by using the :code:`.run` method on the return value. + + :param benchmarks: Benchmarking configurations. + :type benchmarks: List of :class:`Benchmark` + """ + wrapper = lambda fn: Mark(fn, benchmarks) + return wrapper + + +def get_dram_gbps(device=None): + ''' return DRAM bandwidth in GB/s ''' + import torch + + from .runtime import driver + if not device: + device = torch.cuda.current_device() + mem_clock_khz = driver.active.utils.get_device_properties(device)["mem_clock_rate"] # in kHz + bus_width = driver.active.utils.get_device_properties(device)["mem_bus_width"] + bw_gbps = mem_clock_khz * bus_width * 2 / 1e6 / 8 # In GB/s + return bw_gbps + + +def get_max_tensorcore_tflops(dtype, clock_rate, device=None): + import torch + + from .runtime import driver + if not device: + device = torch.cuda.current_device() + + num_subcores = driver.active.utils.get_device_properties(device)["multiprocessor_count"] * 4 + capability = torch.cuda.get_device_capability(device) + if capability[0] < 8: + assert dtype == torch.float16 + ops_per_sub_core = 256 # 2 4x4x4 Tensor Cores + else: + if dtype in [torch.float32, torch.int32]: + ops_per_sub_core = 256 + elif dtype in [torch.float16, torch.bfloat16, torch.int16]: + ops_per_sub_core = 512 + elif dtype in [torch.int8, tl.float8e4nv, tl.float8e4b15, tl.float8e5]: + ops_per_sub_core = 1024 + else: + raise RuntimeError("dtype not supported") + tflops = num_subcores * clock_rate * ops_per_sub_core * 1e-9 + return tflops + + +# create decorator that wraps test function into +# a cuda-memcheck system call + + +def cuda_memcheck(**target_kwargs): + + def decorator(test_fn): + + @functools.wraps(test_fn) + def wrapper(*args, **kwargs): + import psutil + ppid_name = psutil.Process(os.getppid()).name() + run_cuda_memcheck = target_kwargs.items() <= kwargs.items() + if run_cuda_memcheck and ppid_name != "cuda-memcheck": + path = os.path.realpath(test_fn.__globals__["__file__"]) + # get path of current file + env = {"PATH": os.environ["PATH"], "PYTORCH_NO_CUDA_MEMORY_CACHING": "1"} + assert 'request' in kwargs, "memcheck'ed test must have a (possibly unused) `request` fixture" + test_id = kwargs['request'].node.callspec.id + cmd = f"{path}::{test_fn.__name__}[{test_id}]" + out = subprocess.run(["cuda-memcheck", "pytest", "-vs", cmd], capture_output=True, env=env) + assert out.returncode == 0, "cuda-memcheck returned an error: bounds checking failed" + assert "ERROR SUMMARY: 0 errors" in str(out.stdout) + else: + test_fn(*args, **kwargs) + + return wrapper + + return decorator + + +@contextmanager +def set_gpu_clock(ref_sm_clock=1350, ref_mem_clock=1215): + try: + subprocess.check_output(["nvidia-smi", "-i", "0", "-pm", "1"]) + subprocess.check_output([ + "nvidia-smi", + "-i", + "0", + f"--lock-gpu-clocks={ref_sm_clock},{ref_sm_clock}", + ]) + subprocess.check_output([ + "nvidia-smi", + "-i", + "0", + f"--lock-memory-clocks={ref_mem_clock},{ref_mem_clock}", + ]) + cur_sm_clock = nvsmi(["clocks.current.sm"])[0] + cur_mem_clock = nvsmi(["clocks.current.memory"])[0] + assert abs(cur_sm_clock - ref_sm_clock) < 10, f"GPU SMs must run at {ref_sm_clock} MHz" + assert abs(cur_mem_clock - ref_mem_clock) < 10, f"GPU SMs must run at {ref_mem_clock} MHz" + tflops = 1e-6 * 2 * 108 * 4 * 256 * ref_sm_clock + gbps = 640 * 2 * ref_mem_clock * 1e-3 + yield tflops, gbps + finally: + subprocess.check_output(["nvidia-smi", "-i", "0", "-pm", "0"]) + subprocess.check_output(["nvidia-smi", "-i", "0", "-rgc"]) + subprocess.check_output(["nvidia-smi", "-i", "0", "-rmc"]) + + +def get_max_simd_tflops(dtype, clock_rate, device=None): + import torch + + from .runtime import driver + if not device: + device = torch.cuda.current_device() + + num_subcores = driver.active.utils.get_device_properties(device)["multiprocessor_count"] * 4 + capability = torch.cuda.get_device_capability() + if capability[0] < 8: + if dtype == torch.float32: + ops_per_sub_core = 32 # 2*16 + elif dtype == torch.float16: + ops_per_sub_core = 64 + else: + raise RuntimeError("dtype not supported") + else: + if dtype == torch.float32: + ops_per_sub_core = 32 + elif dtype in [torch.float16, torch.bfloat16]: + ops_per_sub_core = 64 + else: + raise RuntimeError("dtype not supported") + tflops = num_subcores * clock_rate * ops_per_sub_core * 1e-9 + return tflops diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccc12c70a2e8f6f7dd609deec815a559520ce2c3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/__pycache__/disasm.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/__pycache__/disasm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7432029c8b49d1abb36a0ff158357a8716c82465 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/__pycache__/disasm.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/__pycache__/tensor_descriptor.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/__pycache__/tensor_descriptor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfa816157974293d4d9eee17f9f53e1ccf5e707a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/__pycache__/tensor_descriptor.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/build_extern.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/build_extern.py new file mode 100644 index 0000000000000000000000000000000000000000..8f0168d59d7af045bde68a508a000654f4893bb1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/build_extern.py @@ -0,0 +1,365 @@ +import argparse +import subprocess +from abc import ABC, abstractmethod +from typing import Dict, List, Optional + + +class Symbol: + _name: str + _op_name: str + _ret_type: str + _arg_names: List[str] + _arg_types: List[str] + + def __init__( + self, + name: str, + op_name: str, + ret_type: str, + arg_names: List[str], + arg_types: List[str], + ) -> None: + ''' + A symbol is a function declaration. + :param name: name of the symbol + :param op_name: name of the operation + :param ret_type: return type of the operation + :param arg_names: names of the arguments + :param arg_types: types of the arguments + ''' + self._name = name + self._op_name = op_name + self._ret_type = ret_type + self._arg_names = list(arg_names) + self._arg_types = list(arg_types) + + @property + def name(self) -> str: + return self._name + + @property + def op_name(self) -> str: + return self._op_name + + @property + def ret_type(self) -> str: + return self._ret_type + + @property + def arg_names(self) -> List[str]: + return self._arg_names + + @property + def arg_types(self) -> List[str]: + return self._arg_types + + +def convert_type(type_str) -> Optional[str]: + if type_str == "i32": + return "int32" + elif type_str == "u32": + return "uint32" + elif type_str == "i64": + return "int64" + elif type_str == "u64": + return "uint64" + elif type_str == "float": + return "fp32" + elif type_str == "double": + return "fp64" + else: + # ignore other types, such as pointer types + return None + + +def to_unsigned(type_str) -> str: + if type_str == "int32": + return "uint32" + elif type_str == "int64": + return "uint64" + else: + return type_str + + +class ExternLibrary(ABC): + _name: str + _path: str + _symbols: Dict[str, Symbol] + _format: bool + _grouping: bool + + def __init__( + self, + name: str, + path: str, + format: bool = True, + grouping: bool = True, + ) -> None: + ''' + Abstract class for extern library. + :param name: name of the library + :param path: path of the library + :param format: whether to format the generated stub file + ''' + self._name = name + self._path = path + self._symbols = {} + self._format = format + self._grouping = grouping + + @property + def name(self) -> str: + return self._name + + @property + def path(self) -> str: + return self._path + + @property + def symbols(self) -> Dict[str, Symbol]: + return self._symbols + + @property + def grouping(self) -> bool: + return self._grouping + + @abstractmethod + def parse_symbols(self, input_file) -> None: + pass + + @abstractmethod + def _output_stubs(self) -> str: + pass + + def generate_stub_file(self, output_dir) -> None: + file_str = self._output_stubs() + if file_str is None or len(file_str) == 0: + raise Exception("file_str is empty") + + output_file = f"{output_dir}/{self._name}.py" + with open(output_file, "w") as f: + f.write(file_str) + f.close() + if self._format: + subprocess.Popen(["autopep8", "-a", "-r", "-i", output_file], stdout=subprocess.PIPE).communicate() + subprocess.Popen(["isort", output_file], stdout=subprocess.PIPE).communicate() + + +class Libdevice(ExternLibrary): + _symbol_groups: Dict[str, List[Symbol]] + + def __init__(self, path) -> None: + ''' + Constructor for Libdevice. + :param path: path of the libdevice library + ''' + super().__init__("libdevice", path) + self._symbol_groups = {} + self.is_pure = True + + @staticmethod + def _extract_symbol(line) -> Optional[Symbol]: + # Extract symbols from line in the following format: + # "define [internal] @(,)" + entries = line.split("@") + ret_str = entries[0] + func_str = entries[1] + # Get ret_type, skip internal symbols + ret_strs = ret_str.split() + if ret_strs[1] == "internal": + return None + ret_type = convert_type(ret_strs[1]) + if ret_type is None: + return None + # Get function name + func_strs = func_str.split("(") + func_name = func_strs[0].replace("@", "") + op_name = func_name.replace("__nv_", "") + if 'ieee' in op_name: + return None + # Get arg_types + arg_strs = func_strs[1].split(",") + arg_types = [] + arg_names = [] + for i, arg_str in enumerate(arg_strs): + arg_type = convert_type(arg_str.split()[0]) + if arg_type is None: + return None + arg_name = 'arg' + str(i) + arg_types.append(arg_type) + arg_names.append(arg_name) + if op_name == "sad": + # Special case for sad, where the last argument is an unsigned int + arg_types[-1] = to_unsigned(arg_types[-1]) + elif op_name.startswith("u"): + # LLVM does not differentiate between signed and unsigned integer type. + # We have to convert the types to unsigned + ret_type = to_unsigned(ret_type) + for i, arg_type in enumerate(arg_types): + arg_types[i] = to_unsigned(arg_type) + return Symbol(func_name, op_name, ret_type, arg_names, arg_types) + + def _group_symbols(self) -> None: + symbol_set = {} + for symbol in self._symbols.values(): + op_name = symbol.op_name + symbol_set[op_name] = symbol + + # Group functions together by renaming. + renaming = { + 'llabs': 'abs', 'acosf': 'acos', 'acoshf': 'acosh', 'dadd_rd': 'add_rd', 'fadd_rd': 'add_rd', 'dadd_rn': + 'add_rn', 'fadd_rn': 'add_rn', 'dadd_ru': 'add_ru', 'fadd_ru': 'add_ru', 'dadd_rz': 'add_rz', 'fadd_rz': + 'add_rz', 'asinf': 'asin', 'asinhf': 'asinh', 'atanf': 'atan', 'atan2f': 'atan2', 'atanhf': 'atanh', + 'brevll': 'brev', 'cbrtf': 'cbrt', 'ceilf': 'ceil', 'clzll': 'clz', 'copysignf': 'copysign', 'cosf': 'cos', + 'coshf': 'cosh', 'cospif': 'cospi', 'cyl_bessel_i0f': 'cyl_bessel_i0', 'cyl_bessel_i1f': 'cyl_bessel_i1', + 'fdiv_rd': 'div_rd', 'ddiv_rd': 'div_rd', 'fdiv_rn': 'div_rn', 'ddiv_rn': 'div_rn', 'fdiv_ru': 'div_ru', + 'ddiv_ru': 'div_ru', 'fdiv_rz': 'div_rz', 'ddiv_rz': 'div_rz', 'erff': 'erf', 'erfcf': 'erfc', 'erfcinvf': + 'erfcinv', 'erfcxf': 'erfcx', 'erfinvf': 'erfinv', 'expf': 'exp', 'exp10f': 'exp10', 'exp2f': 'exp2', + 'expm1f': 'expm1', 'fabsf': 'abs', 'fabs': 'abs', 'fast_fdividef': 'fast_dividef', 'fdimf': 'fdim', 'ffsll': + 'ffs', 'floorf': 'floor', 'fmaf': 'fma', 'fmaf_rd': 'fma_rd', 'fmaf_rn': 'fma_rn', 'fmaf_ru': 'fma_ru', + 'fmaf_rz': 'fma_rz', 'fmodf': 'fmod', 'uhadd': 'hadd', 'hypotf': 'hypot', 'ilogbf': 'ilogb', 'isinff': + 'isinf', 'isinfd': 'isinf', 'isnanf': 'isnan', 'isnand': 'isnan', 'j0f': 'j0', 'j1f': 'j1', 'jnf': 'jn', + 'ldexpf': 'ldexp', 'lgammaf': 'lgamma', 'llrintf': 'llrint', 'llroundf': 'llround', 'logf': 'log', 'log10f': + 'log10', 'log1pf': 'log1p', 'log2f': 'log2', 'logbf': 'logb', 'umax': 'max', 'llmax': 'max', 'ullmax': + 'max', 'fmaxf': 'max', 'fmax': 'max', 'umin': 'min', 'llmin': 'min', 'ullmin': 'min', 'fminf': 'min', + 'fmin': 'min', 'dmul_rd': 'mul_rd', 'fmul_rd': 'mul_rd', 'dmul_rn': 'mul_rn', 'fmul_rn': 'mul_rn', + 'dmul_ru': 'mul_ru', 'fmul_ru': 'mul_ru', 'dmul_rz': 'mul_rz', 'fmul_rz': 'mul_rz', 'umul24': 'mul24', + 'umulhi': 'mulhi', 'mul64hi': 'mulhi', 'umul64hi': 'mulhi', 'nearbyintf': 'nearbyint', 'nextafterf': + 'nextafter', 'norm3df': 'norm3d', 'norm4df': 'norm4d', 'normcdff': 'normcdf', 'normcdfinvf': 'normcdfinv', + 'popcll': 'popc', 'powif': 'pow', 'powi': 'pow', 'powf': 'pow', 'rcbrtf': 'rcbrt', 'frcp_rd': 'rcp_rd', + 'drcp_rd': 'rcp_rd', 'frcp_rn': 'rcp_rn', 'drcp_rn': 'rcp_rn', 'frcp_ru': 'rcp_ru', 'drcp_ru': 'rcp_ru', + 'frcp_rz': 'rcp_rz', 'drcp_rz': 'rcp_rz', 'remainderf': 'remainder', 'urhadd': 'rhadd', 'rhypotf': 'rhypot', + 'rintf': 'rint', 'rnorm3df': 'rnorm3d', 'rnorm4df': 'rnorm4d', 'roundf': 'round', 'rsqrtf': 'rsqrt', + 'frsqrt_rn': 'rsqrt_rn', 'usad': 'sad', 'scalbnf': 'scalbn', 'signbitf': 'signbit', 'signbitd': 'signbit', + 'sinf': 'sin', 'sinhf': 'sinh', 'sinpif': 'sinpi', 'sqrtf': 'sqrt', 'fsqrt_rd': 'sqrt_rd', 'dsqrt_rd': + 'sqrt_rd', 'fsqrt_rn': 'sqrt_rn', 'dsqrt_rn': 'sqrt_rn', 'fsqrt_ru': 'sqrt_ru', 'dsqrt_ru': 'sqrt_ru', + 'fsqrt_rz': 'sqrt_rz', 'dsqrt_rz': 'sqrt_rz', 'fsub_rd': 'sub_rd', 'dsub_rd': 'sub_rd', 'fsub_rn': 'sub_rn', + 'dsub_rn': 'sub_rn', 'fsub_ru': 'sub_ru', 'dsub_ru': 'sub_ru', 'fsub_rz': 'sub_rz', 'dsub_rz': 'sub_rz', + 'tanf': 'tan', 'tanhf': 'tanh', 'tgammaf': 'tgamma', 'truncf': 'trunc', 'y0f': 'y0', 'y1f': 'y1', 'ynf': + 'yn' + } + + for symbol in self._symbols.values(): + op_name = symbol.op_name + if op_name in renaming: + op_name = renaming[op_name] + symbol._op_name = op_name + if op_name in self._symbol_groups: + self._symbol_groups[op_name].append(symbol) + else: + self._symbol_groups[op_name] = [symbol] + + def parse_symbols(self, input_file) -> None: + if len(self.symbols) > 0: + return + output = subprocess.check_output(["grep", "define", input_file]).decode().splitlines() + for line in output: + symbol = self._extract_symbol(line) + if symbol is None: + continue + self._symbols[symbol.name] = symbol + + self._group_symbols() + + def _output_stubs(self) -> str: + # Generate python functions in the following format: + # @extern.extern + # def (, _builder=None): + # arg_type_symbol_dict = {[arg_type]: {(symbol, ret_type)}} + # return core.extern_elementwise("libdevice", , , , _builder) + import_str = "from . import core\n" + + header_str = "" + func_str = "" + for symbols in self._symbol_groups.values(): + func_str += "@core.extern\n" + func_name_str = f"def {symbols[0].op_name}(" + for arg_name in symbols[0].arg_names: + func_name_str += f"{arg_name}, " + func_name_str += "_builder=None):\n" + + return_str = f"\treturn core.extern_elementwise(\"{self._name}\", libdevice_path(), [" + for arg_name in symbols[0].arg_names: + return_str += f"{arg_name}, " + return_str += "], \n" + + arg_type_symbol_dict_str = "{" + for symbol in symbols: + arg_type_symbol_dict_str += "(" + for arg_type in symbol.arg_types: + arg_type_symbol_dict_str += f'core.dtype("{arg_type}"),' + ret_type = f'core.dtype("{symbol.ret_type}")' + arg_type_symbol_dict_str += "): (\"" + symbol.name + "\", " + ret_type + "),\n" + arg_type_symbol_dict_str += "}" + + return_str += arg_type_symbol_dict_str + return_str += f", is_pure={self.is_pure}" + return_str += ", _builder=_builder)\n" + + func_str += func_name_str + return_str + "\n" + file_str = import_str + header_str + func_str + + return file_str + + +class LLVMDisassembler: + _path: str + _ll_file: str + + def __init__(self, path) -> None: + ''' + Invoke llvm-dis to disassemble the given file. + :param path: path to llvm-dis + ''' + self._path = path + self._ll_file = "/tmp/extern_lib.ll" + + def disasm(self, lib_path: str) -> None: + subprocess.Popen([self._path, lib_path, "-o", self.ll_file], stdout=subprocess.PIPE).communicate() + + @property + def ll_file(self) -> str: + return self._ll_file + + @property + def path(self) -> str: + return self._path + + +extern_libs = ["libdevice"] + + +def build( + llvm_dis_path: str, + lib_path: str, + lib_name: str, + output_dir: str, +) -> None: + ''' + Interface function to build the library file. + :param llvm_dis_path: path to the llvm-dis binary + :param lib_path: path to the external library file + :param lib_name: name of the library + :param output_dir: path to the output directory + ''' + if lib_name == "libdevice": + extern_lib = Libdevice(lib_path) + else: + raise Exception(f"Unknown extern library: {lib_name}") + + llvm_disassembler = LLVMDisassembler(llvm_dis_path) + llvm_disassembler.disasm(lib_path) + + extern_lib.parse_symbols(llvm_disassembler.ll_file) + extern_lib.generate_stub_file(output_dir) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--llvm-dis", dest="llvm_dis_path", help="Path to llvm-dis", default="llvm-dis") + parser.add_argument("--lib-path", dest="lib_path", help="Path to the extern library") + parser.add_argument("--lib-name", dest="lib_name", help="Name of the extern library") + parser.add_argument("--output", dest="output_dir", help="Output file path", default="/tmp/") + args = parser.parse_args() + + build(args.llvm_dis_path, args.lib_path, args.lib_name, args.output_dir) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/compile.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/compile.py new file mode 100644 index 0000000000000000000000000000000000000000..48561f8ab1f90bda02e513e7ccaa6b04806c401d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/compile.py @@ -0,0 +1,210 @@ +import binascii +import hashlib +import importlib.util +import sys +from argparse import ArgumentParser +from dataclasses import dataclass +from pathlib import Path +from typing import List + +import triton +import triton.backends + + +@dataclass +class CompileArgs: + ''' + A class to contain arguments from command-line parser. + ''' + path: str = '' + kernel_name: str = '' + signature: str = '' + grid: str = '' + target: str | None = None + num_warps: int = 1 + num_stages: int = 3 + out_name: str | None = None + out_path: Path | None = None + + +desc = """ +Triton ahead-of-time compiler: + +This program compiles the kernel with name `kernel-name` in the file at the +provided `path` into self-contained C source-code that embeds the `cubin` +data along with utilities to load, unload and launch the kernel. + +signature is provided as a list of (optionally divisibility-hinted) types +or constexpr values, e.g. + +`compile.py --kernel-name kernel --signature "*fp32:16, i32:16, 1024, i32" --out-name kernel /path/to/kernel.py` + +will compile triton.JITFunction of name `kernel` inside the file `/path/to/kernel.py`. +Said kernel will be specialized such that argument 0, 1 are assumed to be multiple of 16, +and argument 2 is assumed to be a compile-time constant of value 1024, i.e. it won't be part of the generated prototype. + +The resulting entry point will have signature + +CUresult kernel_{specialization_suffix}(CUstream stream, unsigned gX, unsigned gY, unsigned gZ, float* arg0, int32_t arg1, int32_t arg2) + +Different such specialized entry points can be combined using the `linker.py` script. + +NOTE: when resolving the scope of /path/to/kernel.py, the file will be executed from within its parent directory with the python interpreter +used to run this `compile.py` script +""" + + +def main(): + # command-line arguments + parser = ArgumentParser(description=desc) + parser.add_argument("path", + help="Path to Python source containing desired kernel in its scope. File will be executed.") + parser.add_argument("--kernel-name", "-n", type=str, default="", help="Name of the kernel to compile", + required=True) + parser.add_argument( + "--target", "-t", type=str, default=None, + help="The target to compile towards, in format of '::'; " + "e.g., 'cuda:80:32', 'hip:gfx942:64'. Default to None, which means using current machine's GPU target") + parser.add_argument("--num-warps", "-w", type=int, default=1, help="Number of warps to launch the kernel") + parser.add_argument("--num-stages", "-ns", type=int, default=3, + help="Number of stages (meta-parameter of the kernel)") + parser.add_argument("--out-name", "-on", type=str, default=None, help="Out name for the compiled kernel") + parser.add_argument("--out-path", "-o", type=Path, default=None, help="Out filename") + parser.add_argument("--signature", "-s", type=str, help="Signature of the kernel", required=True) + parser.add_argument("--grid", "-g", type=str, help="Launch grid of the kernel", required=True) + cli_args = parser.parse_args() + args = CompileArgs(**vars(cli_args)) # A sanity check to ensure class CompileArgs is updated as well. + compile_kernel(args) + + +def compile_kernel(args: CompileArgs): + out_name = args.out_name if args.out_name else args.kernel_name + out_path = args.out_path if args.out_path else Path(out_name) + + # execute python sources and extract functions wrapped in JITFunction + arg_path = Path(args.path) + sys.path.insert(0, str(arg_path.parent)) + spec = importlib.util.spec_from_file_location(arg_path.stem, arg_path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + kernel = getattr(mod, args.kernel_name) + grid = args.grid.split(",") + assert len(grid) == 3 + + # validate and parse signature + signature = list(map(lambda s: s.strip(" "), args.signature.split(","))) + + def hash_signature(signature: List[str]): + m = hashlib.sha256() + m.update(" ".join(signature).encode()) + return m.hexdigest()[:8] + + meta_sig = f"warps{args.num_warps}xstages{args.num_stages}" + sig_hash = hash_signature(signature + [meta_sig]) + + def constexpr(s): + try: + ret = int(s) + return ret + except ValueError: + pass + try: + ret = float(s) + return ret + except ValueError: + pass + return None + + hints = {(i, ): constexpr(s.split(":")[1]) for i, s in enumerate(signature) if ":" in s} + hints = {k: v for k, v in hints.items() if v is not None} + constants = {kernel.arg_names[i]: constexpr(s) for i, s in enumerate(signature)} + constants = {k: v for k, v in constants.items() if v is not None} + for key, value in hints.items(): + if value == 1: + constants[kernel.arg_names[key[0]]] = value + signature = {kernel.arg_names[i]: s.split(":")[0] for i, s in enumerate(signature)} + for key in constants: + signature[key] = 'constexpr' + const_sig = 'x'.join([str(v) for v in constants.values()]) + doc_string = [f"{k}={v}" for k, v in constants.items()] + doc_string += [f"num_warps={args.num_warps}", f"num_stages={args.num_stages}"] + # compile ast into cubin + for h in hints.values(): + assert h in [1, 16], f"Only 1 and 16 are valid hints, got {h}" + attrs = {k: [["tt.divisibility", 16]] for k, v in hints.items() if v == 16} + src = triton.compiler.ASTSource(fn=kernel, constexprs=constants, signature=signature, attrs=attrs) + + target = triton.backends.compiler.GPUTarget(*args.target.split(":")) \ + if args.target else triton.runtime.driver.active.get_current_target() + backend = triton.compiler.make_backend(target) + kwargs = {"num_warps": args.num_warps, "num_stages": args.num_stages} + options = backend.parse_options(kwargs) + ccinfo = triton.compile(src, target=target, options=options.__dict__) + + if getattr(ccinfo.metadata, "global_scratch_size", 0) > 0: + raise RuntimeError("AOT compiling kernels with global scratch requirements is not yet implemented") + if ccinfo.metadata.profile_scratch_size > 0: + raise RuntimeError("AOT compiling kernels with profile scratch requirements is not yet implemented") + + arg_names = [] + arg_types = [] + arg_names_not_1 = [] + arg_types_not_1 = [] + for i, arg_name in enumerate(kernel.arg_names): + if arg_name not in constants: + arg_names.append(arg_name) + arg_types.append(signature[arg_name]) + arg_names_not_1.append(arg_name) + arg_types_not_1.append(signature[arg_name]) + elif hints.get((i, ), None) == 1: + arg_names.append(arg_name) + arg_types.append("i32") + + # dump C stub code + suffix = '' + for i, ty in enumerate(signature.values()): + suffix += str(i) + if hints.get((i, ), None) == 1: + suffix += 'c' + if hints.get((i, ), None) == 16: + suffix += 'd' + func_name = '_'.join([out_name, sig_hash, suffix]) + asm = ccinfo.asm[backend.binary_ext] # store binary data once + + hex_ = str(binascii.hexlify(asm))[2:-1] + + ty_to_cpp = triton.runtime.driver.active.map_python_to_cpp_type + + params = { + "kernel_name": func_name, + "triton_kernel_name": args.kernel_name, + "bin_size": len(asm), + "bin_data": ", ".join([f"0x{x}{y}" for x, y in zip(hex_[::2], hex_[1::2])]), + "signature": ", ".join([f"{ty_to_cpp(ty)} {name}" for name, ty in zip(arg_names_not_1, arg_types_not_1)]), + "full_signature": ", ".join([f"{ty_to_cpp(ty)} {name}" for name, ty in zip(arg_names, arg_types)]), + "arg_pointers": ", ".join([f"&{arg}" for arg in arg_names_not_1] + ["&global_scratch"] + ["&profile_scratch"]), + "num_args": len(arg_names_not_1) + 2, # +2 for global and profile scratch + "kernel_docstring": doc_string, + "shared": ccinfo.metadata.shared, + "num_warps": args.num_warps, + "algo_info": "_".join([const_sig, meta_sig]), + "gridX": grid[0], + "gridY": grid[1], + "gridZ": grid[2], + "_placeholder": "", + } + output_files = [] + backend_name = target.backend + template_dir = Path(__file__).parent / "extra" / backend_name + for template_path in template_dir.glob('compile.*'): + ext = template_path.suffix + output_file = out_path.with_suffix(f".{sig_hash}_{suffix}{ext}") + with output_file.open("w") as fp: + fp.write(template_path.read_text().format(**params)) + output_files.append(output_file) + + return func_name, output_files + + +if __name__ == "__main__": + main() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/disasm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/disasm.py new file mode 100644 index 0000000000000000000000000000000000000000..c2301fd2eaab5b7e1e7b6b1f2f18e2962b26cabd --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/disasm.py @@ -0,0 +1,143 @@ +# MIT License + +# Copyright (c) 2020 Da Yan @ HKUST + +# 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. + +import functools +import os +import re +import subprocess +import tempfile + +FLINE_RE = re.compile(r'\s*/\*\w{4}\*/\s*([^;]*;)\s*/\* 0x(\w{16}) \*/\s*') +SLINE_RE = re.compile(r'\s*/\* 0x(\w{16}) \*/\s*') +FNAME_RE = re.compile(r'\s*Function : (\w+)\s*') +BRA_RE = re.compile(r'(.*BRA(?:\.U)? )(0x\w+);') + + +def parseCtrl(sline): + enc = int(SLINE_RE.match(sline).group(1), 16) + stall = (enc >> 41) & 0xf + yld = (enc >> 45) & 0x1 + wrtdb = (enc >> 46) & 0x7 + readb = (enc >> 49) & 0x7 + watdb = (enc >> 52) & 0x3f + + yld_str = 'Y' if yld == 0 else '-' + wrtdb_str = '-' if wrtdb == 7 else str(wrtdb) + readb_str = '-' if readb == 7 else str(readb) + watdb_str = '--' if watdb == 0 else f'{watdb:02d}' + return f'{watdb_str}:{readb_str}:{wrtdb_str}:{yld_str}:{stall:x}' + + +def processSassLines(fline, sline, labels): + asm = FLINE_RE.match(fline).group(1) + # Remove tailing space + if asm.endswith(" ;"): + asm = asm[:-2] + ";" + ctrl = parseCtrl(sline) + # BRA target address + if BRA_RE.match(asm) is not None: + target = int(BRA_RE.match(asm).group(2), 16) + if target in labels: + pass + else: + labels[target] = len(labels) + return (f'{ctrl}', f'{asm}') + + +@functools.lru_cache() +def get_sass(cubin_asm, fun=None): + fd, path = tempfile.mkstemp() + try: + with open(fd, 'wb') as cubin: + cubin.write(cubin_asm) + sass = extract(path, fun) + finally: + os.remove(path) + return sass + + +def path_to_cuobjdump(): + from triton import knobs + return knobs.nvidia.cuobjdump.path + + +def extract(file_path, fun): + cuobjdump = path_to_cuobjdump() + if fun is None: + sass_str = subprocess.check_output([cuobjdump, "-sass", file_path]) + else: + sass_str = subprocess.check_output([cuobjdump, "-fun", fun, "-sass", file_path]) + sass_lines = sass_str.splitlines() + line_idx = 0 + while line_idx < len(sass_lines): + line = sass_lines[line_idx].decode() + # format: + # function : + # .headerflags: ... + # /*0000*/ asmstr /*0x...*/ + # /*0x...*/ + + # Looking for new function header (function: ) + while FNAME_RE.match(line) is None: + line_idx += 1 + if line_idx < len(sass_lines): + line = sass_lines[line_idx].decode() + else: + return + + fname = FNAME_RE.match(line).group(1) + ret = '' + ret += f'Function:{fname}\n' + line_idx += 2 # bypass .headerflags + line = sass_lines[line_idx].decode() + # Remapping address to label + labels = {} # address -> label_idx + # store sass asm in buffer and them print them (for labels) + # (ctrl, asm) + asm_buffer = [] + while FLINE_RE.match(line) is not None: + # First line (Offset ASM Encoding) + fline = sass_lines[line_idx].decode() + line_idx += 1 + # Second line (Encoding) + sline = sass_lines[line_idx].decode() + line_idx += 1 + asm_buffer.append(processSassLines(fline, sline, labels)) + # peek the next line + line = sass_lines[line_idx].decode() + # Print sass + # label naming convention: LBB#i + for idx, (ctrl, asm) in enumerate(asm_buffer): + # Print label if this is BRA target + offset = idx * 16 + if offset in labels: + label_name = f'LBB{labels[offset]}' + ret += f'{label_name}:\n' + ret += ctrl + '\t' + # if this is BRA, remap offset to label + if BRA_RE.match(asm): + target = int(BRA_RE.match(asm).group(2), 16) + target_name = f'LBB{labels[target]}' + asm = BRA_RE.sub(rf'\1{target_name};', asm) + ret += asm + '\n' + ret += '\n' + return ret diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/extra/cuda/compile.c b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/extra/cuda/compile.c new file mode 100644 index 0000000000000000000000000000000000000000..c5ed8eb5626173e7988d4da820638fac43a7ebdc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/extra/cuda/compile.c @@ -0,0 +1,69 @@ +/* clang-format off */ +#include +#include +#include +#include +#include + + +// helpers to check for cuda errors +#define CUDA_CHECK(ans) {{\ + gpuAssert((ans), __FILE__, __LINE__);\ + }}\ + +static inline void gpuAssert(CUresult code, const char *file, int line) {{ + if (code != CUDA_SUCCESS) {{ + const char *prefix = "Triton Error [CUDA]: "; + const char *str; + cuGetErrorString(code, &str); + char err[1024] = {{0}}; + strcat(err, prefix); + strcat(err, str); + printf("%s\\n", err); + exit(code); + }} +}} + +// globals +#define CUBIN_NAME {kernel_name}_cubin +CUmodule {kernel_name}_mod = NULL; +CUfunction {kernel_name}_func = NULL; +unsigned char CUBIN_NAME[{bin_size}] = {{ {bin_data} }}; + + +void unload_{kernel_name}(void) {{ + CUDA_CHECK(cuModuleUnload({kernel_name}_mod)); +}} + +// TODO: some code duplication with `runtime/backend/cuda.c` +void load_{kernel_name}() {{ + int dev = 0; + void *bin = (void *)&CUBIN_NAME; + int shared = {shared}; + CUDA_CHECK(cuModuleLoadData(&{kernel_name}_mod, bin)); + CUDA_CHECK(cuModuleGetFunction(&{kernel_name}_func, {kernel_name}_mod, "{triton_kernel_name}")); + // set dynamic shared memory if necessary + int shared_optin; + CUDA_CHECK(cuDeviceGetAttribute(&shared_optin, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN, dev)); + if (shared > 49152 && shared_optin > 49152) {{ + CUDA_CHECK(cuFuncSetCacheConfig({kernel_name}_func, CU_FUNC_CACHE_PREFER_SHARED)); + CUDA_CHECK(cuFuncSetAttribute({kernel_name}_func, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shared_optin)) + }} +}} + +/* +{kernel_docstring} +*/ +CUresult {kernel_name}(CUstream stream, {signature}) {{ + if ({kernel_name}_func == NULL) + load_{kernel_name}(); + unsigned int gX = {gridX}; + unsigned int gY = {gridY}; + unsigned int gZ = {gridZ}; + CUdeviceptr global_scratch = 0; + CUdeviceptr profile_scratch = 0; + void *args[{num_args}] = {{ {arg_pointers} }}; + // TODO: shared memory + if(gX * gY * gZ > 0) + return cuLaunchKernel({kernel_name}_func, gX, gY, gZ, {num_warps} * 32, 1, 1, {shared}, stream, args, NULL); +}} diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/extra/cuda/compile.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/extra/cuda/compile.h new file mode 100644 index 0000000000000000000000000000000000000000..d98b7063b6ae6292b65b61abf5a30c58b7d28e95 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/extra/cuda/compile.h @@ -0,0 +1,14 @@ +#ifndef TT_KERNEL_INCLUDES +#define TT_KERNEL_INCLUDES + +#include +#include +#include +#include + +#endif + +void unload_{kernel_name}(void); +void load_{kernel_name}(void); +// tt-linker: {kernel_name}:{full_signature}:{algo_info} +CUresult{_placeholder} {kernel_name}(CUstream stream, {signature}); diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/extra/hip/compile.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/extra/hip/compile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c8a9c1b2d9f3b09d60a6a43b195b155b67e571f7 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/extra/hip/compile.cpp @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2025, Advanced Micro Devices, Inc. All rights reserved. + +/* clang-format off */ +#include +#include +#include +#include +#include + +// helpers to check for hip errors +#define HIP_CHECK(ans) {{\ + gpuAssert((ans), __FILE__, __LINE__);\ + }}\ + +static inline void gpuAssert(hipError_t code, const char *file, int line) {{ + if (code != hipSuccess) {{ + const char *prefix = "Triton Error [HIP]: "; + const char *str; + hipDrvGetErrorString(code, &str); + char err[1024] = {{0}}; + strcat(err, prefix); + strcat(err, str); + printf("%s\\n", err); + exit(code); + }} +}} + +// globals +#define HSACO_NAME {kernel_name}_hsaco +hipModule_t {kernel_name}_mod = nullptr; +hipFunction_t {kernel_name}_func = nullptr; +unsigned char HSACO_NAME[{bin_size}] = {{ {bin_data} }}; + + +void unload_{kernel_name}(void) {{ + HIP_CHECK(hipModuleUnload({kernel_name}_mod)); +}} + + +void load_{kernel_name}() {{ + int dev = 0; + void *bin = (void *)&HSACO_NAME; + int shared = {shared}; + HIP_CHECK(hipModuleLoadData(&{kernel_name}_mod, bin)); + HIP_CHECK(hipModuleGetFunction(&{kernel_name}_func, {kernel_name}_mod, "{triton_kernel_name}")); +}} + +/* +{kernel_docstring} +*/ +hipError_t {kernel_name}(hipStream_t stream, {signature}) {{ + if ({kernel_name}_func == nullptr) + load_{kernel_name}(); + unsigned int gX = {gridX}; + unsigned int gY = {gridY}; + unsigned int gZ = {gridZ}; + hipDeviceptr_t global_scratch = 0; + hipDeviceptr_t profile_scratch = 0; + void *args[{num_args}] = {{ {arg_pointers} }}; + // TODO: shared memory + if(gX * gY * gZ > 0) + return hipModuleLaunchKernel({kernel_name}_func, gX, gY, gZ, {num_warps} * warpSize, 1, 1, {shared}, stream, args, nullptr); + else + return hipErrorInvalidValue; +}} diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/extra/hip/compile.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/extra/hip/compile.h new file mode 100644 index 0000000000000000000000000000000000000000..cc5007ad939277df890306a84a91c0b87f1c8825 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/extra/hip/compile.h @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2025, Advanced Micro Devices, Inc. All rights reserved. + +#pragma once + +#include +#include +#include +#include + +void unload_{kernel_name}(void); +void load_{kernel_name}(void); +hipError_t{_placeholder} {kernel_name}(hipStream_t stream, {signature}); diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/link.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/link.py new file mode 100644 index 0000000000000000000000000000000000000000..75a1157a52f92bbd5d2eae640af97ea360da2ef3 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/link.py @@ -0,0 +1,322 @@ +from collections import defaultdict +from pathlib import Path +from typing import Sequence, Union + +from dataclasses import dataclass + + +def _exists(x): + return x is not None + + +class LinkerError(Exception): + pass + + +@dataclass +class KernelLinkerMeta: + orig_kernel_name: str + arg_names: Sequence[str] + arg_ctypes: Sequence[str] + sizes: Sequence[Union[int, None]] + sig_hash: str + triton_suffix: str + suffix: str + num_specs: int + """ number of specialized arguments """ + + +class HeaderParser: + + def __init__(self) -> None: + import re + + # [kernel_name, c signature] + self.linker_directives = re.compile("//[\\s]*tt-linker:[\\s]*([\\w]+):(.+):(.+)") + # [name, hash, suffix] + self.kernel_name = re.compile("^([\\w]+)_([\\w]+)_([\\w]+)$") + # [(type, name)] + self.c_sig = re.compile("[\\s]*(\\w+)\\s(\\w+)[,]?") + # [d|c] + self.arg_suffix = re.compile("[c,d]") + + self.kernels = defaultdict(list) + + def extract_linker_meta(self, header: str): + for ln in header.splitlines(): + if ln.startswith("//"): + m = self.linker_directives.match(ln) + if _exists(m): + ker_name, c_sig, algo_info = m.group(1), m.group(2), m.group(3) + name, sig_hash, suffix = self._match_name(ker_name) + c_types, arg_names = self._match_c_sig(c_sig) + num_specs, sizes = self._match_suffix(suffix, c_sig) + self._add_kernel( + "_".join([name, algo_info]), + KernelLinkerMeta( + orig_kernel_name=name, + arg_names=arg_names, + arg_ctypes=c_types, + sizes=sizes, + sig_hash=sig_hash, + triton_suffix=suffix, + suffix=suffix, + num_specs=num_specs, + ), + ) + + def _match_name(self, ker_name: str): + m = self.kernel_name.match(ker_name) + if _exists(m): + name, sig_hash, suffix = m.group(1), m.group(2), m.group(3) + return name, sig_hash, suffix + raise LinkerError(f"{ker_name} is not a valid kernel name") + + def _match_c_sig(self, c_sig: str): + m = self.c_sig.findall(c_sig) + if len(m): + tys, args = [], [] + for ty, arg_name in m: + tys.append(ty) + args.append(arg_name) + return tys, args + + raise LinkerError(f"{c_sig} is not a valid argument signature") + + def _match_suffix(self, suffix: str, c_sig: str): + args = c_sig.split(",") + s2i = {"c": 1, "d": 16} + num_specs = 0 + sizes = [] + # scan through suffix, first find the index, + # then see if it is followed by d or c + for i in range(len(args)): + pos = suffix.find(str(i)) + if pos == -1: + raise LinkerError(f"{suffix} is not a valid kernel suffix") + pos += len(str(i)) + if self.arg_suffix.match(suffix, pos): + num_specs += 1 + sizes.extend([None] * (i - len(sizes))) + sizes.append(s2i[suffix[pos]]) + pos += 1 + if i < len(args) - 1: + suffix = suffix[pos:] + else: + sizes.extend([None] * (len(args) - len(sizes))) + return num_specs, sizes + + def _add_kernel(self, name: str, ker: KernelLinkerMeta): + if name in self.kernels: + last: KernelLinkerMeta = self.kernels[name][-1] + + for cur, new_ in zip(last.arg_ctypes, ker.arg_ctypes): + if cur != new_: + raise LinkerError( + f"Mismatched signature for kernel {name}: \n\texisting sig is: {','.join(last.arg_ctypes)}\n\tcurrent is: {','.join(ker.arg_ctypes)}" + ) + + self.kernels[name].append(ker) + + +def gen_signature_with_full_args(m): + return ", ".join([f"{ty} {arg}" for ty, arg in zip(m.arg_ctypes, m.arg_names)]) + + +def gen_signature(m): + arg_types = [ty for ty, hint in zip(m.arg_ctypes, m.sizes) if hint != 1] + arg_names = [arg for arg, hint in zip(m.arg_names, m.sizes) if hint != 1] + sig = ", ".join([f"{ty} {arg}" for ty, arg in zip(arg_types, arg_names)]) + return sig + + +# generate declarations of kernels with meta-parameter and constant values +def make_algo_decls(name: str, metas: Sequence[KernelLinkerMeta]) -> str: + return f""" +CUresult {name}(CUstream stream, {gen_signature_with_full_args(metas[-1])}); +void load_{name}(); +void unload_{name}(); + """ + + +# generate declarations of kernels with meta-parameter and constant values +def make_global_decl(meta: KernelLinkerMeta) -> str: + return f""" +CUresult {meta.orig_kernel_name}_default(CUstream stream, {gen_signature_with_full_args(meta)}); +CUresult {meta.orig_kernel_name}(CUstream stream, {gen_signature_with_full_args(meta)}, int algo_id); +void load_{meta.orig_kernel_name}(); +void unload_{meta.orig_kernel_name}(); + """ + + +# generate dispatcher function for kernels with different meta-parameter and constant values +def make_default_algo_kernel(meta: KernelLinkerMeta) -> str: + src = f"CUresult {meta.orig_kernel_name}_default(CUstream stream, {gen_signature_with_full_args(meta)}){{\n" + src += (f" return {meta.orig_kernel_name}(stream, {', '.join(meta.arg_names)}, 0);\n") + src += "}\n" + return src + + +# generate dispatcher function for kernels with different integer value hints +def make_kernel_hints_dispatcher(name: str, metas: Sequence[KernelLinkerMeta]) -> str: + src = f"// launcher for: {name}\n" + for meta in sorted(metas, key=lambda m: -m.num_specs): + src += f"CUresult {meta.orig_kernel_name}_{meta.sig_hash}_{meta.suffix}(CUstream stream, {gen_signature(meta)});\n" + src += "\n" + + src += (f"CUresult {name}(CUstream stream, {gen_signature_with_full_args(metas[-1])}){{") + src += "\n" + for meta in sorted(metas, key=lambda m: -m.num_specs): + cond_fn = ( # + lambda val, hint: f"({val} % {hint} == 0)" # + if hint == 16 # + else f"({val} == {hint})" # + if hint == 1 # + else None) + conds = " && ".join([ # + cond_fn(val, hint) # + for val, hint in zip(meta.arg_names, meta.sizes) # + if hint is not None + ]) + src += (f" if ({conds})\n" if any(meta.sizes) else "if (1)\n" + ) # Edge case where no specializations hence no dispatching required + arg_names = [arg for arg, hint in zip(meta.arg_names, meta.sizes) if hint != 1] + src += f" return {meta.orig_kernel_name}_{meta.sig_hash}_{meta.suffix}(stream, {', '.join(arg_names)});\n" + src += "\n" + src += " return CUDA_ERROR_INVALID_VALUE;\n" + src += "}\n" + + for mode in ["load", "unload"]: + src += f"\n// {mode} for: {name}\n" + for meta in sorted(metas, key=lambda m: -m.num_specs): + src += f"void {mode}_{meta.orig_kernel_name}_{meta.sig_hash}_{meta.suffix}();\n" + src += f"void {mode}_{name}() {{" + src += "\n" + for meta in sorted(metas, key=lambda m: -m.num_specs): + src += (f" {mode}_{meta.orig_kernel_name}_{meta.sig_hash}_{meta.suffix}();\n") + src += "}\n" + return src + + +# generate dispatcher function for kernels with different meta-parameter and constant values +def make_kernel_meta_const_dispatcher(meta: KernelLinkerMeta) -> str: + src = f"CUresult {meta.orig_kernel_name}(CUstream stream, {gen_signature_with_full_args(meta)}, int algo_id){{\n" + src += f" assert (algo_id < (int)sizeof({meta.orig_kernel_name}_kernels));\n" + src += f" return {meta.orig_kernel_name}_kernels[algo_id](stream, {', '.join(meta.arg_names)});\n" + src += "}\n" + return src + + +# generate definition of function pointers of kernel dispatchers based on meta-parameter and constant values +def make_func_pointers(names: str, meta: KernelLinkerMeta) -> str: + # the table of hint dispatchers + src = f"typedef CUresult (*kernel_func_t)(CUstream stream, {gen_signature_with_full_args(meta)});\n" + src += f"kernel_func_t {meta.orig_kernel_name}_kernels[] = {{\n" + for name in names: + src += f" {name},\n" + src += "};\n" + return src + + +# generate definition for load/unload functions for kernels with different meta-parameter and constant values +def make_kernel_load_def(names: str, meta: KernelLinkerMeta) -> str: + src = "" + for mode in ["load", "unload"]: + src += f"void {mode}_{meta.orig_kernel_name}(void){{\n" + for name in names: + src += f" {mode}_{name}();\n" + src += "}\n\n" + return src + + +def make_get_num_algos_decl(meta: KernelLinkerMeta) -> str: + src = f"int {meta.orig_kernel_name}_get_num_algos(void);" + return src + + +def make_get_num_algos_def(meta: KernelLinkerMeta) -> str: + src = f"int {meta.orig_kernel_name}_get_num_algos(void){{\n" + src += f" return (int)(sizeof({meta.orig_kernel_name}_kernels) / sizeof({meta.orig_kernel_name}_kernels[0]));\n" + src += "}\n" + return src + + +desc = """ +Triton ahead-of-time linker: + +This program takes in header files generated by compile.py, and generates a +single entry-point responsible for dispatching the user's input to the right +kernel given the specializations that were compiled. + +Example usage: +python link.py /path/to/headers/*.h -o kernel_name +""" + +if __name__ == "__main__": + from argparse import ArgumentParser + + parser = ArgumentParser(description=desc) + parser.add_argument( + "headers", + nargs="+", + help="Paths to header files to link. Must include linker directive annotations (autogenerated by ttc)", + ) + parser.add_argument("--out", "-o", type=Path, help="Out filename") + parser.add_argument( + "--prefix", + type=str, + default="", + help="String to prefix kernel dispatcher names", + ) + args = parser.parse_args() + + # metadata + parser = HeaderParser() + includes = [] + for header in args.headers: + h_path = Path(header) + h_str = h_path.read_text() + includes.append(h_path.name) + parser.extract_linker_meta(h_str) + + # generate headers + algo_decls = [make_algo_decls(name, meta) for name, meta in parser.kernels.items()] + meta_lists = [meta for name, meta in parser.kernels.items()] + meta = meta_lists[0][0] + get_num_algos_decl = make_get_num_algos_decl(meta) + global_decl = make_global_decl(meta) + with args.out.with_suffix(".h").open("w") as fp: + out = "#include \n" + out += "\n".join(algo_decls) + out += "\n" + out += get_num_algos_decl + out += "\n" + out += global_decl + fp.write(out) + + # generate source + defs = [make_kernel_hints_dispatcher(name, meta) for name, meta in parser.kernels.items()] + names = [name for name in parser.kernels.keys()] + func_pointers_def = make_func_pointers(names, meta) + meta_const_def = make_kernel_meta_const_dispatcher(meta) + load_unload_def = make_kernel_load_def(names, meta) + get_num_algos_def = make_get_num_algos_def(meta) + default_algo_kernel = make_default_algo_kernel(meta) + with args.out.with_suffix(".c").open("w") as fp: + out = "" + out += "#include \n" + out += "#include \n" + out += "#include \n" + out += "\n" + out += "\n".join(defs) + out += "\n" + out += func_pointers_def + out += "\n" + out += get_num_algos_def + out += "\n" + out += meta_const_def + out += "\n" + out += load_unload_def + out += "\n" + out += default_algo_kernel + fp.write(out) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/mxfp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/mxfp.py new file mode 100644 index 0000000000000000000000000000000000000000..1b129c1aef2ddc8165a2f81718b1be980573c458 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/mxfp.py @@ -0,0 +1,301 @@ +""" +Helper classes for working with low precision floating point types that +align with the opencompute (OCP) microscaling (MX) specification. + * MXFP4Tensor: 4-bit E2M1 floating point data + * MXScaleTensor: 8-bit E8M0 floating point data +Reference: https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf +""" + +import torch + + +class MXFP4Tensor: + + def __init__(self, data=None, size=None, device=None): + """ + Tensor class for working with four bit E2M1 floating point data as defined by the + opencompute microscaling specification. + + + Parameters: + - data: A torch tensor of float32 numbers to convert to fp4e2m1 microscaling format. + - size: The size of the tensor to create. + - device: The device on which to create the tensor. + """ + self.device = device + if data is not None: + assert isinstance(data, torch.Tensor), "Parameter data must be a torch tensor" + self.device = data.device + self.data = self._from_float(data) + elif size is not None: + self.size = size if isinstance(size, tuple) else (size, ) + else: + raise ValueError("Either parameter data or size must be provided") + + def random(self): + S = torch.randint(0, 2, size=self.size, dtype=torch.uint8, device=self.device) + E = torch.randint(0, 4, size=self.size, dtype=torch.uint8, device=self.device) + M = torch.randint(0, 2, size=self.size, dtype=torch.uint8, device=self.device) + + self.data = ((S << 3) | (E << 1) | M).type(torch.uint8) + return self + + def to(self, dtype): + """ + Convert fp4e2m1 data to float32. + + Returns: + - A torch tensor of type dtype representing the fp4e2m1 data. + """ + assert dtype == torch.float32, "Currently only float32 is supported for fp4e2m1 to float conversion" + + data = self.data + S = ((data >> 3) & 0x1).type(dtype) + E = ((data >> 1) & 0x3).type(dtype) + M = (data & 0x1).type(dtype) + + # The MXF4 E2M1 spec defines 0bS000 as zero + value = torch.zeros_like(S) + is_zero = (E == 0) & (M == 0) + non_zero_mask = ~is_zero + if non_zero_mask.any(): + S_nz = S[non_zero_mask] + E_nz = E[non_zero_mask] + M_nz = M[non_zero_mask] + + sign = torch.pow(-1, S_nz) + # Normal and subnormal handling for the exponent and mantissa + exponent = torch.where(E_nz == 0, E_nz, E_nz - 1) + mantissa = torch.where(E_nz == 0, M_nz * 0.5, 1.0 + M_nz * 0.5) + value_nz = sign * torch.pow(2, exponent) * mantissa + + value[non_zero_mask] = value_nz + + # For zeros, the values must remain zero with the correct sign + value[is_zero & (S == 1)] *= -1 + return value.type(torch.float32) + + def _from_float(self, values): + """ + Convert float32 numbers to mxf4 e2m1 format. + * No encodings are reserved for Inf or NaN in mxf4. + * Conversion from float supports roundTiesToEven rounding mode. + * If a value exceeds the mxf4 representable range after rounding, + clamps to the maximum mxf4 magnitude, preserving the sign. + * If a value has magnitude less than the minimum subnormal magnitude + in mxf4 after rounding, converts to zero. + + Parameters: + - values: A torch tensor of float32 numbers to convert to fp4 format. + """ + S = torch.signbit(values).type(torch.uint8) + abs_values = torch.abs(values) + + is_zero = (abs_values == 0) + is_invalid = torch.isnan(values) | torch.isinf(values) + + # Enumerate all possible E2M1 exponent and mantissa values. We will + # use these to compare the distance between float32 and all possible + # E2M1 floats to find the nearest E2M1 representable value + E_bits = torch.tensor([0, 1, 2, 3], dtype=torch.uint8, device=self.device) + M_bits = torch.tensor([0, 1], dtype=torch.uint8, device=self.device) + + candidate_values = [] + candidate_E = [] + candidate_M = [] + + for E in E_bits: + if E == 0: + # Subnormals + exponent = 0 + for M in M_bits: + significand = M * 0.5 + value = significand * (2**exponent) + candidate_values.append(value) + candidate_E.append(E) + candidate_M.append(M) + else: + # Normals + exponent = E.item() - 1 + for M in M_bits: + significand = 1.0 + M * 0.5 + value = significand * (2**exponent) + candidate_values.append(value) + candidate_E.append(E) + candidate_M.append(M) + + candidates = torch.tensor(candidate_values, dtype=torch.float32, device=self.device) + candidate_E = torch.tensor(candidate_E, dtype=torch.uint8, device=self.device) + candidate_M = torch.tensor(candidate_M, dtype=torch.uint8, device=self.device) + + abs_values_flat = abs_values.view(-1) + N = abs_values_flat.shape[0] + abs_values_expanded = abs_values_flat.unsqueeze(1) + + # Clamp invalid values to the max e2m1 representable value + max_candidate_value = candidates.max().item() + abs_values_flat[is_invalid.view(-1)] = max_candidate_value + + # Compute distance between all abs_values and candidate e2m1 values + errors = torch.abs(abs_values_expanded - candidates.unsqueeze(0)) + + # To implement roundTiesToEven, we need to break ties by preferring + # even mantissas (M == 0). We do so by adding an epsilon bias to shift + # the closest candidate with an even mantissa closer to the float value + min_errors, _ = torch.min(errors, dim=1, keepdim=True) + is_tie = (errors == min_errors) + # More than one candidate has the min error for some float value + if is_tie.sum() > 1: + M_bits_expanded = candidate_M.unsqueeze(0).expand(N, -1) + tie_breaker = (M_bits_expanded == 0).type(torch.int32) + + errors = errors - (tie_breaker * 1e-6) + + best_indices = torch.argmin(errors, dim=1) + + E_selected = candidate_E[best_indices] + M_selected = candidate_M[best_indices] + E = E_selected.view(abs_values.shape) + M = M_selected.view(abs_values.shape) + + E[is_zero] = 0 + M[is_zero] = 0 + + return ((S << 3) | (E << 1) | M).type(torch.uint8) + + def to_packed_tensor(self, dim): + """ + Packs two e2m1 elements into a single uint8 along the specified dimension. + + Parameters: + - dim: The dimension along which to pack the elements. + + Returns: + - A torch tensor of dtype uint8 with two e2m1 elements packed into one uint8. + """ + data = self.data + assert 0 <= dim < data.ndim, \ + "The dimension to pack along is not within the range of tensor dimensions" + + size_along_dim = data.size(dim) + new_size_along_dim = (size_along_dim + 1) // 2 + + # If the size is odd, we pad the data along dim with zeros at the end + if size_along_dim % 2 != 0: + pad_sizes = [0] * (2 * data.ndim) + pad_index = (data.ndim - dim - 1) * 2 + 1 + pad_sizes[pad_index] = 1 + data = torch.nn.functional.pad(data, pad_sizes, mode='constant', value=0) + + new_shape = list(data.shape) + new_shape[dim] = new_size_along_dim + new_shape.insert(dim + 1, 2) # packed dimension of length 2 + data = data.reshape(*new_shape) + + low = data.select(dim + 1, 0) + high = data.select(dim + 1, 1) + packed = (high << 4) | low + + return packed + + def unpack_packed_tensor(self, packed_tensor, dim, original_shape): + """ + Unpacks a tensor where two fp4 elements are packed into a single uint8. + + Parameters: + - packed_tensor: The packed tensor + - dim: The dimension along which the tensor was packed. + - original_shape: The shape of the original tensor before packing. + + Returns: + - A tensor with the original data unpacked into uint8 elements containing one + fp4e2m1 element in the least significant bits. + """ + high = (packed_tensor >> 4) & 0xF + low = packed_tensor & 0xF + + stacked = torch.stack((low, high), dim=dim + 1) + + # Flatten along dim and dim+1 and then merge + shape = list(stacked.shape) + new_shape = shape[:dim] + [shape[dim] * 2] + shape[dim + 2:] + data = stacked.reshape(*new_shape) + + # Remove any padding + if original_shape[dim] % 2 != 0: + indices = [slice(None)] * data.ndim + indices[dim] = slice(0, original_shape[dim]) + data = data[tuple(indices)] + + return data.type(torch.uint8) + + +class MXScaleTensor: + + def __init__(self, data=None, size=None, device=None): + """ + Tensor class for working with microscaling E8M0 block scale factors. + + Parameters: + - data: A torch tensor of float32 numbers to convert to fp8e8m0 microscaling format. + - size: The size of the tensor to create. + - device: The device on which to create the tensor. + """ + self.device = device + if data is not None: + assert isinstance(data, torch.Tensor), "Parameter data must be a torch tensor" + self.device = data.device + self.data = self._from_float(data) + elif size is not None: + self.size = size if isinstance(size, tuple) else (size, ) + else: + raise ValueError("Either parameter data or size must be provided") + + def random(self, low=None, high=None): + """ + Generate random E8M0 data within a specified range. + * Excludes the NaN encoding (255). + """ + bias = 127 + + min_exponent = 0 if low is None else max(0, int(torch.log2(torch.tensor(low))) + bias) + max_exponent = 254 if high is None else min(254, max(0, int(torch.log2(torch.tensor(high))) + bias)) + assert min_exponent <= max_exponent, "Low must be less than or equal to high" + + E = torch.randint(min_exponent, max_exponent + 1, size=self.size, dtype=torch.uint8, device=self.device) + self.data = E + return self + + def to(self, dtype): + assert dtype == torch.float32, "Currently only float32 is supported for f8e8m0 to float conversion" + data = self.data.type(dtype) + is_nan = (data == 255) + e_biased = data.clone() + e_biased[is_nan] = 0 + e = e_biased - 127 + value = torch.pow(2.0, e) + value[is_nan] = torch.nan + return value.type(dtype) + + def _from_float(self, values): + """ + Convert float32 numbers to E8M0 format. + * Values <= 0, NaNs, and Infs are converted to the NaN encoding (255). + * Positive values are converted by computing the floor of log2(value) to get the exponent. + + Parameters: + - values: A torch tensor of float32 numbers to convert to E8M0 format. + """ + result = torch.empty_like(values, dtype=torch.uint8, device=self.device) + + is_invalid = torch.isnan(values) | torch.isinf(values) | (values <= 0) + result[is_invalid] = 255 + + valid_values = values[~is_invalid] + e = torch.floor(torch.log2(valid_values)) + e_biased = e + 127 + e_biased_int = e_biased.type(torch.int32) + e_biased_clamped = torch.clamp(e_biased_int, 0, 254) + result[~is_invalid] = e_biased_clamped.type(torch.uint8) + + return result diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/ragged_tma.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/ragged_tma.py new file mode 100644 index 0000000000000000000000000000000000000000..7029b7135d9fdaf64eabf8606f7d15ac3703d9fc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/ragged_tma.py @@ -0,0 +1,92 @@ +import triton +import triton.language as tl +from triton.tools.tensor_descriptor import TensorDescriptor + +# fmt: off + + +def create_ragged_descriptor(T, block_shape, ragged_dim=0): + """ + Given a 2- or 3-dimensional tensor T, this creates a 'ragged descriptor' + which behaves like a concatenation (along the first axis) of subarrays + of potentially unequal size. + + The load_ragged and store_ragged device functions can be used to read + and write from subarrays T[batch_offset : batch_offset + batch_size] + with hardware bounds-checking preventing any sort of leakage outside + the subarray. + """ + + block_shape = list(block_shape) + tensor_shape = list(T.shape) + rank = len(tensor_shape) + + if ragged_dim < 0: + ragged_dim += rank + + assert 0 <= ragged_dim < rank - 1, "last dimension cannot be ragged" + assert rank <= 3, "read-write ragged descriptors must have at most 3 dimensions" + + assert len(block_shape) == rank, "block shape must have same length as tensor shape" + + max_int = 0x7fff0000 + billion = 0x40000000 # == 2**30 + + assert tensor_shape[ragged_dim] <= billion, "number of rows may not exceed 2**30" + tensor_shape[ragged_dim] = billion + ragged_stride = T.stride(ragged_dim) + + # we prepend an extra two dimensions and rely on the fact that pointers + # have 64-bit wraparound semantics: + tma_stride = [2**34 - ragged_stride, ragged_stride] + [T.stride(i) for i in range(rank)] + tma_shape = [max_int, max_int] + tensor_shape + box_shape = [1, 1] + block_shape + + return TensorDescriptor(T, tma_shape, tma_stride, box_shape) + + +@triton.jit +def to_ragged_indices(batch_offset, batch_size, row): + """ + Helper function for load_ragged and store_ragged. + """ + + billion = 0x40000000 # == 2**30 + x = billion - batch_size + row + y = batch_offset + batch_size + + return billion, y, x + + +@triton.jit +def load_ragged(TMA, batch_offset, batch_size, coords, ragged_dim: tl.constexpr = 0): + """ + Read from a subarray T[batch_offset : batch_offset + batch_size] with + hardware bounds-checking, where reading outside the subarray gives zeros. + + Coords should be an appropriately-sized list of integers, just like in + TMA.load(). + """ + + tl.static_assert(len(TMA.shape) == len(coords) + 2, "TMA must be a read-write ragged descriptor") + + c0, c1, c2 = to_ragged_indices(batch_offset, batch_size, coords[ragged_dim]) + data = TMA.load([c0, c1] + coords[:ragged_dim] + [c2] + coords[ragged_dim + 1:]) + data = tl.reshape(data, data.shape[2:]) + return data + + +@triton.jit +def store_ragged(TMA, batch_offset, batch_size, coords, data, ragged_dim: tl.constexpr = 0): + """ + Write to a subarray T[batch_offset : batch_offset + batch_size] with + hardware bounds-checking, where writes outside the subarray are masked + correctly. + + Coords should be an appropriately-sized list of integers, just like in + TMA.store(). + """ + + c0, c1, c2 = to_ragged_indices(batch_offset, batch_size, coords[ragged_dim]) + data = tl.reshape(data, [1, 1] + data.shape) + TMA.store([c0, c1] + coords[:ragged_dim] + [c2] + coords[ragged_dim + 1:], data) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/tensor_descriptor.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/tensor_descriptor.py new file mode 100644 index 0000000000000000000000000000000000000000..f6ccb03659314737d6bd50b1ae8fb2bd7a350df2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/triton/tools/tensor_descriptor.py @@ -0,0 +1,34 @@ +from dataclasses import dataclass +from typing import List, Any +from triton._utils import validate_block_shape + + +@dataclass +class TensorDescriptor: + base: Any + shape: List[int] + strides: List[int] + block_shape: List[int] + padding: str = "zero" + + def __post_init__(self): + rank = len(self.shape) + assert len(self.strides) == rank, f"rank mismatch: {self}" + assert len(self.block_shape) == rank, f"rank mismatch: {self}" + assert rank > 0, "rank must not be zero" + assert rank <= 5, "rank cannot be more than 5" + ty = type(self.base) + if ty.__name__ not in ("FakeTensor", "FunctionalTensor"): + assert self.base.data_ptr() % 16 == 0, "base must be 16-byte aligned" + validate_block_shape(self.block_shape) + elem_bytes = self.base.dtype.itemsize + for stride in self.strides[:-1]: + assert (stride * elem_bytes) % 16 == 0, "strides must be 16-byte aligned" + assert self.strides[-1] == 1, "Last dimension must be contiguous" + assert self.padding == "zero" or self.padding == "nan", "Illegal value for padding" + if self.padding == "nan": + assert self.base.dtype.is_floating_point, "Padding option `nan` is only supported for floating point tensors" + + @staticmethod + def from_tensor(tensor: Any, block_shape: List[int], padding="zero"): + return TensorDescriptor(tensor, tensor.shape, tensor.stride(), block_shape, padding) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d5adb255aac551e8e91f8717d2e5162ef0c2e043 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/__init__.py @@ -0,0 +1,6 @@ +# IANA versions like 2020a are not valid PEP 440 identifiers; the recommended +# way to translate the version is to use YYYY.n where `n` is a 0-based index. +__version__ = "2025.2" + +# This exposes the original IANA version number. +IANA_VERSION = "2025b" diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Abidjan b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Abidjan new file mode 100644 index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Abidjan differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Accra b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Accra new file mode 100644 index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Accra differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Addis_Ababa b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Addis_Ababa new file mode 100644 index 0000000000000000000000000000000000000000..5f4ebcb7f9789c4ecda13ac66c2e768851113004 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Addis_Ababa differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Algiers b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Algiers new file mode 100644 index 0000000000000000000000000000000000000000..56a4dd2a19fac5cc1bb1951dedf3ae93e0b9e321 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Algiers differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Asmara b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Asmara new file mode 100644 index 0000000000000000000000000000000000000000..5f4ebcb7f9789c4ecda13ac66c2e768851113004 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Asmara differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Asmera b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Asmera new file mode 100644 index 0000000000000000000000000000000000000000..5f4ebcb7f9789c4ecda13ac66c2e768851113004 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Asmera differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Bamako b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Bamako new file mode 100644 index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Bamako differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Bangui b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Bangui new file mode 100644 index 0000000000000000000000000000000000000000..3d7a71ba0e96de946446fc96add2f38a806a44a5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Bangui differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Banjul b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Banjul new file mode 100644 index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Banjul differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Bissau b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Bissau new file mode 100644 index 0000000000000000000000000000000000000000..0da1d1e211bc6b9b081959c1d510583cb9eb7102 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Bissau differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Blantyre b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Blantyre new file mode 100644 index 0000000000000000000000000000000000000000..581bb0e08b616a433d422ccb8f958cbebdae1770 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Blantyre differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Brazzaville b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Brazzaville new file mode 100644 index 0000000000000000000000000000000000000000..3d7a71ba0e96de946446fc96add2f38a806a44a5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Brazzaville differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Bujumbura b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Bujumbura new file mode 100644 index 0000000000000000000000000000000000000000..581bb0e08b616a433d422ccb8f958cbebdae1770 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Bujumbura differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Cairo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Cairo new file mode 100644 index 0000000000000000000000000000000000000000..1e6d48d1ca4e5416913c41e8814dc045c57d5b58 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Cairo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Casablanca b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Casablanca new file mode 100644 index 0000000000000000000000000000000000000000..240ebb2bfb22642570a6053445a6e71864e7f48a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Casablanca differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Ceuta b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Ceuta new file mode 100644 index 0000000000000000000000000000000000000000..a461dceaa2adccd6cb3196b6eccf5395130881ff Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Ceuta differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Conakry b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Conakry new file mode 100644 index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Conakry differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Dakar b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Dakar new file mode 100644 index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Dakar differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Dar_es_Salaam b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Dar_es_Salaam new file mode 100644 index 0000000000000000000000000000000000000000..5f4ebcb7f9789c4ecda13ac66c2e768851113004 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Dar_es_Salaam differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Djibouti b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Djibouti new file mode 100644 index 0000000000000000000000000000000000000000..5f4ebcb7f9789c4ecda13ac66c2e768851113004 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Djibouti differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Douala b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Douala new file mode 100644 index 0000000000000000000000000000000000000000..3d7a71ba0e96de946446fc96add2f38a806a44a5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Douala differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/El_Aaiun b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/El_Aaiun new file mode 100644 index 0000000000000000000000000000000000000000..909c5f9682927c14e3e64e21da75559ad2e598f9 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/El_Aaiun differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Freetown b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Freetown new file mode 100644 index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Freetown differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Gaborone b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Gaborone new file mode 100644 index 0000000000000000000000000000000000000000..581bb0e08b616a433d422ccb8f958cbebdae1770 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Gaborone differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Harare b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Harare new file mode 100644 index 0000000000000000000000000000000000000000..581bb0e08b616a433d422ccb8f958cbebdae1770 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Harare differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Johannesburg b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Johannesburg new file mode 100644 index 0000000000000000000000000000000000000000..bada0638f8a2224a603f13afff16c0d8e986a591 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Johannesburg differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Juba b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Juba new file mode 100644 index 0000000000000000000000000000000000000000..0aba9ffd89dcbb47f1bf003dad75227f08d99679 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Juba differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Kampala b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Kampala new file mode 100644 index 0000000000000000000000000000000000000000..5f4ebcb7f9789c4ecda13ac66c2e768851113004 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Kampala differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Khartoum b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Khartoum new file mode 100644 index 0000000000000000000000000000000000000000..3f8e44b8a6e171a0fde96736ed9d4fcde1bcd4a8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Khartoum differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Kigali b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Kigali new file mode 100644 index 0000000000000000000000000000000000000000..581bb0e08b616a433d422ccb8f958cbebdae1770 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Kigali differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Kinshasa b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Kinshasa new file mode 100644 index 0000000000000000000000000000000000000000..3d7a71ba0e96de946446fc96add2f38a806a44a5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Kinshasa differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Lagos b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Lagos new file mode 100644 index 0000000000000000000000000000000000000000..3d7a71ba0e96de946446fc96add2f38a806a44a5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Lagos differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Libreville b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Libreville new file mode 100644 index 0000000000000000000000000000000000000000..3d7a71ba0e96de946446fc96add2f38a806a44a5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Libreville differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Lome b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Lome new file mode 100644 index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Lome differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Luanda b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Luanda new file mode 100644 index 0000000000000000000000000000000000000000..3d7a71ba0e96de946446fc96add2f38a806a44a5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Luanda differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Lubumbashi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Lubumbashi new file mode 100644 index 0000000000000000000000000000000000000000..581bb0e08b616a433d422ccb8f958cbebdae1770 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Lubumbashi differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Lusaka b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Lusaka new file mode 100644 index 0000000000000000000000000000000000000000..581bb0e08b616a433d422ccb8f958cbebdae1770 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Lusaka differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Malabo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Malabo new file mode 100644 index 0000000000000000000000000000000000000000..3d7a71ba0e96de946446fc96add2f38a806a44a5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Malabo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Maputo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Maputo new file mode 100644 index 0000000000000000000000000000000000000000..581bb0e08b616a433d422ccb8f958cbebdae1770 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Maputo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Maseru b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Maseru new file mode 100644 index 0000000000000000000000000000000000000000..bada0638f8a2224a603f13afff16c0d8e986a591 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Maseru differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Mbabane b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Mbabane new file mode 100644 index 0000000000000000000000000000000000000000..bada0638f8a2224a603f13afff16c0d8e986a591 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Mbabane differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Mogadishu b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Mogadishu new file mode 100644 index 0000000000000000000000000000000000000000..5f4ebcb7f9789c4ecda13ac66c2e768851113004 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Mogadishu differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Monrovia b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Monrovia new file mode 100644 index 0000000000000000000000000000000000000000..837780922f23fc58ff7f73930954840e9c63c908 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Monrovia differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Nairobi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Nairobi new file mode 100644 index 0000000000000000000000000000000000000000..5f4ebcb7f9789c4ecda13ac66c2e768851113004 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Nairobi differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Ndjamena b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Ndjamena new file mode 100644 index 0000000000000000000000000000000000000000..ecbc0966dc2dc01fd4f93139318eccc0dddce5a6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Ndjamena differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Niamey b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Niamey new file mode 100644 index 0000000000000000000000000000000000000000..3d7a71ba0e96de946446fc96add2f38a806a44a5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Niamey differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Nouakchott b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Nouakchott new file mode 100644 index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Nouakchott differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Ouagadougou b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Ouagadougou new file mode 100644 index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Ouagadougou differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Porto-Novo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Porto-Novo new file mode 100644 index 0000000000000000000000000000000000000000..3d7a71ba0e96de946446fc96add2f38a806a44a5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Porto-Novo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Sao_Tome b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Sao_Tome new file mode 100644 index 0000000000000000000000000000000000000000..425ad3fda7c517742fe01db74e38c0130be4a7ab Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Sao_Tome differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Timbuktu b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Timbuktu new file mode 100644 index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Timbuktu differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Tripoli b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Tripoli new file mode 100644 index 0000000000000000000000000000000000000000..e0c89971aabea2c87842a9276b043d0fd946e34e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Tripoli differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Tunis b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Tunis new file mode 100644 index 0000000000000000000000000000000000000000..ca324cb4cd26cc29529faaee4c0465ae0cecc8f6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Tunis differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Windhoek b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Windhoek new file mode 100644 index 0000000000000000000000000000000000000000..0edc52b9b783827a8ac1090fe350bfe13977f745 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/Windhoek differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Africa/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Adak b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Adak new file mode 100644 index 0000000000000000000000000000000000000000..b1497bda631efdcb6635ffb6b0ee6f7da9e2a280 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Adak differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Anchorage b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Anchorage new file mode 100644 index 0000000000000000000000000000000000000000..cdf0572be31d3052a98494e3d01802b83737f23c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Anchorage differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Anguilla b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Anguilla new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Anguilla differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Antigua b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Antigua new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Antigua differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Araguaina b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Araguaina new file mode 100644 index 0000000000000000000000000000000000000000..f66c9f79d6cd4790c54d01286660f8ea0807f1c6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Araguaina differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Buenos_Aires b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Buenos_Aires new file mode 100644 index 0000000000000000000000000000000000000000..d6f999b8605c9f73653a16e2ddbd5a49b96c0f56 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Buenos_Aires differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Catamarca b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Catamarca new file mode 100644 index 0000000000000000000000000000000000000000..1dcc8d85434c9d016f170cb2f16811ebef327b77 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Catamarca differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/ComodRivadavia b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/ComodRivadavia new file mode 100644 index 0000000000000000000000000000000000000000..1dcc8d85434c9d016f170cb2f16811ebef327b77 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/ComodRivadavia differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Cordoba b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Cordoba new file mode 100644 index 0000000000000000000000000000000000000000..35a52e53d123b5ef5d293b3af19046630f02bb66 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Cordoba differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Jujuy b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Jujuy new file mode 100644 index 0000000000000000000000000000000000000000..b275f27c0287415674d2ccc850c3d612f4a45b0f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Jujuy differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/La_Rioja b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/La_Rioja new file mode 100644 index 0000000000000000000000000000000000000000..23fca12205222be27c167e597df5086520f699cf Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/La_Rioja differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Mendoza b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Mendoza new file mode 100644 index 0000000000000000000000000000000000000000..691c56978a033586e3302db2ef600e4b0ffd6366 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Mendoza differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Rio_Gallegos b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Rio_Gallegos new file mode 100644 index 0000000000000000000000000000000000000000..991d1fae69ee1602fc6a07e6e85a3b62d66650c2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Rio_Gallegos differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Salta b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Salta new file mode 100644 index 0000000000000000000000000000000000000000..58863e0436d16ef8ff8ba3d96b452086e4ae8ff5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Salta differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/San_Juan b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/San_Juan new file mode 100644 index 0000000000000000000000000000000000000000..7eba33c1c5b13cbd9b7566f450d524a45cf8b65e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/San_Juan differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/San_Luis b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/San_Luis new file mode 100644 index 0000000000000000000000000000000000000000..0a81cbddfa2813041472b716baa91c35a8451379 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/San_Luis differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Tucuman b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Tucuman new file mode 100644 index 0000000000000000000000000000000000000000..10556d5d856a0f33afd8da2b07a2005e7be80fb0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Tucuman differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Ushuaia b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Ushuaia new file mode 100644 index 0000000000000000000000000000000000000000..e0317502769271ad0c038493df2ad2b90ec402d4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Ushuaia differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Aruba b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Aruba new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Aruba differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Asuncion b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Asuncion new file mode 100644 index 0000000000000000000000000000000000000000..f056047f058ee5983f113c9129cb7e3e87633de6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Asuncion differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Atikokan b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Atikokan new file mode 100644 index 0000000000000000000000000000000000000000..9154643f4c9189998392afb8a93e2e2eb9eaecf5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Atikokan differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Atka b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Atka new file mode 100644 index 0000000000000000000000000000000000000000..b1497bda631efdcb6635ffb6b0ee6f7da9e2a280 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Atka differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Bahia b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Bahia new file mode 100644 index 0000000000000000000000000000000000000000..7969e3076687a35835653a348f0f3c8c0b2e1821 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Bahia differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Bahia_Banderas b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Bahia_Banderas new file mode 100644 index 0000000000000000000000000000000000000000..882400bd33bdc23fc75b092a01ea935b02431715 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Bahia_Banderas differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Barbados b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Barbados new file mode 100644 index 0000000000000000000000000000000000000000..720c9863f2a834f310280cc9113bedc59a25206d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Barbados differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Belem b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Belem new file mode 100644 index 0000000000000000000000000000000000000000..e0d7653c64c1e3b3e546d4c5e7644865b237f128 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Belem differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Belize b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Belize new file mode 100644 index 0000000000000000000000000000000000000000..bfc19f4e587cadf6a2b05781860c21dccdf02961 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Belize differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Blanc-Sablon b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Blanc-Sablon new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Blanc-Sablon differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Boa_Vista b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Boa_Vista new file mode 100644 index 0000000000000000000000000000000000000000..fca97207b2833031d00d3ff0246d7518b3042644 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Boa_Vista differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Bogota b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Bogota new file mode 100644 index 0000000000000000000000000000000000000000..85b903333eb6325aa8343f6e9aee38447495303f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Bogota differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Boise b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Boise new file mode 100644 index 0000000000000000000000000000000000000000..72fec9e8c52ab8bb3dc6519b9d7f0c311900ac16 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Boise differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Buenos_Aires b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Buenos_Aires new file mode 100644 index 0000000000000000000000000000000000000000..d6f999b8605c9f73653a16e2ddbd5a49b96c0f56 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Buenos_Aires differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cambridge_Bay b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cambridge_Bay new file mode 100644 index 0000000000000000000000000000000000000000..1092f4b61a1b203f7feabb586b51085bb72602dc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cambridge_Bay differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Campo_Grande b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Campo_Grande new file mode 100644 index 0000000000000000000000000000000000000000..6855e4e9fe021cbbc392c76e1effef86dd53510c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Campo_Grande differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cancun b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cancun new file mode 100644 index 0000000000000000000000000000000000000000..3110cdfd6e6f4ccd889447657dff43560d5aaee0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cancun differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Caracas b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Caracas new file mode 100644 index 0000000000000000000000000000000000000000..8dbe6ff74127e02577fdccd694af5a61580369e5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Caracas differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Catamarca b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Catamarca new file mode 100644 index 0000000000000000000000000000000000000000..1dcc8d85434c9d016f170cb2f16811ebef327b77 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Catamarca differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cayenne b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cayenne new file mode 100644 index 0000000000000000000000000000000000000000..cd49f0534438cc3bfa0e09bb5701552ce9a177cc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cayenne differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cayman b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cayman new file mode 100644 index 0000000000000000000000000000000000000000..9154643f4c9189998392afb8a93e2e2eb9eaecf5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cayman differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Chicago b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Chicago new file mode 100644 index 0000000000000000000000000000000000000000..b016880653929aa40dd5ac0e82e4094a9d787cdf Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Chicago differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Chihuahua b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Chihuahua new file mode 100644 index 0000000000000000000000000000000000000000..f65bb1c9310447737822ad026470d5092ce87678 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Chihuahua differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Ciudad_Juarez b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Ciudad_Juarez new file mode 100644 index 0000000000000000000000000000000000000000..5f865ea808b57d97634d4331fc5fce84349ded36 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Ciudad_Juarez differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Coral_Harbour b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Coral_Harbour new file mode 100644 index 0000000000000000000000000000000000000000..9154643f4c9189998392afb8a93e2e2eb9eaecf5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Coral_Harbour differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cordoba b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cordoba new file mode 100644 index 0000000000000000000000000000000000000000..35a52e53d123b5ef5d293b3af19046630f02bb66 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cordoba differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Costa_Rica b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Costa_Rica new file mode 100644 index 0000000000000000000000000000000000000000..08f0128ee681d8f7e1df186d93514f3f4cff2830 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Costa_Rica differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Coyhaique b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Coyhaique new file mode 100644 index 0000000000000000000000000000000000000000..26354e89460e7c9e585d62ab477cd69a5559b554 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Coyhaique differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Creston b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Creston new file mode 100644 index 0000000000000000000000000000000000000000..c2bd2f949b248b835c98216b4dc66f9f6eb0265e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Creston differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cuiaba b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cuiaba new file mode 100644 index 0000000000000000000000000000000000000000..c09a87558d53b031fca84a4c92165b01b37da360 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Cuiaba differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Curacao b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Curacao new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Curacao differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Danmarkshavn b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Danmarkshavn new file mode 100644 index 0000000000000000000000000000000000000000..8718efcce25cd28ff9fa0f48bba0a2a7e6be4ed0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Danmarkshavn differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Dawson b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Dawson new file mode 100644 index 0000000000000000000000000000000000000000..07e4c5f4ac3852571b17cb33fe565a5ea2c49f0a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Dawson differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Dawson_Creek b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Dawson_Creek new file mode 100644 index 0000000000000000000000000000000000000000..761d1d9af53662efdb521bef949ded15e3f1f4dc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Dawson_Creek differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Denver b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Denver new file mode 100644 index 0000000000000000000000000000000000000000..09e54e5c7c5bb2384e37626d4b985cfad29ed29b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Denver differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Detroit b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Detroit new file mode 100644 index 0000000000000000000000000000000000000000..6eb3ac46ec56985b52488ae6a8d80247c2adcd4a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Detroit differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Dominica b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Dominica new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Dominica differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Edmonton b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Edmonton new file mode 100644 index 0000000000000000000000000000000000000000..645ee9453073acf4cff9f9420b358a8ebbe40f93 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Edmonton differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Eirunepe b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Eirunepe new file mode 100644 index 0000000000000000000000000000000000000000..7da4b98fe3c70a1aecae8e0f4264324eaf9e1fb6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Eirunepe differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/El_Salvador b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/El_Salvador new file mode 100644 index 0000000000000000000000000000000000000000..43484117e2858004a0377195b5c83c3a9748062d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/El_Salvador differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Ensenada b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Ensenada new file mode 100644 index 0000000000000000000000000000000000000000..18d0d14afc1cdf37c8f3607181e3f72211da99e9 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Ensenada differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Fort_Nelson b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Fort_Nelson new file mode 100644 index 0000000000000000000000000000000000000000..2a49c6c50f4c21765232712d18a6cbbeedafc441 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Fort_Nelson differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Fort_Wayne b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Fort_Wayne new file mode 100644 index 0000000000000000000000000000000000000000..6b08d15bdaba6cf94dcb2681887154f4d265d8ba Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Fort_Wayne differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Fortaleza b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Fortaleza new file mode 100644 index 0000000000000000000000000000000000000000..092e40d70122f764fd2630957be1d3e32858f6f5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Fortaleza differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Glace_Bay b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Glace_Bay new file mode 100644 index 0000000000000000000000000000000000000000..f85eb341575850b353d31b37908f4fa49119a007 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Glace_Bay differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Godthab b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Godthab new file mode 100644 index 0000000000000000000000000000000000000000..310774ea4fdd1798782a41f905d16e3548cd191e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Godthab differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Goose_Bay b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Goose_Bay new file mode 100644 index 0000000000000000000000000000000000000000..e2cc3eefc273c206ab9d88f94660f587932991fc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Goose_Bay differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Grand_Turk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Grand_Turk new file mode 100644 index 0000000000000000000000000000000000000000..9d90e745b04fae51493817b5ba1db5015a39bfda Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Grand_Turk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Grenada b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Grenada new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Grenada differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Guadeloupe b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Guadeloupe new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Guadeloupe differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Guatemala b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Guatemala new file mode 100644 index 0000000000000000000000000000000000000000..8aa8e588e3cbf963193269ae01eecfafaeb02b50 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Guatemala differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Guayaquil b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Guayaquil new file mode 100644 index 0000000000000000000000000000000000000000..381ae6c463260d85ce92d6585b6420fed0c096dd Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Guayaquil differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Guyana b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Guyana new file mode 100644 index 0000000000000000000000000000000000000000..bcc66881c17cebf8767b7a147b1fcf7ab29bbd9f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Guyana differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Halifax b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Halifax new file mode 100644 index 0000000000000000000000000000000000000000..9fa850a7d4c36dea84149bc0ea2fcd3581d61a8c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Halifax differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Havana b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Havana new file mode 100644 index 0000000000000000000000000000000000000000..e06629d36841463326ff3350bc2f94d0417c3cdd Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Havana differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Hermosillo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Hermosillo new file mode 100644 index 0000000000000000000000000000000000000000..ba7b14760d47d1e10241e78e976f0093ada6551b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Hermosillo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Indianapolis b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Indianapolis new file mode 100644 index 0000000000000000000000000000000000000000..6b08d15bdaba6cf94dcb2681887154f4d265d8ba Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Indianapolis differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Knox b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Knox new file mode 100644 index 0000000000000000000000000000000000000000..b187d5f8c75685af67913e9360b50ecad19fe6ad Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Knox differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Marengo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Marengo new file mode 100644 index 0000000000000000000000000000000000000000..a730fe666b6522026ec2eb74f94616699178a346 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Marengo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Petersburg b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Petersburg new file mode 100644 index 0000000000000000000000000000000000000000..341a0235ef488ee623aba36a8b5928122774d2fb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Petersburg differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Tell_City b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Tell_City new file mode 100644 index 0000000000000000000000000000000000000000..76e1f6285b552c11ceae9bc6cdbd6a308419b0e8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Tell_City differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Vevay b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Vevay new file mode 100644 index 0000000000000000000000000000000000000000..f2acf6cbbd653929e826366aec83f443d11c66e7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Vevay differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Vincennes b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Vincennes new file mode 100644 index 0000000000000000000000000000000000000000..c255f89b6da9916832a8b6a9bb7620859ce33d91 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Vincennes differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Winamac b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Winamac new file mode 100644 index 0000000000000000000000000000000000000000..679d321e3b691b5403d9c9493367651360ea6f15 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Winamac differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indianapolis b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indianapolis new file mode 100644 index 0000000000000000000000000000000000000000..6b08d15bdaba6cf94dcb2681887154f4d265d8ba Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Indianapolis differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Inuvik b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Inuvik new file mode 100644 index 0000000000000000000000000000000000000000..86639f6ecb4c424911e5bdbca81a9e39c86e850c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Inuvik differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Iqaluit b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Iqaluit new file mode 100644 index 0000000000000000000000000000000000000000..95e055cb55d19335fa96f1a8d81fb5620f790771 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Iqaluit differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Jamaica b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Jamaica new file mode 100644 index 0000000000000000000000000000000000000000..be6b1b6f1e77a8f13a7400bcfc10c63a7ee1d55d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Jamaica differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Jujuy b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Jujuy new file mode 100644 index 0000000000000000000000000000000000000000..b275f27c0287415674d2ccc850c3d612f4a45b0f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Jujuy differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Juneau b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Juneau new file mode 100644 index 0000000000000000000000000000000000000000..e347b369f780629179a5ffd7a256054d901a1ad5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Juneau differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/Louisville b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/Louisville new file mode 100644 index 0000000000000000000000000000000000000000..f2136d6ed41bb7dc0646b91bab366efb46bacb78 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/Louisville differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/Monticello b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/Monticello new file mode 100644 index 0000000000000000000000000000000000000000..d9f54a18bbe6885a05a7f42a056bc892b7a641e8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/Monticello differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Knox_IN b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Knox_IN new file mode 100644 index 0000000000000000000000000000000000000000..b187d5f8c75685af67913e9360b50ecad19fe6ad Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Knox_IN differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Kralendijk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Kralendijk new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Kralendijk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/La_Paz b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/La_Paz new file mode 100644 index 0000000000000000000000000000000000000000..68ddaae768e665a8170ea1485aae51c686f5cfed Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/La_Paz differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Lima b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Lima new file mode 100644 index 0000000000000000000000000000000000000000..b643c5517f923f075d58897764ba6885197f5758 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Lima differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Los_Angeles b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Los_Angeles new file mode 100644 index 0000000000000000000000000000000000000000..aaf07787ad92b65eadae63b64bba290f9f961507 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Los_Angeles differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Louisville b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Louisville new file mode 100644 index 0000000000000000000000000000000000000000..f2136d6ed41bb7dc0646b91bab366efb46bacb78 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Louisville differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Lower_Princes b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Lower_Princes new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Lower_Princes differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Maceio b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Maceio new file mode 100644 index 0000000000000000000000000000000000000000..dbb8d57d91d6640c1282fab3a063567d1f663f88 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Maceio differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Managua b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Managua new file mode 100644 index 0000000000000000000000000000000000000000..86ef76bf2241b6abde0f4790d23b180db4b4b1cc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Managua differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Manaus b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Manaus new file mode 100644 index 0000000000000000000000000000000000000000..59c952ebc65169dce30078a3e1ee371e0da52ae4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Manaus differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Marigot b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Marigot new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Marigot differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Martinique b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Martinique new file mode 100644 index 0000000000000000000000000000000000000000..25c0232d95492333e8c1aef7321a24a331e2e24a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Martinique differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Matamoros b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Matamoros new file mode 100644 index 0000000000000000000000000000000000000000..993ac47559c154e52af8fba1bcd7c9d0e3bea880 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Matamoros differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Mazatlan b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Mazatlan new file mode 100644 index 0000000000000000000000000000000000000000..5aa6039ea4cb36077f048782b54c6275c25e86b3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Mazatlan differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Mendoza b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Mendoza new file mode 100644 index 0000000000000000000000000000000000000000..691c56978a033586e3302db2ef600e4b0ffd6366 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Mendoza differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Menominee b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Menominee new file mode 100644 index 0000000000000000000000000000000000000000..28d2c56e1a991556b5aca45108e3415f3ebfe868 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Menominee differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Merida b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Merida new file mode 100644 index 0000000000000000000000000000000000000000..e5c7d8cc2d2a986374f35561d8b629110b481a66 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Merida differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Metlakatla b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Metlakatla new file mode 100644 index 0000000000000000000000000000000000000000..71b0eab085dbbb48050d7b6a271ebb1a29fb1926 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Metlakatla differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Mexico_City b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Mexico_City new file mode 100644 index 0000000000000000000000000000000000000000..18112346129a885b5d5fa27109682b63784f72c0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Mexico_City differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Miquelon b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Miquelon new file mode 100644 index 0000000000000000000000000000000000000000..ba95cb0b3f755ab94154a54fd8cf6e6b9cdb0556 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Miquelon differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Moncton b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Moncton new file mode 100644 index 0000000000000000000000000000000000000000..020e33d976179e8f61a6040caaef3c8eb7f348bc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Moncton differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Monterrey b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Monterrey new file mode 100644 index 0000000000000000000000000000000000000000..c1e05464513a451ab3cc49452e39da2b04e01de0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Monterrey differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Montevideo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Montevideo new file mode 100644 index 0000000000000000000000000000000000000000..4b2fb3e560f6ad26b30b2215d26b3d6176d076b2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Montevideo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Montreal b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Montreal new file mode 100644 index 0000000000000000000000000000000000000000..668e70d765dc3fb0eda16fb0f1932af607b53412 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Montreal differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Montserrat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Montserrat new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Montserrat differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Nassau b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Nassau new file mode 100644 index 0000000000000000000000000000000000000000..668e70d765dc3fb0eda16fb0f1932af607b53412 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Nassau differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/New_York b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/New_York new file mode 100644 index 0000000000000000000000000000000000000000..2b6c2eea14df07392729ae9f5712a44ec4f02bae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/New_York differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Nipigon b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Nipigon new file mode 100644 index 0000000000000000000000000000000000000000..668e70d765dc3fb0eda16fb0f1932af607b53412 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Nipigon differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Nome b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Nome new file mode 100644 index 0000000000000000000000000000000000000000..23ead1c004ffd82c03b69b44e147daef4c07c961 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Nome differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Noronha b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Noronha new file mode 100644 index 0000000000000000000000000000000000000000..9e74745ca79137918281337fa270c5fec4bd7da1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Noronha differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/Beulah b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/Beulah new file mode 100644 index 0000000000000000000000000000000000000000..becf4383301e2d90db0c0c06659b588d25042ee5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/Beulah differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/Center b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/Center new file mode 100644 index 0000000000000000000000000000000000000000..d03bda045d31662adc65450b33e9665c54fdb245 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/Center differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/New_Salem b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/New_Salem new file mode 100644 index 0000000000000000000000000000000000000000..ecefc15d8cdf601347e114ff25b3bb2df4d56a57 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/New_Salem differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Nuuk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Nuuk new file mode 100644 index 0000000000000000000000000000000000000000..310774ea4fdd1798782a41f905d16e3548cd191e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Nuuk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Ojinaga b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Ojinaga new file mode 100644 index 0000000000000000000000000000000000000000..1dd08b1cafd4b36ce963bdc42a075665fa723b54 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Ojinaga differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Panama b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Panama new file mode 100644 index 0000000000000000000000000000000000000000..9154643f4c9189998392afb8a93e2e2eb9eaecf5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Panama differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Pangnirtung b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Pangnirtung new file mode 100644 index 0000000000000000000000000000000000000000..95e055cb55d19335fa96f1a8d81fb5620f790771 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Pangnirtung differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Paramaribo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Paramaribo new file mode 100644 index 0000000000000000000000000000000000000000..24f925a2dd33d487e41cb38b9c3b4c420af69c1d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Paramaribo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Phoenix b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Phoenix new file mode 100644 index 0000000000000000000000000000000000000000..c2bd2f949b248b835c98216b4dc66f9f6eb0265e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Phoenix differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Port-au-Prince b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Port-au-Prince new file mode 100644 index 0000000000000000000000000000000000000000..3e75731baa7c47f2a60ad07733d6f8467ccfbebf Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Port-au-Prince differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Port_of_Spain b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Port_of_Spain new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Port_of_Spain differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Porto_Acre b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Porto_Acre new file mode 100644 index 0000000000000000000000000000000000000000..fb5185ca60283bd56f795e9a956274c0b6e63325 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Porto_Acre differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Porto_Velho b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Porto_Velho new file mode 100644 index 0000000000000000000000000000000000000000..7f8047d9396f92476873c9dbedb4598d9d238046 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Porto_Velho differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Puerto_Rico b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Puerto_Rico new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Puerto_Rico differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Punta_Arenas b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Punta_Arenas new file mode 100644 index 0000000000000000000000000000000000000000..aa839ea7d42eb9822002e66322c4ae195f1644b5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Punta_Arenas differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Rainy_River b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Rainy_River new file mode 100644 index 0000000000000000000000000000000000000000..7e646d18e18851bfde743b379e52df4ec5b5a20f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Rainy_River differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Rankin_Inlet b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Rankin_Inlet new file mode 100644 index 0000000000000000000000000000000000000000..6d1d90dede9888571eb09299dbd0b3e7dcfb1cc9 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Rankin_Inlet differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Recife b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Recife new file mode 100644 index 0000000000000000000000000000000000000000..305abcb8a2217834e8333a2c486ccd389199a334 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Recife differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Regina b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Regina new file mode 100644 index 0000000000000000000000000000000000000000..a3f8217a544ebb0993473bbffaae8e2d723c4ec3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Regina differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Resolute b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Resolute new file mode 100644 index 0000000000000000000000000000000000000000..97eb8a9c1fbbf56b8e32a1bea34f68e263e2a9d7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Resolute differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Rio_Branco b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Rio_Branco new file mode 100644 index 0000000000000000000000000000000000000000..fb5185ca60283bd56f795e9a956274c0b6e63325 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Rio_Branco differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Rosario b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Rosario new file mode 100644 index 0000000000000000000000000000000000000000..35a52e53d123b5ef5d293b3af19046630f02bb66 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Rosario differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Santa_Isabel b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Santa_Isabel new file mode 100644 index 0000000000000000000000000000000000000000..18d0d14afc1cdf37c8f3607181e3f72211da99e9 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Santa_Isabel differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Santarem b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Santarem new file mode 100644 index 0000000000000000000000000000000000000000..f81d144206ac5bd2029d59beac0bb82801ebe67a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Santarem differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Santiago b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Santiago new file mode 100644 index 0000000000000000000000000000000000000000..d3fc9b8343369abf5f14be781397f426c5969608 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Santiago differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Santo_Domingo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Santo_Domingo new file mode 100644 index 0000000000000000000000000000000000000000..3e0785086639e483597890d2b53b9bc4c4ccfe91 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Santo_Domingo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Sao_Paulo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Sao_Paulo new file mode 100644 index 0000000000000000000000000000000000000000..a16da2c4d5a980cd944d86c34ea8a2f597e39b71 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Sao_Paulo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Scoresbysund b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Scoresbysund new file mode 100644 index 0000000000000000000000000000000000000000..fc1b11cbe876cabb53fc1d42db25b0aabd967fc0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Scoresbysund differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Shiprock b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Shiprock new file mode 100644 index 0000000000000000000000000000000000000000..09e54e5c7c5bb2384e37626d4b985cfad29ed29b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Shiprock differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Sitka b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Sitka new file mode 100644 index 0000000000000000000000000000000000000000..36681ed78eaf0b46f8d142884cf7ae8903a18907 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Sitka differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Barthelemy b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Barthelemy new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Barthelemy differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Johns b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Johns new file mode 100644 index 0000000000000000000000000000000000000000..94d790baaccb72298bb577041cf3c8400339a7da Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Johns differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Kitts b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Kitts new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Kitts differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Lucia b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Lucia new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Lucia differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Thomas b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Thomas new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Thomas differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Vincent b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Vincent new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/St_Vincent differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Swift_Current b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Swift_Current new file mode 100644 index 0000000000000000000000000000000000000000..bdbb494487de8aeb624c950e470ebba223d16961 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Swift_Current differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Tegucigalpa b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Tegucigalpa new file mode 100644 index 0000000000000000000000000000000000000000..38036a32831d149c6c737dfa49f0947f066288b1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Tegucigalpa differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Thule b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Thule new file mode 100644 index 0000000000000000000000000000000000000000..f38dc56bf20d9db68515ea7602c9edb39fabae8d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Thule differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Thunder_Bay b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Thunder_Bay new file mode 100644 index 0000000000000000000000000000000000000000..668e70d765dc3fb0eda16fb0f1932af607b53412 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Thunder_Bay differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Tijuana b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Tijuana new file mode 100644 index 0000000000000000000000000000000000000000..18d0d14afc1cdf37c8f3607181e3f72211da99e9 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Tijuana differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Toronto b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Toronto new file mode 100644 index 0000000000000000000000000000000000000000..668e70d765dc3fb0eda16fb0f1932af607b53412 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Toronto differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Tortola b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Tortola new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Tortola differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Vancouver b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Vancouver new file mode 100644 index 0000000000000000000000000000000000000000..c998491112ea5e4430b8266498cf7f23e1266bc5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Vancouver differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Virgin b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Virgin new file mode 100644 index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Virgin differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Whitehorse b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Whitehorse new file mode 100644 index 0000000000000000000000000000000000000000..40baa9aba2a879f7a38a5a0f67e16e7a2d677a5e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Whitehorse differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Winnipeg b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Winnipeg new file mode 100644 index 0000000000000000000000000000000000000000..7e646d18e18851bfde743b379e52df4ec5b5a20f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Winnipeg differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Yakutat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Yakutat new file mode 100644 index 0000000000000000000000000000000000000000..773feba89d36ffab4baf105b8f0ae69584a74014 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Yakutat differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Yellowknife b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Yellowknife new file mode 100644 index 0000000000000000000000000000000000000000..645ee9453073acf4cff9f9420b358a8ebbe40f93 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/Yellowknife differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/America/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Casey b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Casey new file mode 100644 index 0000000000000000000000000000000000000000..84f1c61e5c7c35090fd2e628e307cff72389fb02 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Casey differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Davis b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Davis new file mode 100644 index 0000000000000000000000000000000000000000..3ec32224f2982db46a19d1a159f9017286fd1413 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Davis differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/DumontDUrville b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/DumontDUrville new file mode 100644 index 0000000000000000000000000000000000000000..5d8fc3a1b253d1df3a0184013469c6e46f6f6f75 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/DumontDUrville differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Macquarie b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Macquarie new file mode 100644 index 0000000000000000000000000000000000000000..99a8e60edffca85f5caf8eda9d05d85a4978e665 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Macquarie differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Mawson b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Mawson new file mode 100644 index 0000000000000000000000000000000000000000..05e4c6c5867330a5af95cd6816ade311a0cac82d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Mawson differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/McMurdo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/McMurdo new file mode 100644 index 0000000000000000000000000000000000000000..afb3929318475d4f0ea9d6c9e94d0f5f81d8b82e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/McMurdo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Palmer b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Palmer new file mode 100644 index 0000000000000000000000000000000000000000..32c1941634aec9e7721fcf8e9b323e7d99c7f337 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Palmer differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Rothera b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Rothera new file mode 100644 index 0000000000000000000000000000000000000000..ea49c00b2240fbd608425793b225d6e10a58ddef Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Rothera differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/South_Pole b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/South_Pole new file mode 100644 index 0000000000000000000000000000000000000000..afb3929318475d4f0ea9d6c9e94d0f5f81d8b82e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/South_Pole differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Syowa b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Syowa new file mode 100644 index 0000000000000000000000000000000000000000..01c47ccb86ccbde2bf9ad0803298e8df87178a34 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Syowa differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Troll b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Troll new file mode 100644 index 0000000000000000000000000000000000000000..2359c44bd00ed44d2cdbf4f0aa0d9cea507814ed Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Troll differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Vostok b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Vostok new file mode 100644 index 0000000000000000000000000000000000000000..4ce8f74784e970731f5f44b84f73780087890fa5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Vostok differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Antarctica/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Arctic/Longyearbyen b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Arctic/Longyearbyen new file mode 100644 index 0000000000000000000000000000000000000000..465546bd396ae5eb75076f13ba9c29b0c926c835 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Arctic/Longyearbyen differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Arctic/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Arctic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Aden b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Aden new file mode 100644 index 0000000000000000000000000000000000000000..01c47ccb86ccbde2bf9ad0803298e8df87178a34 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Aden differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Almaty b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Almaty new file mode 100644 index 0000000000000000000000000000000000000000..02f047d70fc811f8cc17f2c08ddc1f328576fb94 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Almaty differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Amman b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Amman new file mode 100644 index 0000000000000000000000000000000000000000..a3f9dff57148554c4207d71df64851aee2b28b19 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Amman differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Anadyr b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Anadyr new file mode 100644 index 0000000000000000000000000000000000000000..551884d322bcd2201b4b9898ec765141277e6eee Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Anadyr differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Aqtau b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Aqtau new file mode 100644 index 0000000000000000000000000000000000000000..3a40d1175a7d81d8a307d0e546a1fe9a40888b29 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Aqtau differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Aqtobe b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Aqtobe new file mode 100644 index 0000000000000000000000000000000000000000..62c5840a83e29b4fcedba95e438581cec96b3cf6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Aqtobe differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ashgabat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ashgabat new file mode 100644 index 0000000000000000000000000000000000000000..8482167269080ead3a6046ae5e64b56d48dac1dd Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ashgabat differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ashkhabad b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ashkhabad new file mode 100644 index 0000000000000000000000000000000000000000..8482167269080ead3a6046ae5e64b56d48dac1dd Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ashkhabad differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Atyrau b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Atyrau new file mode 100644 index 0000000000000000000000000000000000000000..cb2c82f657c7380462b3ea38d5e58cc3d692e0b2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Atyrau differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Baghdad b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Baghdad new file mode 100644 index 0000000000000000000000000000000000000000..a3ce97599100c0e514afa0764879c3f104be87e9 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Baghdad differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Bahrain b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Bahrain new file mode 100644 index 0000000000000000000000000000000000000000..7409d74983c8d0cd8347a663c3bfbc1c041124da Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Bahrain differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Baku b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Baku new file mode 100644 index 0000000000000000000000000000000000000000..96203d7a4266cd8646032165950374761090e318 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Baku differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Bangkok b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Bangkok new file mode 100644 index 0000000000000000000000000000000000000000..ed687d2985c208171adcaa3401496b05325edca4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Bangkok differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Barnaul b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Barnaul new file mode 100644 index 0000000000000000000000000000000000000000..ff976dd3b27ac5f14dcbac2362f1b4638c5684aa Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Barnaul differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Beirut b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Beirut new file mode 100644 index 0000000000000000000000000000000000000000..55dce5722cc9d913164747da068f37d3529e799f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Beirut differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Bishkek b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Bishkek new file mode 100644 index 0000000000000000000000000000000000000000..fe7832cdf99ed9da3b64e3b8f6c5cd0b8b4c8de7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Bishkek differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Brunei b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Brunei new file mode 100644 index 0000000000000000000000000000000000000000..59bc6e40b7bb0b4eb199dd8c17f416ee00ca4158 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Brunei differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Calcutta b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Calcutta new file mode 100644 index 0000000000000000000000000000000000000000..00bc80a65e9a7aa470d63fba1ce1b29ef173d922 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Calcutta differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Chita b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Chita new file mode 100644 index 0000000000000000000000000000000000000000..9d49cd35cd5e52c5ff0f2c0cc6bd3f4f6e856915 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Chita differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Choibalsan b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Choibalsan new file mode 100644 index 0000000000000000000000000000000000000000..6f5d3a15abbe48b8a4dc72aadc88c416160a56a6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Choibalsan differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Chongqing b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Chongqing new file mode 100644 index 0000000000000000000000000000000000000000..d6b66984a2f36ae36b35e174756707aa7286c292 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Chongqing differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Chungking b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Chungking new file mode 100644 index 0000000000000000000000000000000000000000..d6b66984a2f36ae36b35e174756707aa7286c292 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Chungking differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Colombo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Colombo new file mode 100644 index 0000000000000000000000000000000000000000..3eeb1b72b68993e26a2452afe98a6420ac66bafb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Colombo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Dacca b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Dacca new file mode 100644 index 0000000000000000000000000000000000000000..28136808b6d1029676448d8711265d8c55cb4bae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Dacca differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Damascus b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Damascus new file mode 100644 index 0000000000000000000000000000000000000000..bd1624de5148d5670e4585dfcb445d8b270c02df Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Damascus differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Dhaka b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Dhaka new file mode 100644 index 0000000000000000000000000000000000000000..28136808b6d1029676448d8711265d8c55cb4bae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Dhaka differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Dili b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Dili new file mode 100644 index 0000000000000000000000000000000000000000..22e705ca1ab1218e9f36b9f4f607258389853c8b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Dili differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Dubai b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Dubai new file mode 100644 index 0000000000000000000000000000000000000000..58d75bc26eec90272e97696f40483eb56c2b8b45 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Dubai differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Dushanbe b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Dushanbe new file mode 100644 index 0000000000000000000000000000000000000000..d83fb076a256817ca0a3ec4e43c7768e6680dc84 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Dushanbe differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Famagusta b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Famagusta new file mode 100644 index 0000000000000000000000000000000000000000..cc44179564afe36db0f1f7aab0a19cbc3e4fa4d0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Famagusta differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Gaza b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Gaza new file mode 100644 index 0000000000000000000000000000000000000000..0d79662716b445f61e5577bdb09e7c91e4a40d28 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Gaza differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Harbin b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Harbin new file mode 100644 index 0000000000000000000000000000000000000000..d6b66984a2f36ae36b35e174756707aa7286c292 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Harbin differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Hebron b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Hebron new file mode 100644 index 0000000000000000000000000000000000000000..53a3c14312bc770bf9bca1d2e7518763fec7a485 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Hebron differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ho_Chi_Minh b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ho_Chi_Minh new file mode 100644 index 0000000000000000000000000000000000000000..86e21b0f524426287fb3b21a82369283c4040c0e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ho_Chi_Minh differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Hong_Kong b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Hong_Kong new file mode 100644 index 0000000000000000000000000000000000000000..c80e364801be87687625f72e8e2c3dbd0f7ae4bc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Hong_Kong differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Hovd b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Hovd new file mode 100644 index 0000000000000000000000000000000000000000..6e08a261274e48f93eb5e221ba294e54ca671b94 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Hovd differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Irkutsk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Irkutsk new file mode 100644 index 0000000000000000000000000000000000000000..550e2a08773b328683ab10fb9feddee2038e9e58 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Irkutsk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Istanbul b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Istanbul new file mode 100644 index 0000000000000000000000000000000000000000..c89186687300068ac4e8505cc0012a1dbf6a9960 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Istanbul differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Jakarta b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Jakarta new file mode 100644 index 0000000000000000000000000000000000000000..c9752d2f23ebbb8b1ca5b8ac604c6f24be5d0def Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Jakarta differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Jayapura b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Jayapura new file mode 100644 index 0000000000000000000000000000000000000000..7c22f539d948e5757a0847892da344309b582473 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Jayapura differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Jerusalem b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Jerusalem new file mode 100644 index 0000000000000000000000000000000000000000..4c49bbf52440631eca750cacb7d79f259eeb8bd2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Jerusalem differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kabul b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kabul new file mode 100644 index 0000000000000000000000000000000000000000..660ce4cf695702ee8c6eef5c0e2419de37d6df74 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kabul differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kamchatka b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kamchatka new file mode 100644 index 0000000000000000000000000000000000000000..c65155402db6a465c05a8cd71ec7a0fc0f792762 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kamchatka differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Karachi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Karachi new file mode 100644 index 0000000000000000000000000000000000000000..e56d5afdafb27c656a39e1dcdf1e3d2b880efa87 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Karachi differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kashgar b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kashgar new file mode 100644 index 0000000000000000000000000000000000000000..69ff7f6fb4973efb1185cad9f553f8c770c75934 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kashgar differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kathmandu b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kathmandu new file mode 100644 index 0000000000000000000000000000000000000000..3a0d330ffd2f08396290960527fc8fc186356161 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kathmandu differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Katmandu b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Katmandu new file mode 100644 index 0000000000000000000000000000000000000000..3a0d330ffd2f08396290960527fc8fc186356161 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Katmandu differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Khandyga b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Khandyga new file mode 100644 index 0000000000000000000000000000000000000000..aeb733202acd5d9d2a19a54fc64c226302887423 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Khandyga differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kolkata b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kolkata new file mode 100644 index 0000000000000000000000000000000000000000..00bc80a65e9a7aa470d63fba1ce1b29ef173d922 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kolkata differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Krasnoyarsk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Krasnoyarsk new file mode 100644 index 0000000000000000000000000000000000000000..e0d4fcb5c3d781943a65dc53cca9fab5d1905f9f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Krasnoyarsk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuala_Lumpur b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuala_Lumpur new file mode 100644 index 0000000000000000000000000000000000000000..dbbdea3c8149004cfd525a0fc26e5da72b20e8a1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuala_Lumpur differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuching b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuching new file mode 100644 index 0000000000000000000000000000000000000000..59bc6e40b7bb0b4eb199dd8c17f416ee00ca4158 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuching differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuwait b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuwait new file mode 100644 index 0000000000000000000000000000000000000000..01c47ccb86ccbde2bf9ad0803298e8df87178a34 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuwait differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Macao b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Macao new file mode 100644 index 0000000000000000000000000000000000000000..c22f75e42db6b12db3c837056436cb77d176b83e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Macao differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Macau b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Macau new file mode 100644 index 0000000000000000000000000000000000000000..c22f75e42db6b12db3c837056436cb77d176b83e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Macau differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Magadan b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Magadan new file mode 100644 index 0000000000000000000000000000000000000000..16bac8444656c393288dcc0209a96c7c3f487a19 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Magadan differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Manila b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Manila new file mode 100644 index 0000000000000000000000000000000000000000..145bb6fb162e192da18e0991c00578d43475b384 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Manila differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Muscat b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Muscat new file mode 100644 index 0000000000000000000000000000000000000000..58d75bc26eec90272e97696f40483eb56c2b8b45 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Muscat differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Nicosia b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Nicosia new file mode 100644 index 0000000000000000000000000000000000000000..390347f442a486e296689c189e3346695bba5105 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Nicosia differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Novokuznetsk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Novokuznetsk new file mode 100644 index 0000000000000000000000000000000000000000..9378d50539dfa8f1dabcb40d3720f64906d36202 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Novokuznetsk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Novosibirsk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Novosibirsk new file mode 100644 index 0000000000000000000000000000000000000000..65a9fa2cd2e8548b13f1d0895bcba46fa11600a4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Novosibirsk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Omsk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Omsk new file mode 100644 index 0000000000000000000000000000000000000000..dc0ed422f6193fb5d7dcb59dd0eb3e06eec8d4de Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Omsk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Oral b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Oral new file mode 100644 index 0000000000000000000000000000000000000000..25a63ec8b9951c94fc00a8c6c9d18d2151b26dde Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Oral differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Phnom_Penh b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Phnom_Penh new file mode 100644 index 0000000000000000000000000000000000000000..ed687d2985c208171adcaa3401496b05325edca4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Phnom_Penh differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Pontianak b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Pontianak new file mode 100644 index 0000000000000000000000000000000000000000..285bed2c63a5debe034a661431d2a1c03dfb0dad Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Pontianak differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Pyongyang b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Pyongyang new file mode 100644 index 0000000000000000000000000000000000000000..57240cf89fb33139a92451ec2eb99cb67b2f49c1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Pyongyang differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Qatar b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Qatar new file mode 100644 index 0000000000000000000000000000000000000000..7409d74983c8d0cd8347a663c3bfbc1c041124da Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Qatar differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Qostanay b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Qostanay new file mode 100644 index 0000000000000000000000000000000000000000..109fe41562e89a026f828125f960498f62fb5d95 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Qostanay differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Qyzylorda b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Qyzylorda new file mode 100644 index 0000000000000000000000000000000000000000..fe4d6c6d6d44f0f6b7dd1f55702c4d640270a1fc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Qyzylorda differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Riyadh b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Riyadh new file mode 100644 index 0000000000000000000000000000000000000000..01c47ccb86ccbde2bf9ad0803298e8df87178a34 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Riyadh differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Samarkand b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Samarkand new file mode 100644 index 0000000000000000000000000000000000000000..c43e27c5d4bd341649b3aa32de068d76618c81ed Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Samarkand differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Shanghai b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Shanghai new file mode 100644 index 0000000000000000000000000000000000000000..d6b66984a2f36ae36b35e174756707aa7286c292 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Shanghai differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Singapore b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Singapore new file mode 100644 index 0000000000000000000000000000000000000000..dbbdea3c8149004cfd525a0fc26e5da72b20e8a1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Singapore differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Srednekolymsk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Srednekolymsk new file mode 100644 index 0000000000000000000000000000000000000000..7fdee5cbee2b1ba0904a672dde16240404466fb9 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Srednekolymsk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Tbilisi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Tbilisi new file mode 100644 index 0000000000000000000000000000000000000000..166e4341d6ce65728367641a467a925800044df6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Tbilisi differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Tel_Aviv b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Tel_Aviv new file mode 100644 index 0000000000000000000000000000000000000000..4c49bbf52440631eca750cacb7d79f259eeb8bd2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Tel_Aviv differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Thimbu b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Thimbu new file mode 100644 index 0000000000000000000000000000000000000000..0edc72cfe46b1976bff562929501f202a205d0cc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Thimbu differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Thimphu b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Thimphu new file mode 100644 index 0000000000000000000000000000000000000000..0edc72cfe46b1976bff562929501f202a205d0cc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Thimphu differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Tomsk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Tomsk new file mode 100644 index 0000000000000000000000000000000000000000..c3c307d7b99f39328cf289360526399c55984af6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Tomsk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ujung_Pandang b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ujung_Pandang new file mode 100644 index 0000000000000000000000000000000000000000..5990010b649745369501c7641c401bcad4345b85 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ujung_Pandang differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ulaanbaatar b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ulaanbaatar new file mode 100644 index 0000000000000000000000000000000000000000..6f5d3a15abbe48b8a4dc72aadc88c416160a56a6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ulaanbaatar differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ulan_Bator b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ulan_Bator new file mode 100644 index 0000000000000000000000000000000000000000..6f5d3a15abbe48b8a4dc72aadc88c416160a56a6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ulan_Bator differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Urumqi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Urumqi new file mode 100644 index 0000000000000000000000000000000000000000..69ff7f6fb4973efb1185cad9f553f8c770c75934 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Urumqi differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ust-Nera b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ust-Nera new file mode 100644 index 0000000000000000000000000000000000000000..c39331e3aa7d7c3c9f38e8ef83e739f0d09194b3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Ust-Nera differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Vientiane b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Vientiane new file mode 100644 index 0000000000000000000000000000000000000000..ed687d2985c208171adcaa3401496b05325edca4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Vientiane differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Vladivostok b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Vladivostok new file mode 100644 index 0000000000000000000000000000000000000000..72a3d4e87a0d6f568eeb84b4a9dfae0b679d23ff Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Vladivostok differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Yakutsk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Yakutsk new file mode 100644 index 0000000000000000000000000000000000000000..336f932e8d458b5096d4aa9483f3177f8d5888eb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Yakutsk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Yangon b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Yangon new file mode 100644 index 0000000000000000000000000000000000000000..14b2ad09ead50a62d5e2b426396c51f9beb293be Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Yangon differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Yekaterinburg b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Yekaterinburg new file mode 100644 index 0000000000000000000000000000000000000000..a3bf7f29b6f14debfbd0f8ccb45f1ea338009ef7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Yekaterinburg differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Yerevan b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Yerevan new file mode 100644 index 0000000000000000000000000000000000000000..6dd927cb94101609afa1d505129296370cd8aabe Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Yerevan differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Azores b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Azores new file mode 100644 index 0000000000000000000000000000000000000000..cda1c1d225ae261ae433579e56d94a84ae2acd38 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Azores differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Bermuda b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Bermuda new file mode 100644 index 0000000000000000000000000000000000000000..abc75ea7ef87f054cdcea06728b99e3540108860 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Bermuda differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Canary b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Canary new file mode 100644 index 0000000000000000000000000000000000000000..5ab3243a5f01f5056127f160cfe693c33edf0531 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Canary differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Cape_Verde b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Cape_Verde new file mode 100644 index 0000000000000000000000000000000000000000..8f7de1c0a19a8d3e0e749626c76c8d4dbd3c4de7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Cape_Verde differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Faeroe b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Faeroe new file mode 100644 index 0000000000000000000000000000000000000000..9558bf7180acab14d3b3f63c956f5224f680b2a3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Faeroe differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Faroe b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Faroe new file mode 100644 index 0000000000000000000000000000000000000000..9558bf7180acab14d3b3f63c956f5224f680b2a3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Faroe differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Jan_Mayen b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Jan_Mayen new file mode 100644 index 0000000000000000000000000000000000000000..465546bd396ae5eb75076f13ba9c29b0c926c835 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Jan_Mayen differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Madeira b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Madeira new file mode 100644 index 0000000000000000000000000000000000000000..21e84571ee1694758dd244ed0702fbae962648e6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Madeira differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Reykjavik b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Reykjavik new file mode 100644 index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Reykjavik differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/South_Georgia b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/South_Georgia new file mode 100644 index 0000000000000000000000000000000000000000..7fa5f4683538498b93d1e639c14256c1f033c354 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/South_Georgia differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/St_Helena b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/St_Helena new file mode 100644 index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/St_Helena differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Stanley b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Stanley new file mode 100644 index 0000000000000000000000000000000000000000..1a4c8ea86361731f4d7e854ac66d96a5ce6b2dbf Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Stanley differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Atlantic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/ACT b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/ACT new file mode 100644 index 0000000000000000000000000000000000000000..1975a3a4bd0ed93db1d10a2c562eb5bc3baaa489 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/ACT differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Adelaide b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Adelaide new file mode 100644 index 0000000000000000000000000000000000000000..3bfbbc563cf97dc2548ff8974ab23dcde28e8744 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Adelaide differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Brisbane b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Brisbane new file mode 100644 index 0000000000000000000000000000000000000000..dc9a980a65923b6629d788e4e03b4358ac151c15 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Brisbane differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Broken_Hill b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Broken_Hill new file mode 100644 index 0000000000000000000000000000000000000000..947b50995f4045ee6562cae21120dc8a05687653 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Broken_Hill differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Canberra b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Canberra new file mode 100644 index 0000000000000000000000000000000000000000..1975a3a4bd0ed93db1d10a2c562eb5bc3baaa489 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Canberra differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Currie b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Currie new file mode 100644 index 0000000000000000000000000000000000000000..dc2ef554dc389f4a34146329935e5c3581a0f2f4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Currie differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Darwin b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Darwin new file mode 100644 index 0000000000000000000000000000000000000000..a6a67300dd5ef87e421c9749702039a6bdbb928f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Darwin differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Eucla b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Eucla new file mode 100644 index 0000000000000000000000000000000000000000..9080f5cdb1216ef6397e7de6205173caa794c646 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Eucla differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Hobart b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Hobart new file mode 100644 index 0000000000000000000000000000000000000000..dc2ef554dc389f4a34146329935e5c3581a0f2f4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Hobart differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/LHI b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/LHI new file mode 100644 index 0000000000000000000000000000000000000000..4d4ec8ceea9a96956864eddff4900fc4fb9ba8f1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/LHI differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Lindeman b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Lindeman new file mode 100644 index 0000000000000000000000000000000000000000..131d77b54a2087ada0bb3a27d03bf752f84326a7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Lindeman differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Lord_Howe b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Lord_Howe new file mode 100644 index 0000000000000000000000000000000000000000..4d4ec8ceea9a96956864eddff4900fc4fb9ba8f1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Lord_Howe differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Melbourne b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Melbourne new file mode 100644 index 0000000000000000000000000000000000000000..d3f195ac2fac23afd46cc16650e0a2454f5a3923 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Melbourne differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/NSW b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/NSW new file mode 100644 index 0000000000000000000000000000000000000000..1975a3a4bd0ed93db1d10a2c562eb5bc3baaa489 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/NSW differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/North b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/North new file mode 100644 index 0000000000000000000000000000000000000000..a6a67300dd5ef87e421c9749702039a6bdbb928f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/North differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Perth b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Perth new file mode 100644 index 0000000000000000000000000000000000000000..4f771828c9b54d9bcaef82639425df4b3559b5e1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Perth differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Queensland b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Queensland new file mode 100644 index 0000000000000000000000000000000000000000..dc9a980a65923b6629d788e4e03b4358ac151c15 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Queensland differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/South b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/South new file mode 100644 index 0000000000000000000000000000000000000000..3bfbbc563cf97dc2548ff8974ab23dcde28e8744 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/South differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Sydney b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Sydney new file mode 100644 index 0000000000000000000000000000000000000000..1975a3a4bd0ed93db1d10a2c562eb5bc3baaa489 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Sydney differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Tasmania b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Tasmania new file mode 100644 index 0000000000000000000000000000000000000000..dc2ef554dc389f4a34146329935e5c3581a0f2f4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Tasmania differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Victoria b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Victoria new file mode 100644 index 0000000000000000000000000000000000000000..d3f195ac2fac23afd46cc16650e0a2454f5a3923 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Victoria differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/West b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/West new file mode 100644 index 0000000000000000000000000000000000000000..4f771828c9b54d9bcaef82639425df4b3559b5e1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/West differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Yancowinna b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Yancowinna new file mode 100644 index 0000000000000000000000000000000000000000..947b50995f4045ee6562cae21120dc8a05687653 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/Yancowinna differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Australia/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Brazil/Acre b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Brazil/Acre new file mode 100644 index 0000000000000000000000000000000000000000..fb5185ca60283bd56f795e9a956274c0b6e63325 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Brazil/Acre differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Brazil/DeNoronha b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Brazil/DeNoronha new file mode 100644 index 0000000000000000000000000000000000000000..9e74745ca79137918281337fa270c5fec4bd7da1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Brazil/DeNoronha differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Brazil/East b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Brazil/East new file mode 100644 index 0000000000000000000000000000000000000000..a16da2c4d5a980cd944d86c34ea8a2f597e39b71 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Brazil/East differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Brazil/West b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Brazil/West new file mode 100644 index 0000000000000000000000000000000000000000..59c952ebc65169dce30078a3e1ee371e0da52ae4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Brazil/West differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Brazil/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Brazil/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/CET b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/CET new file mode 100644 index 0000000000000000000000000000000000000000..31973271d2f87f7e9df4e8b0a1481f09a9e5407d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/CET differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/CST6CDT b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/CST6CDT new file mode 100644 index 0000000000000000000000000000000000000000..b016880653929aa40dd5ac0e82e4094a9d787cdf Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/CST6CDT differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Atlantic b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Atlantic new file mode 100644 index 0000000000000000000000000000000000000000..9fa850a7d4c36dea84149bc0ea2fcd3581d61a8c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Atlantic differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Central b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Central new file mode 100644 index 0000000000000000000000000000000000000000..7e646d18e18851bfde743b379e52df4ec5b5a20f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Central differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Eastern b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Eastern new file mode 100644 index 0000000000000000000000000000000000000000..668e70d765dc3fb0eda16fb0f1932af607b53412 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Eastern differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Mountain b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Mountain new file mode 100644 index 0000000000000000000000000000000000000000..645ee9453073acf4cff9f9420b358a8ebbe40f93 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Mountain differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Newfoundland b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Newfoundland new file mode 100644 index 0000000000000000000000000000000000000000..94d790baaccb72298bb577041cf3c8400339a7da Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Newfoundland differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Pacific b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Pacific new file mode 100644 index 0000000000000000000000000000000000000000..c998491112ea5e4430b8266498cf7f23e1266bc5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Pacific differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Saskatchewan b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Saskatchewan new file mode 100644 index 0000000000000000000000000000000000000000..a3f8217a544ebb0993473bbffaae8e2d723c4ec3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Saskatchewan differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Yukon b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Yukon new file mode 100644 index 0000000000000000000000000000000000000000..40baa9aba2a879f7a38a5a0f67e16e7a2d677a5e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Yukon differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Chile/Continental b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Chile/Continental new file mode 100644 index 0000000000000000000000000000000000000000..d3fc9b8343369abf5f14be781397f426c5969608 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Chile/Continental differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Chile/EasterIsland b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Chile/EasterIsland new file mode 100644 index 0000000000000000000000000000000000000000..54dff005b876339f5c1ff3dc0aeae1519c29b368 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Chile/EasterIsland differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Chile/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Chile/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Cuba b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Cuba new file mode 100644 index 0000000000000000000000000000000000000000..e06629d36841463326ff3350bc2f94d0417c3cdd Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Cuba differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/EET b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/EET new file mode 100644 index 0000000000000000000000000000000000000000..231bf9c3b713e3676dbd8f3ced867973c601e104 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/EET differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/EST b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/EST new file mode 100644 index 0000000000000000000000000000000000000000..9154643f4c9189998392afb8a93e2e2eb9eaecf5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/EST differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/EST5EDT b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/EST5EDT new file mode 100644 index 0000000000000000000000000000000000000000..2b6c2eea14df07392729ae9f5712a44ec4f02bae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/EST5EDT differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Egypt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Egypt new file mode 100644 index 0000000000000000000000000000000000000000..1e6d48d1ca4e5416913c41e8814dc045c57d5b58 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Egypt differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Eire b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Eire new file mode 100644 index 0000000000000000000000000000000000000000..17d2b1582df89d5794f20fb028956dd9da154922 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Eire differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT new file mode 100644 index 0000000000000000000000000000000000000000..157573b1d340e0f57a0dd4d9698bd3798cbf7136 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+0 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+0 new file mode 100644 index 0000000000000000000000000000000000000000..157573b1d340e0f57a0dd4d9698bd3798cbf7136 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+0 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+1 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+1 new file mode 100644 index 0000000000000000000000000000000000000000..98d5dcf917c6f1d9bd0018db0dc4dd0590e6a8ca Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+1 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+10 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+10 new file mode 100644 index 0000000000000000000000000000000000000000..ecb287e667868e92d97cdf5fee601e09cded0ff2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+10 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+11 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+11 new file mode 100644 index 0000000000000000000000000000000000000000..e941412971a4d805e311e8e4e7eb37e10994e4be Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+11 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+12 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+12 new file mode 100644 index 0000000000000000000000000000000000000000..9c95bd0736da8932cd70e1d9590f8a3ab676c620 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+12 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+2 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+2 new file mode 100644 index 0000000000000000000000000000000000000000..6d5ce3db7323d63f73e9e92b6f4d3d6b77632a94 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+2 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+3 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+3 new file mode 100644 index 0000000000000000000000000000000000000000..5ef7be71fd96e4ef66fce3ab675303559dbb22a3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+3 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+4 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+4 new file mode 100644 index 0000000000000000000000000000000000000000..75f16216f0d39ff98d969cd1f6703473f6fea50f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+4 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+5 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+5 new file mode 100644 index 0000000000000000000000000000000000000000..589990ae8966d1af67f1e05c21e14149adec2089 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+5 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+6 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+6 new file mode 100644 index 0000000000000000000000000000000000000000..fcb60ca2465a3e0c4febd41ac1a05bbb39fd96ed Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+6 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+7 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+7 new file mode 100644 index 0000000000000000000000000000000000000000..c0427a40eef929dcf25451be77c74af6e9111065 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+7 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+8 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+8 new file mode 100644 index 0000000000000000000000000000000000000000..9bdc2283c07d8dae0bb0147c7a7c648ac6a30405 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+8 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+9 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+9 new file mode 100644 index 0000000000000000000000000000000000000000..ca7a81f656f206f32586fdd294a2b385bb519b6a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+9 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-0 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-0 new file mode 100644 index 0000000000000000000000000000000000000000..157573b1d340e0f57a0dd4d9698bd3798cbf7136 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-0 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-1 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-1 new file mode 100644 index 0000000000000000000000000000000000000000..cb45601c958da687b3e3d63366aa259a8a1c5376 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-1 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-10 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-10 new file mode 100644 index 0000000000000000000000000000000000000000..11d988e10a3e318a7cba485d995872636d1acaf0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-10 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-11 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-11 new file mode 100644 index 0000000000000000000000000000000000000000..f4c5d5cc29b5c1687e9728b6b63cd2a5328c9dfb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-11 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-12 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-12 new file mode 100644 index 0000000000000000000000000000000000000000..cd397b02cdde1d348db020ce46785285feb312ba Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-12 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-13 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-13 new file mode 100644 index 0000000000000000000000000000000000000000..8fad7c6b0bef4b13898a94f4004726837cde975e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-13 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-14 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-14 new file mode 100644 index 0000000000000000000000000000000000000000..a595e60eeae161b68617bb401d4acc53dbac1846 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-14 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-2 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-2 new file mode 100644 index 0000000000000000000000000000000000000000..97b44a9baecfd5bd30393142c63323160353bf2f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-2 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-3 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-3 new file mode 100644 index 0000000000000000000000000000000000000000..4eb17ff0057b8843a0b840c6fef4b77accfe43b5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-3 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-4 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-4 new file mode 100644 index 0000000000000000000000000000000000000000..13aef80cbbcf0c938b8d11d92b0755e146a501d2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-4 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-5 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-5 new file mode 100644 index 0000000000000000000000000000000000000000..83a28169552f4fd39e9d0322398d787aad303e3c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-5 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-6 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-6 new file mode 100644 index 0000000000000000000000000000000000000000..79a983e5454a35f134cd4ad736ed912f3deae64f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-6 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-7 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-7 new file mode 100644 index 0000000000000000000000000000000000000000..e136690e165a933fbad2fdc0aba8d97886714fe0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-7 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-8 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-8 new file mode 100644 index 0000000000000000000000000000000000000000..bc70fe416fdbe3abb2c636a7bc1485b79e03af13 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-8 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-9 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-9 new file mode 100644 index 0000000000000000000000000000000000000000..d18cedd524f4cc132106d822fa8bb9bd3779edab Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-9 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT0 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT0 new file mode 100644 index 0000000000000000000000000000000000000000..157573b1d340e0f57a0dd4d9698bd3798cbf7136 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT0 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/Greenwich b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/Greenwich new file mode 100644 index 0000000000000000000000000000000000000000..157573b1d340e0f57a0dd4d9698bd3798cbf7136 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/Greenwich differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/UCT b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/UCT new file mode 100644 index 0000000000000000000000000000000000000000..00841a62213e6cccf7f0b7353e5e8ae214185486 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/UCT differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/UTC b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/UTC new file mode 100644 index 0000000000000000000000000000000000000000..00841a62213e6cccf7f0b7353e5e8ae214185486 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/UTC differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/Universal b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/Universal new file mode 100644 index 0000000000000000000000000000000000000000..00841a62213e6cccf7f0b7353e5e8ae214185486 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/Universal differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/Zulu b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/Zulu new file mode 100644 index 0000000000000000000000000000000000000000..00841a62213e6cccf7f0b7353e5e8ae214185486 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/Zulu differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Amsterdam b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Amsterdam new file mode 100644 index 0000000000000000000000000000000000000000..31973271d2f87f7e9df4e8b0a1481f09a9e5407d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Amsterdam differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Andorra b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Andorra new file mode 100644 index 0000000000000000000000000000000000000000..38685d4219d244f56f665c8afb92eaa6737badb8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Andorra differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Astrakhan b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Astrakhan new file mode 100644 index 0000000000000000000000000000000000000000..aff8d82d2a2de0857f78217cc9d04a112d1e1a08 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Astrakhan differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Athens b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Athens new file mode 100644 index 0000000000000000000000000000000000000000..231bf9c3b713e3676dbd8f3ced867973c601e104 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Athens differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Belfast b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Belfast new file mode 100644 index 0000000000000000000000000000000000000000..b9e95d92623c6cc4c35b16f7ceba3006f5ce4934 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Belfast differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Belgrade b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Belgrade new file mode 100644 index 0000000000000000000000000000000000000000..a1bf9281ed1bc2c9b82ee64efdca60b4af762ede Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Belgrade differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Berlin b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Berlin new file mode 100644 index 0000000000000000000000000000000000000000..465546bd396ae5eb75076f13ba9c29b0c926c835 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Berlin differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Bratislava b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Bratislava new file mode 100644 index 0000000000000000000000000000000000000000..fb7c145ac4c8ab8f39731e75db8c384b7dc4ee11 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Bratislava differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Brussels b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Brussels new file mode 100644 index 0000000000000000000000000000000000000000..31973271d2f87f7e9df4e8b0a1481f09a9e5407d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Brussels differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Bucharest b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Bucharest new file mode 100644 index 0000000000000000000000000000000000000000..c4a391e73b97e1342d352c5cc15a0bace202deef Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Bucharest differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Budapest b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Budapest new file mode 100644 index 0000000000000000000000000000000000000000..940be4670a64ece1265dd28523d78a80f9008dd2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Budapest differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Busingen b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Busingen new file mode 100644 index 0000000000000000000000000000000000000000..388df2969f2dc56738183bd4f0d5755c4533a797 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Busingen differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Chisinau b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Chisinau new file mode 100644 index 0000000000000000000000000000000000000000..9152e68594bb66cc756e0407654a203952fbd4e5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Chisinau differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Copenhagen b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Copenhagen new file mode 100644 index 0000000000000000000000000000000000000000..465546bd396ae5eb75076f13ba9c29b0c926c835 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Copenhagen differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Dublin b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Dublin new file mode 100644 index 0000000000000000000000000000000000000000..17d2b1582df89d5794f20fb028956dd9da154922 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Dublin differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Gibraltar b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Gibraltar new file mode 100644 index 0000000000000000000000000000000000000000..017bb2e34746c8a11c6955d49cc492c974412801 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Gibraltar differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Guernsey b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Guernsey new file mode 100644 index 0000000000000000000000000000000000000000..b9e95d92623c6cc4c35b16f7ceba3006f5ce4934 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Guernsey differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Helsinki b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Helsinki new file mode 100644 index 0000000000000000000000000000000000000000..ff5e56530570974516d249927952c69da601b664 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Helsinki differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Isle_of_Man b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Isle_of_Man new file mode 100644 index 0000000000000000000000000000000000000000..b9e95d92623c6cc4c35b16f7ceba3006f5ce4934 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Isle_of_Man differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Istanbul b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Istanbul new file mode 100644 index 0000000000000000000000000000000000000000..c89186687300068ac4e8505cc0012a1dbf6a9960 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Istanbul differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Jersey b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Jersey new file mode 100644 index 0000000000000000000000000000000000000000..b9e95d92623c6cc4c35b16f7ceba3006f5ce4934 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Jersey differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Kaliningrad b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Kaliningrad new file mode 100644 index 0000000000000000000000000000000000000000..0ec475647055bd235131c6620aa46da7f43209ac Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Kaliningrad differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Kiev b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Kiev new file mode 100644 index 0000000000000000000000000000000000000000..753a6c86f38586797589233f4528837f5b09151c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Kiev differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Kirov b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Kirov new file mode 100644 index 0000000000000000000000000000000000000000..bfac56111d9cc81a93cce85205c685880433b96f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Kirov differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Kyiv b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Kyiv new file mode 100644 index 0000000000000000000000000000000000000000..753a6c86f38586797589233f4528837f5b09151c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Kyiv differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Lisbon b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Lisbon new file mode 100644 index 0000000000000000000000000000000000000000..7e9aae727b2b660e7f5e383121f445daf033a9c5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Lisbon differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Ljubljana b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Ljubljana new file mode 100644 index 0000000000000000000000000000000000000000..a1bf9281ed1bc2c9b82ee64efdca60b4af762ede Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Ljubljana differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/London b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/London new file mode 100644 index 0000000000000000000000000000000000000000..b9e95d92623c6cc4c35b16f7ceba3006f5ce4934 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/London differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Luxembourg b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Luxembourg new file mode 100644 index 0000000000000000000000000000000000000000..31973271d2f87f7e9df4e8b0a1481f09a9e5407d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Luxembourg differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Madrid b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Madrid new file mode 100644 index 0000000000000000000000000000000000000000..60bdf4d07e6ef544ff18013b272dfb851f1cc27c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Madrid differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Malta b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Malta new file mode 100644 index 0000000000000000000000000000000000000000..27539c2243ff2c6be1fe890995485be2df39bf77 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Malta differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Mariehamn b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Mariehamn new file mode 100644 index 0000000000000000000000000000000000000000..ff5e56530570974516d249927952c69da601b664 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Mariehamn differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Minsk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Minsk new file mode 100644 index 0000000000000000000000000000000000000000..30d3a672bf64d0d787ac92bc75d9bc1cc62855c9 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Minsk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Monaco b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Monaco new file mode 100644 index 0000000000000000000000000000000000000000..00a27264c2cb3e28f2f46e5c267e12d575236a9d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Monaco differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Moscow b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Moscow new file mode 100644 index 0000000000000000000000000000000000000000..5e6b6de6451b4408fb71ef73950712a0827d49a6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Moscow differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Nicosia b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Nicosia new file mode 100644 index 0000000000000000000000000000000000000000..390347f442a486e296689c189e3346695bba5105 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Nicosia differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Oslo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Oslo new file mode 100644 index 0000000000000000000000000000000000000000..465546bd396ae5eb75076f13ba9c29b0c926c835 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Oslo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Paris b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Paris new file mode 100644 index 0000000000000000000000000000000000000000..00a27264c2cb3e28f2f46e5c267e12d575236a9d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Paris differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Podgorica b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Podgorica new file mode 100644 index 0000000000000000000000000000000000000000..a1bf9281ed1bc2c9b82ee64efdca60b4af762ede Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Podgorica differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Prague b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Prague new file mode 100644 index 0000000000000000000000000000000000000000..fb7c145ac4c8ab8f39731e75db8c384b7dc4ee11 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Prague differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Riga b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Riga new file mode 100644 index 0000000000000000000000000000000000000000..d99170b6420d4b91ec0c0e4652136f765974e0d8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Riga differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Rome b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Rome new file mode 100644 index 0000000000000000000000000000000000000000..639ca3be4062496b10a8dee26be3733cf457fbdd Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Rome differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Samara b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Samara new file mode 100644 index 0000000000000000000000000000000000000000..8d0c26e5c85294b799e1f346994b04948d3175fe Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Samara differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/San_Marino b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/San_Marino new file mode 100644 index 0000000000000000000000000000000000000000..639ca3be4062496b10a8dee26be3733cf457fbdd Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/San_Marino differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Sarajevo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Sarajevo new file mode 100644 index 0000000000000000000000000000000000000000..a1bf9281ed1bc2c9b82ee64efdca60b4af762ede Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Sarajevo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Saratov b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Saratov new file mode 100644 index 0000000000000000000000000000000000000000..2684d8f8b89f7807ed4a0fcba89822b24a0166bb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Saratov differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Simferopol b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Simferopol new file mode 100644 index 0000000000000000000000000000000000000000..298b8326ca7ab3e86b5f508fd06fc744b4a142f6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Simferopol differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Skopje b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Skopje new file mode 100644 index 0000000000000000000000000000000000000000..a1bf9281ed1bc2c9b82ee64efdca60b4af762ede Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Skopje differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Sofia b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Sofia new file mode 100644 index 0000000000000000000000000000000000000000..89450685cd149950dc6d65d1b4f076d96c3dc9a0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Sofia differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Stockholm b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Stockholm new file mode 100644 index 0000000000000000000000000000000000000000..465546bd396ae5eb75076f13ba9c29b0c926c835 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Stockholm differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Tallinn b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Tallinn new file mode 100644 index 0000000000000000000000000000000000000000..fbebdc6255b547b1f3a547f0f92cc8148f05f186 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Tallinn differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Tirane b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Tirane new file mode 100644 index 0000000000000000000000000000000000000000..743a7337ffd8c404d1da0d2d078ea1cd8459affe Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Tirane differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Tiraspol b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Tiraspol new file mode 100644 index 0000000000000000000000000000000000000000..9152e68594bb66cc756e0407654a203952fbd4e5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Tiraspol differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Ulyanovsk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Ulyanovsk new file mode 100644 index 0000000000000000000000000000000000000000..bb842cb1f5087d422630f76f17c3a5eee6490a6b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Ulyanovsk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Uzhgorod b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Uzhgorod new file mode 100644 index 0000000000000000000000000000000000000000..753a6c86f38586797589233f4528837f5b09151c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Uzhgorod differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Vaduz b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Vaduz new file mode 100644 index 0000000000000000000000000000000000000000..388df2969f2dc56738183bd4f0d5755c4533a797 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Vaduz differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Vatican b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Vatican new file mode 100644 index 0000000000000000000000000000000000000000..639ca3be4062496b10a8dee26be3733cf457fbdd Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Vatican differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Vienna b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Vienna new file mode 100644 index 0000000000000000000000000000000000000000..75339e98d0a72f2792924294d7a9e560dba4648f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Vienna differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Vilnius b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Vilnius new file mode 100644 index 0000000000000000000000000000000000000000..43c3d7f1089366e1c48297906c2693712ac6d99c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Vilnius differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Volgograd b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Volgograd new file mode 100644 index 0000000000000000000000000000000000000000..0715d58bc1873c8bae589a08752cbbae562692c7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Volgograd differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Warsaw b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Warsaw new file mode 100644 index 0000000000000000000000000000000000000000..efe1a40f2a8ffd499d22cd83e6b5df6c6c1e8e5c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Warsaw differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Zagreb b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Zagreb new file mode 100644 index 0000000000000000000000000000000000000000..a1bf9281ed1bc2c9b82ee64efdca60b4af762ede Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Zagreb differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Zaporozhye b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Zaporozhye new file mode 100644 index 0000000000000000000000000000000000000000..753a6c86f38586797589233f4528837f5b09151c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Zaporozhye differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Zurich b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Zurich new file mode 100644 index 0000000000000000000000000000000000000000..388df2969f2dc56738183bd4f0d5755c4533a797 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/Zurich differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Europe/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Factory b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Factory new file mode 100644 index 0000000000000000000000000000000000000000..b4dd7735ed5b945e3403f2dd7cd57712dc9184d3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Factory differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GB b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GB new file mode 100644 index 0000000000000000000000000000000000000000..b9e95d92623c6cc4c35b16f7ceba3006f5ce4934 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GB differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GB-Eire b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GB-Eire new file mode 100644 index 0000000000000000000000000000000000000000..b9e95d92623c6cc4c35b16f7ceba3006f5ce4934 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GB-Eire differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GMT b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GMT new file mode 100644 index 0000000000000000000000000000000000000000..157573b1d340e0f57a0dd4d9698bd3798cbf7136 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GMT differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GMT+0 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GMT+0 new file mode 100644 index 0000000000000000000000000000000000000000..157573b1d340e0f57a0dd4d9698bd3798cbf7136 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GMT+0 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GMT-0 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GMT-0 new file mode 100644 index 0000000000000000000000000000000000000000..157573b1d340e0f57a0dd4d9698bd3798cbf7136 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GMT-0 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GMT0 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GMT0 new file mode 100644 index 0000000000000000000000000000000000000000..157573b1d340e0f57a0dd4d9698bd3798cbf7136 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/GMT0 differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Greenwich b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Greenwich new file mode 100644 index 0000000000000000000000000000000000000000..157573b1d340e0f57a0dd4d9698bd3798cbf7136 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Greenwich differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/HST b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/HST new file mode 100644 index 0000000000000000000000000000000000000000..40e3d492e6c22c30041c31f159d4fe0ee9451c03 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/HST differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Hongkong b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Hongkong new file mode 100644 index 0000000000000000000000000000000000000000..c80e364801be87687625f72e8e2c3dbd0f7ae4bc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Hongkong differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Iceland b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Iceland new file mode 100644 index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Iceland differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Antananarivo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Antananarivo new file mode 100644 index 0000000000000000000000000000000000000000..5f4ebcb7f9789c4ecda13ac66c2e768851113004 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Antananarivo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Chagos b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Chagos new file mode 100644 index 0000000000000000000000000000000000000000..8b8ce226b6b7f67229577b837775e7d448348bde Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Chagos differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Christmas b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Christmas new file mode 100644 index 0000000000000000000000000000000000000000..ed687d2985c208171adcaa3401496b05325edca4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Christmas differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Cocos b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Cocos new file mode 100644 index 0000000000000000000000000000000000000000..14b2ad09ead50a62d5e2b426396c51f9beb293be Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Cocos differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Comoro b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Comoro new file mode 100644 index 0000000000000000000000000000000000000000..5f4ebcb7f9789c4ecda13ac66c2e768851113004 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Comoro differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Kerguelen b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Kerguelen new file mode 100644 index 0000000000000000000000000000000000000000..58a82e4eb701ecb0413f908c57080646be392bba Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Kerguelen differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Mahe b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Mahe new file mode 100644 index 0000000000000000000000000000000000000000..58d75bc26eec90272e97696f40483eb56c2b8b45 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Mahe differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Maldives b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Maldives new file mode 100644 index 0000000000000000000000000000000000000000..58a82e4eb701ecb0413f908c57080646be392bba Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Maldives differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Mauritius b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Mauritius new file mode 100644 index 0000000000000000000000000000000000000000..7c1113488200c4d45ddb533bbebd899e2073f750 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Mauritius differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Mayotte b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Mayotte new file mode 100644 index 0000000000000000000000000000000000000000..5f4ebcb7f9789c4ecda13ac66c2e768851113004 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Mayotte differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Reunion b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Reunion new file mode 100644 index 0000000000000000000000000000000000000000..58d75bc26eec90272e97696f40483eb56c2b8b45 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/Reunion differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Indian/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Iran b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Iran new file mode 100644 index 0000000000000000000000000000000000000000..6fd31e075a29223eeea3f9a1a747b4531775f8ef Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Iran differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Israel b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Israel new file mode 100644 index 0000000000000000000000000000000000000000..4c49bbf52440631eca750cacb7d79f259eeb8bd2 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Israel differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Jamaica b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Jamaica new file mode 100644 index 0000000000000000000000000000000000000000..be6b1b6f1e77a8f13a7400bcfc10c63a7ee1d55d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Jamaica differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Japan b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Japan new file mode 100644 index 0000000000000000000000000000000000000000..1aa066ce38fce7bd0a680f51d6f075718d153a77 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Japan differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Kwajalein b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Kwajalein new file mode 100644 index 0000000000000000000000000000000000000000..9416d522d0a3e19ab6b81317f5b94961c55e91fc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Kwajalein differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Libya b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Libya new file mode 100644 index 0000000000000000000000000000000000000000..e0c89971aabea2c87842a9276b043d0fd946e34e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Libya differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/MET b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/MET new file mode 100644 index 0000000000000000000000000000000000000000..31973271d2f87f7e9df4e8b0a1481f09a9e5407d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/MET differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/MST b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/MST new file mode 100644 index 0000000000000000000000000000000000000000..c2bd2f949b248b835c98216b4dc66f9f6eb0265e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/MST differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/MST7MDT b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/MST7MDT new file mode 100644 index 0000000000000000000000000000000000000000..09e54e5c7c5bb2384e37626d4b985cfad29ed29b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/MST7MDT differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Mexico/BajaNorte b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Mexico/BajaNorte new file mode 100644 index 0000000000000000000000000000000000000000..18d0d14afc1cdf37c8f3607181e3f72211da99e9 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Mexico/BajaNorte differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Mexico/BajaSur b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Mexico/BajaSur new file mode 100644 index 0000000000000000000000000000000000000000..5aa6039ea4cb36077f048782b54c6275c25e86b3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Mexico/BajaSur differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Mexico/General b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Mexico/General new file mode 100644 index 0000000000000000000000000000000000000000..18112346129a885b5d5fa27109682b63784f72c0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Mexico/General differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Mexico/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Mexico/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/NZ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/NZ new file mode 100644 index 0000000000000000000000000000000000000000..afb3929318475d4f0ea9d6c9e94d0f5f81d8b82e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/NZ differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/NZ-CHAT b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/NZ-CHAT new file mode 100644 index 0000000000000000000000000000000000000000..f06065ebd18315683f60cf87839d477a1d699f01 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/NZ-CHAT differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Navajo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Navajo new file mode 100644 index 0000000000000000000000000000000000000000..09e54e5c7c5bb2384e37626d4b985cfad29ed29b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Navajo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/PRC b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/PRC new file mode 100644 index 0000000000000000000000000000000000000000..d6b66984a2f36ae36b35e174756707aa7286c292 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/PRC differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/PST8PDT b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/PST8PDT new file mode 100644 index 0000000000000000000000000000000000000000..aaf07787ad92b65eadae63b64bba290f9f961507 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/PST8PDT differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Apia b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Apia new file mode 100644 index 0000000000000000000000000000000000000000..a6b835aab4c5e2e2a31bda0afdc8646b57d19a87 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Apia differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Auckland b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Auckland new file mode 100644 index 0000000000000000000000000000000000000000..afb3929318475d4f0ea9d6c9e94d0f5f81d8b82e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Auckland differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Bougainville b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Bougainville new file mode 100644 index 0000000000000000000000000000000000000000..7c667093c50d33ce9161662a732fcf6c5092a38b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Bougainville differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Chatham b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Chatham new file mode 100644 index 0000000000000000000000000000000000000000..f06065ebd18315683f60cf87839d477a1d699f01 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Chatham differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Chuuk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Chuuk new file mode 100644 index 0000000000000000000000000000000000000000..5d8fc3a1b253d1df3a0184013469c6e46f6f6f75 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Chuuk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Easter b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Easter new file mode 100644 index 0000000000000000000000000000000000000000..54dff005b876339f5c1ff3dc0aeae1519c29b368 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Easter differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Efate b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Efate new file mode 100644 index 0000000000000000000000000000000000000000..bf7471dd3fc26b7fba883acf0e0bf0a69687b31e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Efate differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Enderbury b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Enderbury new file mode 100644 index 0000000000000000000000000000000000000000..2b6a06088ef603f03fb482b628347ff72970fe3d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Enderbury differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Fakaofo b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Fakaofo new file mode 100644 index 0000000000000000000000000000000000000000..b7b30213e154012a5275c1384b41dbff29860644 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Fakaofo differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Fiji b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Fiji new file mode 100644 index 0000000000000000000000000000000000000000..610b850b1dec4966d570eb36f9a8b35fd6aacd68 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Fiji differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Funafuti b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Funafuti new file mode 100644 index 0000000000000000000000000000000000000000..6bc216823e007c8dbdd6a5e8402b2e0cc5eaf3fc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Funafuti differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Galapagos b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Galapagos new file mode 100644 index 0000000000000000000000000000000000000000..a9403eca467d3b2ccf85b76bf2d94678a2ce3030 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Galapagos differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Gambier b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Gambier new file mode 100644 index 0000000000000000000000000000000000000000..ddfc34ffc0971e01ec4f13b78ddfa40033853cd1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Gambier differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Guadalcanal b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Guadalcanal new file mode 100644 index 0000000000000000000000000000000000000000..720c679017404f9b9ecec0687c09a879abf6d256 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Guadalcanal differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Guam b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Guam new file mode 100644 index 0000000000000000000000000000000000000000..bf9a2d955fc23bb6c2043472e8292d4adc20d4ed Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Guam differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Honolulu b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Honolulu new file mode 100644 index 0000000000000000000000000000000000000000..40e3d492e6c22c30041c31f159d4fe0ee9451c03 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Honolulu differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Johnston b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Johnston new file mode 100644 index 0000000000000000000000000000000000000000..40e3d492e6c22c30041c31f159d4fe0ee9451c03 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Johnston differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kanton b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kanton new file mode 100644 index 0000000000000000000000000000000000000000..2b6a06088ef603f03fb482b628347ff72970fe3d Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kanton differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kiritimati b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kiritimati new file mode 100644 index 0000000000000000000000000000000000000000..2f676d3bf5c8599994bcabd402ca30efa4cde5dd Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kiritimati differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kosrae b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kosrae new file mode 100644 index 0000000000000000000000000000000000000000..f5d58242c8198bfd7139883e1299b0706704bd32 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kosrae differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kwajalein b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kwajalein new file mode 100644 index 0000000000000000000000000000000000000000..9416d522d0a3e19ab6b81317f5b94961c55e91fc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kwajalein differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Majuro b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Majuro new file mode 100644 index 0000000000000000000000000000000000000000..6bc216823e007c8dbdd6a5e8402b2e0cc5eaf3fc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Majuro differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Marquesas b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Marquesas new file mode 100644 index 0000000000000000000000000000000000000000..6ea24b72cd9552c973510d1c17ace66fd35e1cc5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Marquesas differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Midway b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Midway new file mode 100644 index 0000000000000000000000000000000000000000..001289ceecff85fe0d0f376a6bc394329445f13f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Midway differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Nauru b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Nauru new file mode 100644 index 0000000000000000000000000000000000000000..ae13aac7792a04fe97b0a746f546e52d32f484c5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Nauru differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Niue b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Niue new file mode 100644 index 0000000000000000000000000000000000000000..be874e2472c2a79ed0d4de3011abd8831812911f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Niue differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Norfolk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Norfolk new file mode 100644 index 0000000000000000000000000000000000000000..0c0bdbda2a72022180bde561f6693268e27beb6b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Norfolk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Noumea b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Noumea new file mode 100644 index 0000000000000000000000000000000000000000..824f814160ee4a95cc6a6d5553b3c1aacc907895 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Noumea differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pago_Pago b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pago_Pago new file mode 100644 index 0000000000000000000000000000000000000000..001289ceecff85fe0d0f376a6bc394329445f13f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pago_Pago differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Palau b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Palau new file mode 100644 index 0000000000000000000000000000000000000000..bc8eb7a55b8a20a8c800507b620d0afef1d477a4 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Palau differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pitcairn b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pitcairn new file mode 100644 index 0000000000000000000000000000000000000000..8a4ba4d30a6b7da8399f20a8b98c91169e04ae40 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pitcairn differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pohnpei b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pohnpei new file mode 100644 index 0000000000000000000000000000000000000000..720c679017404f9b9ecec0687c09a879abf6d256 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pohnpei differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Ponape b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Ponape new file mode 100644 index 0000000000000000000000000000000000000000..720c679017404f9b9ecec0687c09a879abf6d256 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Ponape differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Port_Moresby b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Port_Moresby new file mode 100644 index 0000000000000000000000000000000000000000..5d8fc3a1b253d1df3a0184013469c6e46f6f6f75 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Port_Moresby differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Rarotonga b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Rarotonga new file mode 100644 index 0000000000000000000000000000000000000000..7220bda0adb9f04d704cb893a5d1ee8bd9173b82 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Rarotonga differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Saipan b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Saipan new file mode 100644 index 0000000000000000000000000000000000000000..bf9a2d955fc23bb6c2043472e8292d4adc20d4ed Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Saipan differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Samoa b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Samoa new file mode 100644 index 0000000000000000000000000000000000000000..001289ceecff85fe0d0f376a6bc394329445f13f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Samoa differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tahiti b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tahiti new file mode 100644 index 0000000000000000000000000000000000000000..50a064fa0166a0dc22f89cdadf957a545d3f6544 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tahiti differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tarawa b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tarawa new file mode 100644 index 0000000000000000000000000000000000000000..6bc216823e007c8dbdd6a5e8402b2e0cc5eaf3fc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tarawa differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tongatapu b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tongatapu new file mode 100644 index 0000000000000000000000000000000000000000..f28c8401845f84a68a46d45ec2f5b1383a0274b8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tongatapu differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Truk b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Truk new file mode 100644 index 0000000000000000000000000000000000000000..5d8fc3a1b253d1df3a0184013469c6e46f6f6f75 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Truk differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Wake b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Wake new file mode 100644 index 0000000000000000000000000000000000000000..6bc216823e007c8dbdd6a5e8402b2e0cc5eaf3fc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Wake differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Wallis b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Wallis new file mode 100644 index 0000000000000000000000000000000000000000..6bc216823e007c8dbdd6a5e8402b2e0cc5eaf3fc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Wallis differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Yap b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Yap new file mode 100644 index 0000000000000000000000000000000000000000..5d8fc3a1b253d1df3a0184013469c6e46f6f6f75 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/Yap differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Pacific/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Poland b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Poland new file mode 100644 index 0000000000000000000000000000000000000000..efe1a40f2a8ffd499d22cd83e6b5df6c6c1e8e5c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Poland differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Portugal b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Portugal new file mode 100644 index 0000000000000000000000000000000000000000..7e9aae727b2b660e7f5e383121f445daf033a9c5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Portugal differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/ROC b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/ROC new file mode 100644 index 0000000000000000000000000000000000000000..35d89d036d07c3f28dec64092ab1b533c21ae2bc Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/ROC differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/ROK b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/ROK new file mode 100644 index 0000000000000000000000000000000000000000..1755147fab44e07b7527ce1eaf3ae991473fb222 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/ROK differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Singapore b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Singapore new file mode 100644 index 0000000000000000000000000000000000000000..dbbdea3c8149004cfd525a0fc26e5da72b20e8a1 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Singapore differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Turkey b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Turkey new file mode 100644 index 0000000000000000000000000000000000000000..c89186687300068ac4e8505cc0012a1dbf6a9960 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Turkey differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/UCT b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/UCT new file mode 100644 index 0000000000000000000000000000000000000000..00841a62213e6cccf7f0b7353e5e8ae214185486 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/UCT differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Alaska b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Alaska new file mode 100644 index 0000000000000000000000000000000000000000..cdf0572be31d3052a98494e3d01802b83737f23c Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Alaska differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Aleutian b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Aleutian new file mode 100644 index 0000000000000000000000000000000000000000..b1497bda631efdcb6635ffb6b0ee6f7da9e2a280 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Aleutian differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Arizona b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Arizona new file mode 100644 index 0000000000000000000000000000000000000000..c2bd2f949b248b835c98216b4dc66f9f6eb0265e Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Arizona differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Central b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Central new file mode 100644 index 0000000000000000000000000000000000000000..b016880653929aa40dd5ac0e82e4094a9d787cdf Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Central differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/East-Indiana b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/East-Indiana new file mode 100644 index 0000000000000000000000000000000000000000..6b08d15bdaba6cf94dcb2681887154f4d265d8ba Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/East-Indiana differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Eastern b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Eastern new file mode 100644 index 0000000000000000000000000000000000000000..2b6c2eea14df07392729ae9f5712a44ec4f02bae Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Eastern differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Hawaii b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Hawaii new file mode 100644 index 0000000000000000000000000000000000000000..40e3d492e6c22c30041c31f159d4fe0ee9451c03 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Hawaii differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Indiana-Starke b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Indiana-Starke new file mode 100644 index 0000000000000000000000000000000000000000..b187d5f8c75685af67913e9360b50ecad19fe6ad Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Indiana-Starke differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Michigan b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Michigan new file mode 100644 index 0000000000000000000000000000000000000000..6eb3ac46ec56985b52488ae6a8d80247c2adcd4a Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Michigan differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Mountain b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Mountain new file mode 100644 index 0000000000000000000000000000000000000000..09e54e5c7c5bb2384e37626d4b985cfad29ed29b Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Mountain differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Pacific b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Pacific new file mode 100644 index 0000000000000000000000000000000000000000..aaf07787ad92b65eadae63b64bba290f9f961507 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Pacific differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Samoa b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Samoa new file mode 100644 index 0000000000000000000000000000000000000000..001289ceecff85fe0d0f376a6bc394329445f13f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/Samoa differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/US/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/UTC b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/UTC new file mode 100644 index 0000000000000000000000000000000000000000..00841a62213e6cccf7f0b7353e5e8ae214185486 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/UTC differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Universal b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Universal new file mode 100644 index 0000000000000000000000000000000000000000..00841a62213e6cccf7f0b7353e5e8ae214185486 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Universal differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/W-SU b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/W-SU new file mode 100644 index 0000000000000000000000000000000000000000..5e6b6de6451b4408fb71ef73950712a0827d49a6 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/W-SU differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/WET b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/WET new file mode 100644 index 0000000000000000000000000000000000000000..7e9aae727b2b660e7f5e383121f445daf033a9c5 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/WET differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Zulu b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Zulu new file mode 100644 index 0000000000000000000000000000000000000000..00841a62213e6cccf7f0b7353e5e8ae214185486 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/Zulu differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/iso3166.tab b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/iso3166.tab new file mode 100644 index 0000000000000000000000000000000000000000..402c015ec6b1071499155f7d28739db68be7763f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/iso3166.tab @@ -0,0 +1,279 @@ +# ISO 3166 alpha-2 country codes +# +# This file is in the public domain, so clarified as of +# 2009-05-17 by Arthur David Olson. +# +# From Paul Eggert (2023-09-06): +# This file contains a table of two-letter country codes. Columns are +# separated by a single tab. Lines beginning with '#' are comments. +# All text uses UTF-8 encoding. The columns of the table are as follows: +# +# 1. ISO 3166-1 alpha-2 country code, current as of +# ISO/TC 46 N1108 (2023-04-05). See: ISO/TC 46 Documents +# https://www.iso.org/committee/48750.html?view=documents +# 2. The usual English name for the coded region. This sometimes +# departs from ISO-listed names, sometimes so that sorted subsets +# of names are useful (e.g., "Samoa (American)" and "Samoa +# (western)" rather than "American Samoa" and "Samoa"), +# sometimes to avoid confusion among non-experts (e.g., +# "Czech Republic" and "Turkey" rather than "Czechia" and "Türkiye"), +# and sometimes to omit needless detail or churn (e.g., "Netherlands" +# rather than "Netherlands (the)" or "Netherlands (Kingdom of the)"). +# +# The table is sorted by country code. +# +# This table is intended as an aid for users, to help them select time +# zone data appropriate for their practical needs. It is not intended +# to take or endorse any position on legal or territorial claims. +# +#country- +#code name of country, territory, area, or subdivision +AD Andorra +AE United Arab Emirates +AF Afghanistan +AG Antigua & Barbuda +AI Anguilla +AL Albania +AM Armenia +AO Angola +AQ Antarctica +AR Argentina +AS Samoa (American) +AT Austria +AU Australia +AW Aruba +AX Åland Islands +AZ Azerbaijan +BA Bosnia & Herzegovina +BB Barbados +BD Bangladesh +BE Belgium +BF Burkina Faso +BG Bulgaria +BH Bahrain +BI Burundi +BJ Benin +BL St Barthelemy +BM Bermuda +BN Brunei +BO Bolivia +BQ Caribbean NL +BR Brazil +BS Bahamas +BT Bhutan +BV Bouvet Island +BW Botswana +BY Belarus +BZ Belize +CA Canada +CC Cocos (Keeling) Islands +CD Congo (Dem. Rep.) +CF Central African Rep. +CG Congo (Rep.) +CH Switzerland +CI Côte d'Ivoire +CK Cook Islands +CL Chile +CM Cameroon +CN China +CO Colombia +CR Costa Rica +CU Cuba +CV Cape Verde +CW Curaçao +CX Christmas Island +CY Cyprus +CZ Czech Republic +DE Germany +DJ Djibouti +DK Denmark +DM Dominica +DO Dominican Republic +DZ Algeria +EC Ecuador +EE Estonia +EG Egypt +EH Western Sahara +ER Eritrea +ES Spain +ET Ethiopia +FI Finland +FJ Fiji +FK Falkland Islands +FM Micronesia +FO Faroe Islands +FR France +GA Gabon +GB Britain (UK) +GD Grenada +GE Georgia +GF French Guiana +GG Guernsey +GH Ghana +GI Gibraltar +GL Greenland +GM Gambia +GN Guinea +GP Guadeloupe +GQ Equatorial Guinea +GR Greece +GS South Georgia & the South Sandwich Islands +GT Guatemala +GU Guam +GW Guinea-Bissau +GY Guyana +HK Hong Kong +HM Heard Island & McDonald Islands +HN Honduras +HR Croatia +HT Haiti +HU Hungary +ID Indonesia +IE Ireland +IL Israel +IM Isle of Man +IN India +IO British Indian Ocean Territory +IQ Iraq +IR Iran +IS Iceland +IT Italy +JE Jersey +JM Jamaica +JO Jordan +JP Japan +KE Kenya +KG Kyrgyzstan +KH Cambodia +KI Kiribati +KM Comoros +KN St Kitts & Nevis +KP Korea (North) +KR Korea (South) +KW Kuwait +KY Cayman Islands +KZ Kazakhstan +LA Laos +LB Lebanon +LC St Lucia +LI Liechtenstein +LK Sri Lanka +LR Liberia +LS Lesotho +LT Lithuania +LU Luxembourg +LV Latvia +LY Libya +MA Morocco +MC Monaco +MD Moldova +ME Montenegro +MF St Martin (French) +MG Madagascar +MH Marshall Islands +MK North Macedonia +ML Mali +MM Myanmar (Burma) +MN Mongolia +MO Macau +MP Northern Mariana Islands +MQ Martinique +MR Mauritania +MS Montserrat +MT Malta +MU Mauritius +MV Maldives +MW Malawi +MX Mexico +MY Malaysia +MZ Mozambique +NA Namibia +NC New Caledonia +NE Niger +NF Norfolk Island +NG Nigeria +NI Nicaragua +NL Netherlands +NO Norway +NP Nepal +NR Nauru +NU Niue +NZ New Zealand +OM Oman +PA Panama +PE Peru +PF French Polynesia +PG Papua New Guinea +PH Philippines +PK Pakistan +PL Poland +PM St Pierre & Miquelon +PN Pitcairn +PR Puerto Rico +PS Palestine +PT Portugal +PW Palau +PY Paraguay +QA Qatar +RE Réunion +RO Romania +RS Serbia +RU Russia +RW Rwanda +SA Saudi Arabia +SB Solomon Islands +SC Seychelles +SD Sudan +SE Sweden +SG Singapore +SH St Helena +SI Slovenia +SJ Svalbard & Jan Mayen +SK Slovakia +SL Sierra Leone +SM San Marino +SN Senegal +SO Somalia +SR Suriname +SS South Sudan +ST Sao Tome & Principe +SV El Salvador +SX St Maarten (Dutch) +SY Syria +SZ Eswatini (Swaziland) +TC Turks & Caicos Is +TD Chad +TF French S. Terr. +TG Togo +TH Thailand +TJ Tajikistan +TK Tokelau +TL East Timor +TM Turkmenistan +TN Tunisia +TO Tonga +TR Turkey +TT Trinidad & Tobago +TV Tuvalu +TW Taiwan +TZ Tanzania +UA Ukraine +UG Uganda +UM US minor outlying islands +US United States +UY Uruguay +UZ Uzbekistan +VA Vatican City +VC St Vincent +VE Venezuela +VG Virgin Islands (UK) +VI Virgin Islands (US) +VN Vietnam +VU Vanuatu +WF Wallis & Futuna +WS Samoa (western) +YE Yemen +YT Mayotte +ZA South Africa +ZM Zambia +ZW Zimbabwe diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/leapseconds b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/leapseconds new file mode 100644 index 0000000000000000000000000000000000000000..76f771427f25b91e6944ffd2fee6031bfd73979a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/leapseconds @@ -0,0 +1,79 @@ +# Allowance for leap seconds added to each time zone file. + +# This file is in the public domain. + +# This file is generated automatically from the data in the public-domain +# NIST/IERS format leap-seconds.list file, which can be copied from +# +# or, in a variant with different comments, from +# . +# For more about leap-seconds.list, please see +# The NTP Timescale and Leap Seconds +# . + +# The rules for leap seconds are specified in Annex 1 (Time scales) of: +# Standard-frequency and time-signal emissions. +# International Telecommunication Union - Radiocommunication Sector +# (ITU-R) Recommendation TF.460-6 (02/2002) +# . +# The International Earth Rotation and Reference Systems Service (IERS) +# periodically uses leap seconds to keep UTC to within 0.9 s of UT1 +# (a proxy for Earth's angle in space as measured by astronomers) +# and publishes leap second data in a copyrighted file +# . +# See: Levine J. Coordinated Universal Time and the leap second. +# URSI Radio Sci Bull. 2016;89(4):30-6. doi:10.23919/URSIRSB.2016.7909995 +# . + +# There were no leap seconds before 1972, as no official mechanism +# accounted for the discrepancy between atomic time (TAI) and the earth's +# rotation. The first ("1 Jan 1972") data line in leap-seconds.list +# does not denote a leap second; it denotes the start of the current definition +# of UTC. + +# All leap-seconds are Stationary (S) at the given UTC time. +# The correction (+ or -) is made at the given time, so in the unlikely +# event of a negative leap second, a line would look like this: +# Leap YEAR MON DAY 23:59:59 - S +# Typical lines look like this: +# Leap YEAR MON DAY 23:59:60 + S +Leap 1972 Jun 30 23:59:60 + S +Leap 1972 Dec 31 23:59:60 + S +Leap 1973 Dec 31 23:59:60 + S +Leap 1974 Dec 31 23:59:60 + S +Leap 1975 Dec 31 23:59:60 + S +Leap 1976 Dec 31 23:59:60 + S +Leap 1977 Dec 31 23:59:60 + S +Leap 1978 Dec 31 23:59:60 + S +Leap 1979 Dec 31 23:59:60 + S +Leap 1981 Jun 30 23:59:60 + S +Leap 1982 Jun 30 23:59:60 + S +Leap 1983 Jun 30 23:59:60 + S +Leap 1985 Jun 30 23:59:60 + S +Leap 1987 Dec 31 23:59:60 + S +Leap 1989 Dec 31 23:59:60 + S +Leap 1990 Dec 31 23:59:60 + S +Leap 1992 Jun 30 23:59:60 + S +Leap 1993 Jun 30 23:59:60 + S +Leap 1994 Jun 30 23:59:60 + S +Leap 1995 Dec 31 23:59:60 + S +Leap 1997 Jun 30 23:59:60 + S +Leap 1998 Dec 31 23:59:60 + S +Leap 2005 Dec 31 23:59:60 + S +Leap 2008 Dec 31 23:59:60 + S +Leap 2012 Jun 30 23:59:60 + S +Leap 2015 Jun 30 23:59:60 + S +Leap 2016 Dec 31 23:59:60 + S + +# UTC timestamp when this leap second list expires. +# Any additional leap seconds will come after this. +# This Expires line is commented out for now, +# so that pre-2020a zic implementations do not reject this file. +#Expires 2025 Dec 28 00:00:00 + +# POSIX timestamps for the data in this file: +#updated 1736208000 (2025-01-07 00:00:00 UTC) +#expires 1766880000 (2025-12-28 00:00:00 UTC) + +# Updated through IERS Bulletin C (https://hpiers.obspm.fr/iers/bul/bulc/bulletinc.dat) +# File expires on 28 December 2025 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/tzdata.zi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/tzdata.zi new file mode 100644 index 0000000000000000000000000000000000000000..a7fb52f1968f3d4ce81a207325e5d5618e657923 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/tzdata.zi @@ -0,0 +1,4300 @@ +# version 2025b +# This zic input file is in the public domain. +R d 1916 o - Jun 14 23s 1 S +R d 1916 1919 - O Su>=1 23s 0 - +R d 1917 o - Mar 24 23s 1 S +R d 1918 o - Mar 9 23s 1 S +R d 1919 o - Mar 1 23s 1 S +R d 1920 o - F 14 23s 1 S +R d 1920 o - O 23 23s 0 - +R d 1921 o - Mar 14 23s 1 S +R d 1921 o - Jun 21 23s 0 - +R d 1939 o - S 11 23s 1 S +R d 1939 o - N 19 1 0 - +R d 1944 1945 - Ap M>=1 2 1 S +R d 1944 o - O 8 2 0 - +R d 1945 o - S 16 1 0 - +R d 1971 o - Ap 25 23s 1 S +R d 1971 o - S 26 23s 0 - +R d 1977 o - May 6 0 1 S +R d 1977 o - O 21 0 0 - +R d 1978 o - Mar 24 1 1 S +R d 1978 o - S 22 3 0 - +R d 1980 o - Ap 25 0 1 S +R d 1980 o - O 31 2 0 - +R K 1940 o - Jul 15 0 1 S +R K 1940 o - O 1 0 0 - +R K 1941 o - Ap 15 0 1 S +R K 1941 o - S 16 0 0 - +R K 1942 1944 - Ap 1 0 1 S +R K 1942 o - O 27 0 0 - +R K 1943 1945 - N 1 0 0 - +R K 1945 o - Ap 16 0 1 S +R K 1957 o - May 10 0 1 S +R K 1957 1958 - O 1 0 0 - +R K 1958 o - May 1 0 1 S +R K 1959 1981 - May 1 1 1 S +R K 1959 1965 - S 30 3 0 - +R K 1966 1994 - O 1 3 0 - +R K 1982 o - Jul 25 1 1 S +R K 1983 o - Jul 12 1 1 S +R K 1984 1988 - May 1 1 1 S +R K 1989 o - May 6 1 1 S +R K 1990 1994 - May 1 1 1 S +R K 1995 2010 - Ap lastF 0s 1 S +R K 1995 2005 - S lastTh 24 0 - +R K 2006 o - S 21 24 0 - +R K 2007 o - S Th>=1 24 0 - +R K 2008 o - Au lastTh 24 0 - +R K 2009 o - Au 20 24 0 - +R K 2010 o - Au 10 24 0 - +R K 2010 o - S 9 24 1 S +R K 2010 o - S lastTh 24 0 - +R K 2014 o - May 15 24 1 S +R K 2014 o - Jun 26 24 0 - +R K 2014 o - Jul 31 24 1 S +R K 2014 o - S lastTh 24 0 - +R K 2023 ma - Ap lastF 0 1 S +R K 2023 ma - O lastTh 24 0 - +R L 1951 o - O 14 2 1 S +R L 1952 o - Ja 1 0 0 - +R L 1953 o - O 9 2 1 S +R L 1954 o - Ja 1 0 0 - +R L 1955 o - S 30 0 1 S +R L 1956 o - Ja 1 0 0 - +R L 1982 1984 - Ap 1 0 1 S +R L 1982 1985 - O 1 0 0 - +R L 1985 o - Ap 6 0 1 S +R L 1986 o - Ap 4 0 1 S +R L 1986 o - O 3 0 0 - +R L 1987 1989 - Ap 1 0 1 S +R L 1987 1989 - O 1 0 0 - +R L 1997 o - Ap 4 0 1 S +R L 1997 o - O 4 0 0 - +R L 2013 o - Mar lastF 1 1 S +R L 2013 o - O lastF 2 0 - +R MU 1982 o - O 10 0 1 - +R MU 1983 o - Mar 21 0 0 - +R MU 2008 o - O lastSu 2 1 - +R MU 2009 o - Mar lastSu 2 0 - +R M 1939 o - S 12 0 1 - +R M 1939 o - N 19 0 0 - +R M 1940 o - F 25 0 1 - +R M 1945 o - N 18 0 0 - +R M 1950 o - Jun 11 0 1 - +R M 1950 o - O 29 0 0 - +R M 1967 o - Jun 3 12 1 - +R M 1967 o - O 1 0 0 - +R M 1974 o - Jun 24 0 1 - +R M 1974 o - S 1 0 0 - +R M 1976 1977 - May 1 0 1 - +R M 1976 o - Au 1 0 0 - +R M 1977 o - S 28 0 0 - +R M 1978 o - Jun 1 0 1 - +R M 1978 o - Au 4 0 0 - +R M 2008 o - Jun 1 0 1 - +R M 2008 o - S 1 0 0 - +R M 2009 o - Jun 1 0 1 - +R M 2009 o - Au 21 0 0 - +R M 2010 o - May 2 0 1 - +R M 2010 o - Au 8 0 0 - +R M 2011 o - Ap 3 0 1 - +R M 2011 o - Jul 31 0 0 - +R M 2012 2013 - Ap lastSu 2 1 - +R M 2012 o - Jul 20 3 0 - +R M 2012 o - Au 20 2 1 - +R M 2012 o - S 30 3 0 - +R M 2013 o - Jul 7 3 0 - +R M 2013 o - Au 10 2 1 - +R M 2013 2018 - O lastSu 3 0 - +R M 2014 2018 - Mar lastSu 2 1 - +R M 2014 o - Jun 28 3 0 - +R M 2014 o - Au 2 2 1 - +R M 2015 o - Jun 14 3 0 - +R M 2015 o - Jul 19 2 1 - +R M 2016 o - Jun 5 3 0 - +R M 2016 o - Jul 10 2 1 - +R M 2017 o - May 21 3 0 - +R M 2017 o - Jul 2 2 1 - +R M 2018 o - May 13 3 0 - +R M 2018 o - Jun 17 2 1 - +R M 2019 o - May 5 3 -1 - +R M 2019 o - Jun 9 2 0 - +R M 2020 o - Ap 19 3 -1 - +R M 2020 o - May 31 2 0 - +R M 2021 o - Ap 11 3 -1 - +R M 2021 o - May 16 2 0 - +R M 2022 o - Mar 27 3 -1 - +R M 2022 o - May 8 2 0 - +R M 2023 o - Mar 19 3 -1 - +R M 2023 o - Ap 23 2 0 - +R M 2024 o - Mar 10 3 -1 - +R M 2024 o - Ap 14 2 0 - +R M 2025 o - F 23 3 -1 - +R M 2025 o - Ap 6 2 0 - +R M 2026 o - F 15 3 -1 - +R M 2026 o - Mar 22 2 0 - +R M 2027 o - F 7 3 -1 - +R M 2027 o - Mar 14 2 0 - +R M 2028 o - Ja 23 3 -1 - +R M 2028 o - Mar 5 2 0 - +R M 2029 o - Ja 14 3 -1 - +R M 2029 o - F 18 2 0 - +R M 2029 o - D 30 3 -1 - +R M 2030 o - F 10 2 0 - +R M 2030 o - D 22 3 -1 - +R M 2031 o - Ja 26 2 0 - +R M 2031 o - D 14 3 -1 - +R M 2032 o - Ja 18 2 0 - +R M 2032 o - N 28 3 -1 - +R M 2033 o - Ja 9 2 0 - +R M 2033 o - N 20 3 -1 - +R M 2033 o - D 25 2 0 - +R M 2034 o - N 5 3 -1 - +R M 2034 o - D 17 2 0 - +R M 2035 o - O 28 3 -1 - +R M 2035 o - D 9 2 0 - +R M 2036 o - O 19 3 -1 - +R M 2036 o - N 23 2 0 - +R M 2037 o - O 4 3 -1 - +R M 2037 o - N 15 2 0 - +R M 2038 o - S 26 3 -1 - +R M 2038 o - O 31 2 0 - +R M 2039 o - S 18 3 -1 - +R M 2039 o - O 23 2 0 - +R M 2040 o - S 2 3 -1 - +R M 2040 o - O 14 2 0 - +R M 2041 o - Au 25 3 -1 - +R M 2041 o - S 29 2 0 - +R M 2042 o - Au 10 3 -1 - +R M 2042 o - S 21 2 0 - +R M 2043 o - Au 2 3 -1 - +R M 2043 o - S 13 2 0 - +R M 2044 o - Jul 24 3 -1 - +R M 2044 o - Au 28 2 0 - +R M 2045 o - Jul 9 3 -1 - +R M 2045 o - Au 20 2 0 - +R M 2046 o - Jul 1 3 -1 - +R M 2046 o - Au 5 2 0 - +R M 2047 o - Jun 23 3 -1 - +R M 2047 o - Jul 28 2 0 - +R M 2048 o - Jun 7 3 -1 - +R M 2048 o - Jul 19 2 0 - +R M 2049 o - May 30 3 -1 - +R M 2049 o - Jul 4 2 0 - +R M 2050 o - May 15 3 -1 - +R M 2050 o - Jun 26 2 0 - +R M 2051 o - May 7 3 -1 - +R M 2051 o - Jun 18 2 0 - +R M 2052 o - Ap 28 3 -1 - +R M 2052 o - Jun 2 2 0 - +R M 2053 o - Ap 13 3 -1 - +R M 2053 o - May 25 2 0 - +R M 2054 o - Ap 5 3 -1 - +R M 2054 o - May 10 2 0 - +R M 2055 o - Mar 28 3 -1 - +R M 2055 o - May 2 2 0 - +R M 2056 o - Mar 12 3 -1 - +R M 2056 o - Ap 23 2 0 - +R M 2057 o - Mar 4 3 -1 - +R M 2057 o - Ap 8 2 0 - +R M 2058 o - F 17 3 -1 - +R M 2058 o - Mar 31 2 0 - +R M 2059 o - F 9 3 -1 - +R M 2059 o - Mar 23 2 0 - +R M 2060 o - F 1 3 -1 - +R M 2060 o - Mar 7 2 0 - +R M 2061 o - Ja 16 3 -1 - +R M 2061 o - F 27 2 0 - +R M 2062 o - Ja 8 3 -1 - +R M 2062 o - F 12 2 0 - +R M 2062 o - D 31 3 -1 - +R M 2063 o - F 4 2 0 - +R M 2063 o - D 16 3 -1 - +R M 2064 o - Ja 27 2 0 - +R M 2064 o - D 7 3 -1 - +R M 2065 o - Ja 11 2 0 - +R M 2065 o - N 22 3 -1 - +R M 2066 o - Ja 3 2 0 - +R M 2066 o - N 14 3 -1 - +R M 2066 o - D 26 2 0 - +R M 2067 o - N 6 3 -1 - +R M 2067 o - D 11 2 0 - +R M 2068 o - O 21 3 -1 - +R M 2068 o - D 2 2 0 - +R M 2069 o - O 13 3 -1 - +R M 2069 o - N 17 2 0 - +R M 2070 o - O 5 3 -1 - +R M 2070 o - N 9 2 0 - +R M 2071 o - S 20 3 -1 - +R M 2071 o - N 1 2 0 - +R M 2072 o - S 11 3 -1 - +R M 2072 o - O 16 2 0 - +R M 2073 o - Au 27 3 -1 - +R M 2073 o - O 8 2 0 - +R M 2074 o - Au 19 3 -1 - +R M 2074 o - S 30 2 0 - +R M 2075 o - Au 11 3 -1 - +R M 2075 o - S 15 2 0 - +R M 2076 o - Jul 26 3 -1 - +R M 2076 o - S 6 2 0 - +R M 2077 o - Jul 18 3 -1 - +R M 2077 o - Au 22 2 0 - +R M 2078 o - Jul 10 3 -1 - +R M 2078 o - Au 14 2 0 - +R M 2079 o - Jun 25 3 -1 - +R M 2079 o - Au 6 2 0 - +R M 2080 o - Jun 16 3 -1 - +R M 2080 o - Jul 21 2 0 - +R M 2081 o - Jun 1 3 -1 - +R M 2081 o - Jul 13 2 0 - +R M 2082 o - May 24 3 -1 - +R M 2082 o - Jun 28 2 0 - +R M 2083 o - May 16 3 -1 - +R M 2083 o - Jun 20 2 0 - +R M 2084 o - Ap 30 3 -1 - +R M 2084 o - Jun 11 2 0 - +R M 2085 o - Ap 22 3 -1 - +R M 2085 o - May 27 2 0 - +R M 2086 o - Ap 14 3 -1 - +R M 2086 o - May 19 2 0 - +R M 2087 o - Mar 30 3 -1 - +R M 2087 o - May 11 2 0 - +R NA 1994 o - Mar 21 0 -1 WAT +R NA 1994 2017 - S Su>=1 2 0 CAT +R NA 1995 2017 - Ap Su>=1 2 -1 WAT +R SA 1942 1943 - S Su>=15 2 1 - +R SA 1943 1944 - Mar Su>=15 2 0 - +R SD 1970 o - May 1 0 1 S +R SD 1970 1985 - O 15 0 0 - +R SD 1971 o - Ap 30 0 1 S +R SD 1972 1985 - Ap lastSu 0 1 S +R n 1939 o - Ap 15 23s 1 S +R n 1939 o - N 18 23s 0 - +R n 1940 o - F 25 23s 1 S +R n 1941 o - O 6 0 0 - +R n 1942 o - Mar 9 0 1 S +R n 1942 o - N 2 3 0 - +R n 1943 o - Mar 29 2 1 S +R n 1943 o - Ap 17 2 0 - +R n 1943 o - Ap 25 2 1 S +R n 1943 o - O 4 2 0 - +R n 1944 1945 - Ap M>=1 2 1 S +R n 1944 o - O 8 0 0 - +R n 1945 o - S 16 0 0 - +R n 1977 o - Ap 30 0s 1 S +R n 1977 o - S 24 0s 0 - +R n 1978 o - May 1 0s 1 S +R n 1978 o - O 1 0s 0 - +R n 1988 o - Jun 1 0s 1 S +R n 1988 1990 - S lastSu 0s 0 - +R n 1989 o - Mar 26 0s 1 S +R n 1990 o - May 1 0s 1 S +R n 2005 o - May 1 0s 1 S +R n 2005 o - S 30 1s 0 - +R n 2006 2008 - Mar lastSu 2s 1 S +R n 2006 2008 - O lastSu 2s 0 - +R Tr 2005 ma - Mar lastSu 1u 2 +02 +R Tr 2004 ma - O lastSu 1u 0 +00 +R AM 2011 o - Mar lastSu 2s 1 - +R AM 2011 o - O lastSu 2s 0 - +R AZ 1997 2015 - Mar lastSu 4 1 - +R AZ 1997 2015 - O lastSu 5 0 - +R BD 2009 o - Jun 19 23 1 - +R BD 2009 o - D 31 24 0 - +R Sh 1919 o - Ap 12 24 1 D +R Sh 1919 o - S 30 24 0 S +R Sh 1940 o - Jun 1 0 1 D +R Sh 1940 o - O 12 24 0 S +R Sh 1941 o - Mar 15 0 1 D +R Sh 1941 o - N 1 24 0 S +R Sh 1942 o - Ja 31 0 1 D +R Sh 1945 o - S 1 24 0 S +R Sh 1946 o - May 15 0 1 D +R Sh 1946 o - S 30 24 0 S +R Sh 1947 o - Ap 15 0 1 D +R Sh 1947 o - O 31 24 0 S +R Sh 1948 1949 - May 1 0 1 D +R Sh 1948 1949 - S 30 24 0 S +R CN 1986 o - May 4 2 1 D +R CN 1986 1991 - S Su>=11 2 0 S +R CN 1987 1991 - Ap Su>=11 2 1 D +R HK 1946 o - Ap 21 0 1 S +R HK 1946 o - D 1 3:30s 0 - +R HK 1947 o - Ap 13 3:30s 1 S +R HK 1947 o - N 30 3:30s 0 - +R HK 1948 o - May 2 3:30s 1 S +R HK 1948 1952 - O Su>=28 3:30s 0 - +R HK 1949 1953 - Ap Su>=1 3:30 1 S +R HK 1953 1964 - O Su>=31 3:30 0 - +R HK 1954 1964 - Mar Su>=18 3:30 1 S +R HK 1965 1976 - Ap Su>=16 3:30 1 S +R HK 1965 1976 - O Su>=16 3:30 0 - +R HK 1973 o - D 30 3:30 1 S +R HK 1979 o - May 13 3:30 1 S +R HK 1979 o - O 21 3:30 0 - +R f 1946 o - May 15 0 1 D +R f 1946 o - O 1 0 0 S +R f 1947 o - Ap 15 0 1 D +R f 1947 o - N 1 0 0 S +R f 1948 1951 - May 1 0 1 D +R f 1948 1951 - O 1 0 0 S +R f 1952 o - Mar 1 0 1 D +R f 1952 1954 - N 1 0 0 S +R f 1953 1959 - Ap 1 0 1 D +R f 1955 1961 - O 1 0 0 S +R f 1960 1961 - Jun 1 0 1 D +R f 1974 1975 - Ap 1 0 1 D +R f 1974 1975 - O 1 0 0 S +R f 1979 o - Jul 1 0 1 D +R f 1979 o - O 1 0 0 S +R _ 1942 1943 - Ap 30 23 1 - +R _ 1942 o - N 17 23 0 - +R _ 1943 o - S 30 23 0 S +R _ 1946 o - Ap 30 23s 1 D +R _ 1946 o - S 30 23s 0 S +R _ 1947 o - Ap 19 23s 1 D +R _ 1947 o - N 30 23s 0 S +R _ 1948 o - May 2 23s 1 D +R _ 1948 o - O 31 23s 0 S +R _ 1949 1950 - Ap Sa>=1 23s 1 D +R _ 1949 1950 - O lastSa 23s 0 S +R _ 1951 o - Mar 31 23s 1 D +R _ 1951 o - O 28 23s 0 S +R _ 1952 1953 - Ap Sa>=1 23s 1 D +R _ 1952 o - N 1 23s 0 S +R _ 1953 1954 - O lastSa 23s 0 S +R _ 1954 1956 - Mar Sa>=17 23s 1 D +R _ 1955 o - N 5 23s 0 S +R _ 1956 1964 - N Su>=1 3:30 0 S +R _ 1957 1964 - Mar Su>=18 3:30 1 D +R _ 1965 1973 - Ap Su>=16 3:30 1 D +R _ 1965 1966 - O Su>=16 2:30 0 S +R _ 1967 1976 - O Su>=16 3:30 0 S +R _ 1973 o - D 30 3:30 1 D +R _ 1975 1976 - Ap Su>=16 3:30 1 D +R _ 1979 o - May 13 3:30 1 D +R _ 1979 o - O Su>=16 3:30 0 S +R CY 1975 o - Ap 13 0 1 S +R CY 1975 o - O 12 0 0 - +R CY 1976 o - May 15 0 1 S +R CY 1976 o - O 11 0 0 - +R CY 1977 1980 - Ap Su>=1 0 1 S +R CY 1977 o - S 25 0 0 - +R CY 1978 o - O 2 0 0 - +R CY 1979 1997 - S lastSu 0 0 - +R CY 1981 1998 - Mar lastSu 0 1 S +R i 1910 o - Ja 1 0 0 - +R i 1977 o - Mar 21 23 1 - +R i 1977 o - O 20 24 0 - +R i 1978 o - Mar 24 24 1 - +R i 1978 o - Au 5 1 0 - +R i 1979 o - May 26 24 1 - +R i 1979 o - S 18 24 0 - +R i 1980 o - Mar 20 24 1 - +R i 1980 o - S 22 24 0 - +R i 1991 o - May 2 24 1 - +R i 1992 1995 - Mar 21 24 1 - +R i 1991 1995 - S 21 24 0 - +R i 1996 o - Mar 20 24 1 - +R i 1996 o - S 20 24 0 - +R i 1997 1999 - Mar 21 24 1 - +R i 1997 1999 - S 21 24 0 - +R i 2000 o - Mar 20 24 1 - +R i 2000 o - S 20 24 0 - +R i 2001 2003 - Mar 21 24 1 - +R i 2001 2003 - S 21 24 0 - +R i 2004 o - Mar 20 24 1 - +R i 2004 o - S 20 24 0 - +R i 2005 o - Mar 21 24 1 - +R i 2005 o - S 21 24 0 - +R i 2008 o - Mar 20 24 1 - +R i 2008 o - S 20 24 0 - +R i 2009 2011 - Mar 21 24 1 - +R i 2009 2011 - S 21 24 0 - +R i 2012 o - Mar 20 24 1 - +R i 2012 o - S 20 24 0 - +R i 2013 2015 - Mar 21 24 1 - +R i 2013 2015 - S 21 24 0 - +R i 2016 o - Mar 20 24 1 - +R i 2016 o - S 20 24 0 - +R i 2017 2019 - Mar 21 24 1 - +R i 2017 2019 - S 21 24 0 - +R i 2020 o - Mar 20 24 1 - +R i 2020 o - S 20 24 0 - +R i 2021 2022 - Mar 21 24 1 - +R i 2021 2022 - S 21 24 0 - +R IQ 1982 o - May 1 0 1 - +R IQ 1982 1984 - O 1 0 0 - +R IQ 1983 o - Mar 31 0 1 - +R IQ 1984 1985 - Ap 1 0 1 - +R IQ 1985 1990 - S lastSu 1s 0 - +R IQ 1986 1990 - Mar lastSu 1s 1 - +R IQ 1991 2007 - Ap 1 3s 1 - +R IQ 1991 2007 - O 1 3s 0 - +R Z 1940 o - May 31 24u 1 D +R Z 1940 o - S 30 24u 0 S +R Z 1940 o - N 16 24u 1 D +R Z 1942 1946 - O 31 24u 0 S +R Z 1943 1944 - Mar 31 24u 1 D +R Z 1945 1946 - Ap 15 24u 1 D +R Z 1948 o - May 22 24u 2 DD +R Z 1948 o - Au 31 24u 1 D +R Z 1948 1949 - O 31 24u 0 S +R Z 1949 o - Ap 30 24u 1 D +R Z 1950 o - Ap 15 24u 1 D +R Z 1950 o - S 14 24u 0 S +R Z 1951 o - Mar 31 24u 1 D +R Z 1951 o - N 10 24u 0 S +R Z 1952 o - Ap 19 24u 1 D +R Z 1952 o - O 18 24u 0 S +R Z 1953 o - Ap 11 24u 1 D +R Z 1953 o - S 12 24u 0 S +R Z 1954 o - Jun 12 24u 1 D +R Z 1954 o - S 11 24u 0 S +R Z 1955 o - Jun 11 24u 1 D +R Z 1955 o - S 10 24u 0 S +R Z 1956 o - Jun 2 24u 1 D +R Z 1956 o - S 29 24u 0 S +R Z 1957 o - Ap 27 24u 1 D +R Z 1957 o - S 21 24u 0 S +R Z 1974 o - Jul 6 24 1 D +R Z 1974 o - O 12 24 0 S +R Z 1975 o - Ap 19 24 1 D +R Z 1975 o - Au 30 24 0 S +R Z 1980 o - Au 2 24s 1 D +R Z 1980 o - S 13 24s 0 S +R Z 1984 o - May 5 24s 1 D +R Z 1984 o - Au 25 24s 0 S +R Z 1985 o - Ap 13 24 1 D +R Z 1985 o - Au 31 24 0 S +R Z 1986 o - May 17 24 1 D +R Z 1986 o - S 6 24 0 S +R Z 1987 o - Ap 14 24 1 D +R Z 1987 o - S 12 24 0 S +R Z 1988 o - Ap 9 24 1 D +R Z 1988 o - S 3 24 0 S +R Z 1989 o - Ap 29 24 1 D +R Z 1989 o - S 2 24 0 S +R Z 1990 o - Mar 24 24 1 D +R Z 1990 o - Au 25 24 0 S +R Z 1991 o - Mar 23 24 1 D +R Z 1991 o - Au 31 24 0 S +R Z 1992 o - Mar 28 24 1 D +R Z 1992 o - S 5 24 0 S +R Z 1993 o - Ap 2 0 1 D +R Z 1993 o - S 5 0 0 S +R Z 1994 o - Ap 1 0 1 D +R Z 1994 o - Au 28 0 0 S +R Z 1995 o - Mar 31 0 1 D +R Z 1995 o - S 3 0 0 S +R Z 1996 o - Mar 14 24 1 D +R Z 1996 o - S 15 24 0 S +R Z 1997 o - Mar 20 24 1 D +R Z 1997 o - S 13 24 0 S +R Z 1998 o - Mar 20 0 1 D +R Z 1998 o - S 6 0 0 S +R Z 1999 o - Ap 2 2 1 D +R Z 1999 o - S 3 2 0 S +R Z 2000 o - Ap 14 2 1 D +R Z 2000 o - O 6 1 0 S +R Z 2001 o - Ap 9 1 1 D +R Z 2001 o - S 24 1 0 S +R Z 2002 o - Mar 29 1 1 D +R Z 2002 o - O 7 1 0 S +R Z 2003 o - Mar 28 1 1 D +R Z 2003 o - O 3 1 0 S +R Z 2004 o - Ap 7 1 1 D +R Z 2004 o - S 22 1 0 S +R Z 2005 2012 - Ap F<=1 2 1 D +R Z 2005 o - O 9 2 0 S +R Z 2006 o - O 1 2 0 S +R Z 2007 o - S 16 2 0 S +R Z 2008 o - O 5 2 0 S +R Z 2009 o - S 27 2 0 S +R Z 2010 o - S 12 2 0 S +R Z 2011 o - O 2 2 0 S +R Z 2012 o - S 23 2 0 S +R Z 2013 ma - Mar F>=23 2 1 D +R Z 2013 ma - O lastSu 2 0 S +R JP 1948 o - May Sa>=1 24 1 D +R JP 1948 1951 - S Sa>=8 25 0 S +R JP 1949 o - Ap Sa>=1 24 1 D +R JP 1950 1951 - May Sa>=1 24 1 D +R J 1973 o - Jun 6 0 1 S +R J 1973 1975 - O 1 0 0 - +R J 1974 1977 - May 1 0 1 S +R J 1976 o - N 1 0 0 - +R J 1977 o - O 1 0 0 - +R J 1978 o - Ap 30 0 1 S +R J 1978 o - S 30 0 0 - +R J 1985 o - Ap 1 0 1 S +R J 1985 o - O 1 0 0 - +R J 1986 1988 - Ap F>=1 0 1 S +R J 1986 1990 - O F>=1 0 0 - +R J 1989 o - May 8 0 1 S +R J 1990 o - Ap 27 0 1 S +R J 1991 o - Ap 17 0 1 S +R J 1991 o - S 27 0 0 - +R J 1992 o - Ap 10 0 1 S +R J 1992 1993 - O F>=1 0 0 - +R J 1993 1998 - Ap F>=1 0 1 S +R J 1994 o - S F>=15 0 0 - +R J 1995 1998 - S F>=15 0s 0 - +R J 1999 o - Jul 1 0s 1 S +R J 1999 2002 - S lastF 0s 0 - +R J 2000 2001 - Mar lastTh 0s 1 S +R J 2002 2012 - Mar lastTh 24 1 S +R J 2003 o - O 24 0s 0 - +R J 2004 o - O 15 0s 0 - +R J 2005 o - S lastF 0s 0 - +R J 2006 2011 - O lastF 0s 0 - +R J 2013 o - D 20 0 0 - +R J 2014 2021 - Mar lastTh 24 1 S +R J 2014 2022 - O lastF 0s 0 - +R J 2022 o - F lastTh 24 1 S +R KG 1992 1996 - Ap Su>=7 0s 1 - +R KG 1992 1996 - S lastSu 0 0 - +R KG 1997 2005 - Mar lastSu 2:30 1 - +R KG 1997 2004 - O lastSu 2:30 0 - +R KR 1948 o - Jun 1 0 1 D +R KR 1948 o - S 12 24 0 S +R KR 1949 o - Ap 3 0 1 D +R KR 1949 1951 - S Sa>=7 24 0 S +R KR 1950 o - Ap 1 0 1 D +R KR 1951 o - May 6 0 1 D +R KR 1955 o - May 5 0 1 D +R KR 1955 o - S 8 24 0 S +R KR 1956 o - May 20 0 1 D +R KR 1956 o - S 29 24 0 S +R KR 1957 1960 - May Su>=1 0 1 D +R KR 1957 1960 - S Sa>=17 24 0 S +R KR 1987 1988 - May Su>=8 2 1 D +R KR 1987 1988 - O Su>=8 3 0 S +R l 1920 o - Mar 28 0 1 S +R l 1920 o - O 25 0 0 - +R l 1921 o - Ap 3 0 1 S +R l 1921 o - O 3 0 0 - +R l 1922 o - Mar 26 0 1 S +R l 1922 o - O 8 0 0 - +R l 1923 o - Ap 22 0 1 S +R l 1923 o - S 16 0 0 - +R l 1957 1961 - May 1 0 1 S +R l 1957 1961 - O 1 0 0 - +R l 1972 o - Jun 22 0 1 S +R l 1972 1977 - O 1 0 0 - +R l 1973 1977 - May 1 0 1 S +R l 1978 o - Ap 30 0 1 S +R l 1978 o - S 30 0 0 - +R l 1984 1987 - May 1 0 1 S +R l 1984 1991 - O 16 0 0 - +R l 1988 o - Jun 1 0 1 S +R l 1989 o - May 10 0 1 S +R l 1990 1992 - May 1 0 1 S +R l 1992 o - O 4 0 0 - +R l 1993 ma - Mar lastSu 0 1 S +R l 1993 1998 - S lastSu 0 0 - +R l 1999 ma - O lastSu 0 0 - +R NB 1935 1941 - S 14 0 0:20 - +R NB 1935 1941 - D 14 0 0 - +R X 1983 1984 - Ap 1 0 1 - +R X 1983 o - O 1 0 0 - +R X 1985 1998 - Mar lastSu 0 1 - +R X 1984 1998 - S lastSu 0 0 - +R X 2001 o - Ap lastSa 2 1 - +R X 2001 2006 - S lastSa 2 0 - +R X 2002 2006 - Mar lastSa 2 1 - +R X 2015 2016 - Mar lastSa 2 1 - +R X 2015 2016 - S lastSa 0 0 - +R PK 2002 o - Ap Su>=2 0 1 S +R PK 2002 o - O Su>=2 0 0 - +R PK 2008 o - Jun 1 0 1 S +R PK 2008 2009 - N 1 0 0 - +R PK 2009 o - Ap 15 0 1 S +R P 1999 2005 - Ap F>=15 0 1 S +R P 1999 2003 - O F>=15 0 0 - +R P 2004 o - O 1 1 0 - +R P 2005 o - O 4 2 0 - +R P 2006 2007 - Ap 1 0 1 S +R P 2006 o - S 22 0 0 - +R P 2007 o - S 13 2 0 - +R P 2008 2009 - Mar lastF 0 1 S +R P 2008 o - S 1 0 0 - +R P 2009 o - S 4 1 0 - +R P 2010 o - Mar 26 0 1 S +R P 2010 o - Au 11 0 0 - +R P 2011 o - Ap 1 0:1 1 S +R P 2011 o - Au 1 0 0 - +R P 2011 o - Au 30 0 1 S +R P 2011 o - S 30 0 0 - +R P 2012 2014 - Mar lastTh 24 1 S +R P 2012 o - S 21 1 0 - +R P 2013 o - S 27 0 0 - +R P 2014 o - O 24 0 0 - +R P 2015 o - Mar 28 0 1 S +R P 2015 o - O 23 1 0 - +R P 2016 2018 - Mar Sa<=30 1 1 S +R P 2016 2018 - O Sa<=30 1 0 - +R P 2019 o - Mar 29 0 1 S +R P 2019 o - O Sa<=30 0 0 - +R P 2020 2021 - Mar Sa<=30 0 1 S +R P 2020 o - O 24 1 0 - +R P 2021 o - O 29 1 0 - +R P 2022 o - Mar 27 0 1 S +R P 2022 2035 - O Sa<=30 2 0 - +R P 2023 o - Ap 29 2 1 S +R P 2024 o - Ap 20 2 1 S +R P 2025 o - Ap 12 2 1 S +R P 2026 2054 - Mar Sa<=30 2 1 S +R P 2036 o - O 18 2 0 - +R P 2037 o - O 10 2 0 - +R P 2038 o - S 25 2 0 - +R P 2039 o - S 17 2 0 - +R P 2040 o - S 1 2 0 - +R P 2040 o - O 20 2 1 S +R P 2040 2067 - O Sa<=30 2 0 - +R P 2041 o - Au 24 2 0 - +R P 2041 o - O 5 2 1 S +R P 2042 o - Au 16 2 0 - +R P 2042 o - S 27 2 1 S +R P 2043 o - Au 1 2 0 - +R P 2043 o - S 19 2 1 S +R P 2044 o - Jul 23 2 0 - +R P 2044 o - S 3 2 1 S +R P 2045 o - Jul 15 2 0 - +R P 2045 o - Au 26 2 1 S +R P 2046 o - Jun 30 2 0 - +R P 2046 o - Au 18 2 1 S +R P 2047 o - Jun 22 2 0 - +R P 2047 o - Au 3 2 1 S +R P 2048 o - Jun 6 2 0 - +R P 2048 o - Jul 25 2 1 S +R P 2049 o - May 29 2 0 - +R P 2049 o - Jul 10 2 1 S +R P 2050 o - May 21 2 0 - +R P 2050 o - Jul 2 2 1 S +R P 2051 o - May 6 2 0 - +R P 2051 o - Jun 24 2 1 S +R P 2052 o - Ap 27 2 0 - +R P 2052 o - Jun 8 2 1 S +R P 2053 o - Ap 12 2 0 - +R P 2053 o - May 31 2 1 S +R P 2054 o - Ap 4 2 0 - +R P 2054 o - May 23 2 1 S +R P 2055 o - May 8 2 1 S +R P 2056 o - Ap 29 2 1 S +R P 2057 o - Ap 14 2 1 S +R P 2058 o - Ap 6 2 1 S +R P 2059 ma - Mar Sa<=30 2 1 S +R P 2068 o - O 20 2 0 - +R P 2069 o - O 12 2 0 - +R P 2070 o - O 4 2 0 - +R P 2071 o - S 19 2 0 - +R P 2072 o - S 10 2 0 - +R P 2072 o - O 22 2 1 S +R P 2072 ma - O Sa<=30 2 0 - +R P 2073 o - S 2 2 0 - +R P 2073 o - O 14 2 1 S +R P 2074 o - Au 18 2 0 - +R P 2074 o - O 6 2 1 S +R P 2075 o - Au 10 2 0 - +R P 2075 o - S 21 2 1 S +R P 2076 o - Jul 25 2 0 - +R P 2076 o - S 12 2 1 S +R P 2077 o - Jul 17 2 0 - +R P 2077 o - S 4 2 1 S +R P 2078 o - Jul 9 2 0 - +R P 2078 o - Au 20 2 1 S +R P 2079 o - Jun 24 2 0 - +R P 2079 o - Au 12 2 1 S +R P 2080 o - Jun 15 2 0 - +R P 2080 o - Jul 27 2 1 S +R P 2081 o - Jun 7 2 0 - +R P 2081 o - Jul 19 2 1 S +R P 2082 o - May 23 2 0 - +R P 2082 o - Jul 11 2 1 S +R P 2083 o - May 15 2 0 - +R P 2083 o - Jun 26 2 1 S +R P 2084 o - Ap 29 2 0 - +R P 2084 o - Jun 17 2 1 S +R P 2085 o - Ap 21 2 0 - +R P 2085 o - Jun 9 2 1 S +R P 2086 o - Ap 13 2 0 - +R P 2086 o - May 25 2 1 S +R PH 1936 o - O 31 24 1 D +R PH 1937 o - Ja 15 24 0 S +R PH 1941 o - D 15 24 1 D +R PH 1945 o - N 30 24 0 S +R PH 1954 o - Ap 11 24 1 D +R PH 1954 o - Jun 4 24 0 S +R PH 1977 o - Mar 27 24 1 D +R PH 1977 o - S 21 24 0 S +R PH 1990 o - May 21 0 1 D +R PH 1990 o - Jul 28 24 0 S +R S 1920 1923 - Ap Su>=15 2 1 S +R S 1920 1923 - O Su>=1 2 0 - +R S 1962 o - Ap 29 2 1 S +R S 1962 o - O 1 2 0 - +R S 1963 1965 - May 1 2 1 S +R S 1963 o - S 30 2 0 - +R S 1964 o - O 1 2 0 - +R S 1965 o - S 30 2 0 - +R S 1966 o - Ap 24 2 1 S +R S 1966 1976 - O 1 2 0 - +R S 1967 1978 - May 1 2 1 S +R S 1977 1978 - S 1 2 0 - +R S 1983 1984 - Ap 9 2 1 S +R S 1983 1984 - O 1 2 0 - +R S 1986 o - F 16 2 1 S +R S 1986 o - O 9 2 0 - +R S 1987 o - Mar 1 2 1 S +R S 1987 1988 - O 31 2 0 - +R S 1988 o - Mar 15 2 1 S +R S 1989 o - Mar 31 2 1 S +R S 1989 o - O 1 2 0 - +R S 1990 o - Ap 1 2 1 S +R S 1990 o - S 30 2 0 - +R S 1991 o - Ap 1 0 1 S +R S 1991 1992 - O 1 0 0 - +R S 1992 o - Ap 8 0 1 S +R S 1993 o - Mar 26 0 1 S +R S 1993 o - S 25 0 0 - +R S 1994 1996 - Ap 1 0 1 S +R S 1994 2005 - O 1 0 0 - +R S 1997 1998 - Mar lastM 0 1 S +R S 1999 2006 - Ap 1 0 1 S +R S 2006 o - S 22 0 0 - +R S 2007 o - Mar lastF 0 1 S +R S 2007 o - N F>=1 0 0 - +R S 2008 o - Ap F>=1 0 1 S +R S 2008 o - N 1 0 0 - +R S 2009 o - Mar lastF 0 1 S +R S 2010 2011 - Ap F>=1 0 1 S +R S 2012 2022 - Mar lastF 0 1 S +R S 2009 2022 - O lastF 0 0 - +R AU 1917 o - Ja 1 2s 1 D +R AU 1917 o - Mar lastSu 2s 0 S +R AU 1942 o - Ja 1 2s 1 D +R AU 1942 o - Mar lastSu 2s 0 S +R AU 1942 o - S 27 2s 1 D +R AU 1943 1944 - Mar lastSu 2s 0 S +R AU 1943 o - O 3 2s 1 D +R AW 1974 o - O lastSu 2s 1 D +R AW 1975 o - Mar Su>=1 2s 0 S +R AW 1983 o - O lastSu 2s 1 D +R AW 1984 o - Mar Su>=1 2s 0 S +R AW 1991 o - N 17 2s 1 D +R AW 1992 o - Mar Su>=1 2s 0 S +R AW 2006 o - D 3 2s 1 D +R AW 2007 2009 - Mar lastSu 2s 0 S +R AW 2007 2008 - O lastSu 2s 1 D +R AQ 1971 o - O lastSu 2s 1 D +R AQ 1972 o - F lastSu 2s 0 S +R AQ 1989 1991 - O lastSu 2s 1 D +R AQ 1990 1992 - Mar Su>=1 2s 0 S +R Ho 1992 1993 - O lastSu 2s 1 D +R Ho 1993 1994 - Mar Su>=1 2s 0 S +R AS 1971 1985 - O lastSu 2s 1 D +R AS 1986 o - O 19 2s 1 D +R AS 1987 2007 - O lastSu 2s 1 D +R AS 1972 o - F 27 2s 0 S +R AS 1973 1985 - Mar Su>=1 2s 0 S +R AS 1986 1990 - Mar Su>=15 2s 0 S +R AS 1991 o - Mar 3 2s 0 S +R AS 1992 o - Mar 22 2s 0 S +R AS 1993 o - Mar 7 2s 0 S +R AS 1994 o - Mar 20 2s 0 S +R AS 1995 2005 - Mar lastSu 2s 0 S +R AS 2006 o - Ap 2 2s 0 S +R AS 2007 o - Mar lastSu 2s 0 S +R AS 2008 ma - Ap Su>=1 2s 0 S +R AS 2008 ma - O Su>=1 2s 1 D +R AT 1916 o - O Su>=1 2s 1 D +R AT 1917 o - Mar lastSu 2s 0 S +R AT 1917 1918 - O Su>=22 2s 1 D +R AT 1918 1919 - Mar Su>=1 2s 0 S +R AT 1967 o - O Su>=1 2s 1 D +R AT 1968 o - Mar Su>=29 2s 0 S +R AT 1968 1985 - O lastSu 2s 1 D +R AT 1969 1971 - Mar Su>=8 2s 0 S +R AT 1972 o - F lastSu 2s 0 S +R AT 1973 1981 - Mar Su>=1 2s 0 S +R AT 1982 1983 - Mar lastSu 2s 0 S +R AT 1984 1986 - Mar Su>=1 2s 0 S +R AT 1986 o - O Su>=15 2s 1 D +R AT 1987 1990 - Mar Su>=15 2s 0 S +R AT 1987 o - O Su>=22 2s 1 D +R AT 1988 1990 - O lastSu 2s 1 D +R AT 1991 1999 - O Su>=1 2s 1 D +R AT 1991 2005 - Mar lastSu 2s 0 S +R AT 2000 o - Au lastSu 2s 1 D +R AT 2001 ma - O Su>=1 2s 1 D +R AT 2006 o - Ap Su>=1 2s 0 S +R AT 2007 o - Mar lastSu 2s 0 S +R AT 2008 ma - Ap Su>=1 2s 0 S +R AV 1971 1985 - O lastSu 2s 1 D +R AV 1972 o - F lastSu 2s 0 S +R AV 1973 1985 - Mar Su>=1 2s 0 S +R AV 1986 1990 - Mar Su>=15 2s 0 S +R AV 1986 1987 - O Su>=15 2s 1 D +R AV 1988 1999 - O lastSu 2s 1 D +R AV 1991 1994 - Mar Su>=1 2s 0 S +R AV 1995 2005 - Mar lastSu 2s 0 S +R AV 2000 o - Au lastSu 2s 1 D +R AV 2001 2007 - O lastSu 2s 1 D +R AV 2006 o - Ap Su>=1 2s 0 S +R AV 2007 o - Mar lastSu 2s 0 S +R AV 2008 ma - Ap Su>=1 2s 0 S +R AV 2008 ma - O Su>=1 2s 1 D +R AN 1971 1985 - O lastSu 2s 1 D +R AN 1972 o - F 27 2s 0 S +R AN 1973 1981 - Mar Su>=1 2s 0 S +R AN 1982 o - Ap Su>=1 2s 0 S +R AN 1983 1985 - Mar Su>=1 2s 0 S +R AN 1986 1989 - Mar Su>=15 2s 0 S +R AN 1986 o - O 19 2s 1 D +R AN 1987 1999 - O lastSu 2s 1 D +R AN 1990 1995 - Mar Su>=1 2s 0 S +R AN 1996 2005 - Mar lastSu 2s 0 S +R AN 2000 o - Au lastSu 2s 1 D +R AN 2001 2007 - O lastSu 2s 1 D +R AN 2006 o - Ap Su>=1 2s 0 S +R AN 2007 o - Mar lastSu 2s 0 S +R AN 2008 ma - Ap Su>=1 2s 0 S +R AN 2008 ma - O Su>=1 2s 1 D +R LH 1981 1984 - O lastSu 2 1 - +R LH 1982 1985 - Mar Su>=1 2 0 - +R LH 1985 o - O lastSu 2 0:30 - +R LH 1986 1989 - Mar Su>=15 2 0 - +R LH 1986 o - O 19 2 0:30 - +R LH 1987 1999 - O lastSu 2 0:30 - +R LH 1990 1995 - Mar Su>=1 2 0 - +R LH 1996 2005 - Mar lastSu 2 0 - +R LH 2000 o - Au lastSu 2 0:30 - +R LH 2001 2007 - O lastSu 2 0:30 - +R LH 2006 o - Ap Su>=1 2 0 - +R LH 2007 o - Mar lastSu 2 0 - +R LH 2008 ma - Ap Su>=1 2 0 - +R LH 2008 ma - O Su>=1 2 0:30 - +R FJ 1998 1999 - N Su>=1 2 1 - +R FJ 1999 2000 - F lastSu 3 0 - +R FJ 2009 o - N 29 2 1 - +R FJ 2010 o - Mar lastSu 3 0 - +R FJ 2010 2013 - O Su>=21 2 1 - +R FJ 2011 o - Mar Su>=1 3 0 - +R FJ 2012 2013 - Ja Su>=18 3 0 - +R FJ 2014 o - Ja Su>=18 2 0 - +R FJ 2014 2018 - N Su>=1 2 1 - +R FJ 2015 2021 - Ja Su>=12 3 0 - +R FJ 2019 o - N Su>=8 2 1 - +R FJ 2020 o - D 20 2 1 - +R Gu 1959 o - Jun 27 2 1 D +R Gu 1961 o - Ja 29 2 0 S +R Gu 1967 o - S 1 2 1 D +R Gu 1969 o - Ja 26 0:1 0 S +R Gu 1969 o - Jun 22 2 1 D +R Gu 1969 o - Au 31 2 0 S +R Gu 1970 1971 - Ap lastSu 2 1 D +R Gu 1970 1971 - S Su>=1 2 0 S +R Gu 1973 o - D 16 2 1 D +R Gu 1974 o - F 24 2 0 S +R Gu 1976 o - May 26 2 1 D +R Gu 1976 o - Au 22 2:1 0 S +R Gu 1977 o - Ap 24 2 1 D +R Gu 1977 o - Au 28 2 0 S +R NC 1977 1978 - D Su>=1 0 1 - +R NC 1978 1979 - F 27 0 0 - +R NC 1996 o - D 1 2s 1 - +R NC 1997 o - Mar 2 2s 0 - +R NZ 1927 o - N 6 2 1 S +R NZ 1928 o - Mar 4 2 0 M +R NZ 1928 1933 - O Su>=8 2 0:30 S +R NZ 1929 1933 - Mar Su>=15 2 0 M +R NZ 1934 1940 - Ap lastSu 2 0 M +R NZ 1934 1940 - S lastSu 2 0:30 S +R NZ 1946 o - Ja 1 0 0 S +R NZ 1974 o - N Su>=1 2s 1 D +R k 1974 o - N Su>=1 2:45s 1 - +R NZ 1975 o - F lastSu 2s 0 S +R k 1975 o - F lastSu 2:45s 0 - +R NZ 1975 1988 - O lastSu 2s 1 D +R k 1975 1988 - O lastSu 2:45s 1 - +R NZ 1976 1989 - Mar Su>=1 2s 0 S +R k 1976 1989 - Mar Su>=1 2:45s 0 - +R NZ 1989 o - O Su>=8 2s 1 D +R k 1989 o - O Su>=8 2:45s 1 - +R NZ 1990 2006 - O Su>=1 2s 1 D +R k 1990 2006 - O Su>=1 2:45s 1 - +R NZ 1990 2007 - Mar Su>=15 2s 0 S +R k 1990 2007 - Mar Su>=15 2:45s 0 - +R NZ 2007 ma - S lastSu 2s 1 D +R k 2007 ma - S lastSu 2:45s 1 - +R NZ 2008 ma - Ap Su>=1 2s 0 S +R k 2008 ma - Ap Su>=1 2:45s 0 - +R CK 1978 o - N 12 0 0:30 - +R CK 1979 1991 - Mar Su>=1 0 0 - +R CK 1979 1990 - O lastSu 0 0:30 - +R WS 2010 o - S lastSu 0 1 - +R WS 2011 o - Ap Sa>=1 4 0 - +R WS 2011 o - S lastSa 3 1 - +R WS 2012 2021 - Ap Su>=1 4 0 - +R WS 2012 2020 - S lastSu 3 1 - +R TO 1999 o - O 7 2s 1 - +R TO 2000 o - Mar 19 2s 0 - +R TO 2000 2001 - N Su>=1 2 1 - +R TO 2001 2002 - Ja lastSu 2 0 - +R TO 2016 o - N Su>=1 2 1 - +R TO 2017 o - Ja Su>=15 3 0 - +R VU 1973 o - D 22 12u 1 - +R VU 1974 o - Mar 30 12u 0 - +R VU 1983 1991 - S Sa>=22 24 1 - +R VU 1984 1991 - Mar Sa>=22 24 0 - +R VU 1992 1993 - Ja Sa>=22 24 0 - +R VU 1992 o - O Sa>=22 24 1 - +R G 1916 o - May 21 2s 1 BST +R G 1916 o - O 1 2s 0 GMT +R G 1917 o - Ap 8 2s 1 BST +R G 1917 o - S 17 2s 0 GMT +R G 1918 o - Mar 24 2s 1 BST +R G 1918 o - S 30 2s 0 GMT +R G 1919 o - Mar 30 2s 1 BST +R G 1919 o - S 29 2s 0 GMT +R G 1920 o - Mar 28 2s 1 BST +R G 1920 o - O 25 2s 0 GMT +R G 1921 o - Ap 3 2s 1 BST +R G 1921 o - O 3 2s 0 GMT +R G 1922 o - Mar 26 2s 1 BST +R G 1922 o - O 8 2s 0 GMT +R G 1923 o - Ap Su>=16 2s 1 BST +R G 1923 1924 - S Su>=16 2s 0 GMT +R G 1924 o - Ap Su>=9 2s 1 BST +R G 1925 1926 - Ap Su>=16 2s 1 BST +R G 1925 1938 - O Su>=2 2s 0 GMT +R G 1927 o - Ap Su>=9 2s 1 BST +R G 1928 1929 - Ap Su>=16 2s 1 BST +R G 1930 o - Ap Su>=9 2s 1 BST +R G 1931 1932 - Ap Su>=16 2s 1 BST +R G 1933 o - Ap Su>=9 2s 1 BST +R G 1934 o - Ap Su>=16 2s 1 BST +R G 1935 o - Ap Su>=9 2s 1 BST +R G 1936 1937 - Ap Su>=16 2s 1 BST +R G 1938 o - Ap Su>=9 2s 1 BST +R G 1939 o - Ap Su>=16 2s 1 BST +R G 1939 o - N Su>=16 2s 0 GMT +R G 1940 o - F Su>=23 2s 1 BST +R G 1941 o - May Su>=2 1s 2 BDST +R G 1941 1943 - Au Su>=9 1s 1 BST +R G 1942 1944 - Ap Su>=2 1s 2 BDST +R G 1944 o - S Su>=16 1s 1 BST +R G 1945 o - Ap M>=2 1s 2 BDST +R G 1945 o - Jul Su>=9 1s 1 BST +R G 1945 1946 - O Su>=2 2s 0 GMT +R G 1946 o - Ap Su>=9 2s 1 BST +R G 1947 o - Mar 16 2s 1 BST +R G 1947 o - Ap 13 1s 2 BDST +R G 1947 o - Au 10 1s 1 BST +R G 1947 o - N 2 2s 0 GMT +R G 1948 o - Mar 14 2s 1 BST +R G 1948 o - O 31 2s 0 GMT +R G 1949 o - Ap 3 2s 1 BST +R G 1949 o - O 30 2s 0 GMT +R G 1950 1952 - Ap Su>=14 2s 1 BST +R G 1950 1952 - O Su>=21 2s 0 GMT +R G 1953 o - Ap Su>=16 2s 1 BST +R G 1953 1960 - O Su>=2 2s 0 GMT +R G 1954 o - Ap Su>=9 2s 1 BST +R G 1955 1956 - Ap Su>=16 2s 1 BST +R G 1957 o - Ap Su>=9 2s 1 BST +R G 1958 1959 - Ap Su>=16 2s 1 BST +R G 1960 o - Ap Su>=9 2s 1 BST +R G 1961 1963 - Mar lastSu 2s 1 BST +R G 1961 1968 - O Su>=23 2s 0 GMT +R G 1964 1967 - Mar Su>=19 2s 1 BST +R G 1968 o - F 18 2s 1 BST +R G 1972 1980 - Mar Su>=16 2s 1 BST +R G 1972 1980 - O Su>=23 2s 0 GMT +R G 1981 1995 - Mar lastSu 1u 1 BST +R G 1981 1989 - O Su>=23 1u 0 GMT +R G 1990 1995 - O Su>=22 1u 0 GMT +R IE 1971 o - O 31 2u -1 - +R IE 1972 1980 - Mar Su>=16 2u 0 - +R IE 1972 1980 - O Su>=23 2u -1 - +R IE 1981 ma - Mar lastSu 1u 0 - +R IE 1981 1989 - O Su>=23 1u -1 - +R IE 1990 1995 - O Su>=22 1u -1 - +R IE 1996 ma - O lastSu 1u -1 - +R E 1977 1980 - Ap Su>=1 1u 1 S +R E 1977 o - S lastSu 1u 0 - +R E 1978 o - O 1 1u 0 - +R E 1979 1995 - S lastSu 1u 0 - +R E 1981 ma - Mar lastSu 1u 1 S +R E 1996 ma - O lastSu 1u 0 - +R W- 1977 1980 - Ap Su>=1 1s 1 S +R W- 1977 o - S lastSu 1s 0 - +R W- 1978 o - O 1 1s 0 - +R W- 1979 1995 - S lastSu 1s 0 - +R W- 1981 ma - Mar lastSu 1s 1 S +R W- 1996 ma - O lastSu 1s 0 - +R c 1916 o - Ap 30 23 1 S +R c 1916 o - O 1 1 0 - +R c 1917 1918 - Ap M>=15 2s 1 S +R c 1917 1918 - S M>=15 2s 0 - +R c 1940 o - Ap 1 2s 1 S +R c 1942 o - N 2 2s 0 - +R c 1943 o - Mar 29 2s 1 S +R c 1943 o - O 4 2s 0 - +R c 1944 1945 - Ap M>=1 2s 1 S +R c 1944 o - O 2 2s 0 - +R c 1945 o - S 16 2s 0 - +R c 1977 1980 - Ap Su>=1 2s 1 S +R c 1977 o - S lastSu 2s 0 - +R c 1978 o - O 1 2s 0 - +R c 1979 1995 - S lastSu 2s 0 - +R c 1981 ma - Mar lastSu 2s 1 S +R c 1996 ma - O lastSu 2s 0 - +R e 1977 1980 - Ap Su>=1 0 1 S +R e 1977 o - S lastSu 0 0 - +R e 1978 o - O 1 0 0 - +R e 1979 1995 - S lastSu 0 0 - +R e 1981 ma - Mar lastSu 0 1 S +R e 1996 ma - O lastSu 0 0 - +R R 1917 o - Jul 1 23 1 MST +R R 1917 o - D 28 0 0 MMT +R R 1918 o - May 31 22 2 MDST +R R 1918 o - S 16 1 1 MST +R R 1919 o - May 31 23 2 MDST +R R 1919 o - Jul 1 0u 1 MSD +R R 1919 o - Au 16 0 0 MSK +R R 1921 o - F 14 23 1 MSD +R R 1921 o - Mar 20 23 2 +05 +R R 1921 o - S 1 0 1 MSD +R R 1921 o - O 1 0 0 - +R R 1981 1984 - Ap 1 0 1 S +R R 1981 1983 - O 1 0 0 - +R R 1984 1995 - S lastSu 2s 0 - +R R 1985 2010 - Mar lastSu 2s 1 S +R R 1996 2010 - O lastSu 2s 0 - +R q 1940 o - Jun 16 0 1 S +R q 1942 o - N 2 3 0 - +R q 1943 o - Mar 29 2 1 S +R q 1943 o - Ap 10 3 0 - +R q 1974 o - May 4 0 1 S +R q 1974 o - O 2 0 0 - +R q 1975 o - May 1 0 1 S +R q 1975 o - O 2 0 0 - +R q 1976 o - May 2 0 1 S +R q 1976 o - O 3 0 0 - +R q 1977 o - May 8 0 1 S +R q 1977 o - O 2 0 0 - +R q 1978 o - May 6 0 1 S +R q 1978 o - O 1 0 0 - +R q 1979 o - May 5 0 1 S +R q 1979 o - S 30 0 0 - +R q 1980 o - May 3 0 1 S +R q 1980 o - O 4 0 0 - +R q 1981 o - Ap 26 0 1 S +R q 1981 o - S 27 0 0 - +R q 1982 o - May 2 0 1 S +R q 1982 o - O 3 0 0 - +R q 1983 o - Ap 18 0 1 S +R q 1983 o - O 1 0 0 - +R q 1984 o - Ap 1 0 1 S +R a 1920 o - Ap 5 2s 1 S +R a 1920 o - S 13 2s 0 - +R a 1946 o - Ap 14 2s 1 S +R a 1946 o - O 7 2s 0 - +R a 1947 1948 - O Su>=1 2s 0 - +R a 1947 o - Ap 6 2s 1 S +R a 1948 o - Ap 18 2s 1 S +R a 1980 o - Ap 6 0 1 S +R a 1980 o - S 28 0 0 - +R b 1918 o - Mar 9 0s 1 S +R b 1918 1919 - O Sa>=1 23s 0 - +R b 1919 o - Mar 1 23s 1 S +R b 1920 o - F 14 23s 1 S +R b 1920 o - O 23 23s 0 - +R b 1921 o - Mar 14 23s 1 S +R b 1921 o - O 25 23s 0 - +R b 1922 o - Mar 25 23s 1 S +R b 1922 1927 - O Sa>=1 23s 0 - +R b 1923 o - Ap 21 23s 1 S +R b 1924 o - Mar 29 23s 1 S +R b 1925 o - Ap 4 23s 1 S +R b 1926 o - Ap 17 23s 1 S +R b 1927 o - Ap 9 23s 1 S +R b 1928 o - Ap 14 23s 1 S +R b 1928 1938 - O Su>=2 2s 0 - +R b 1929 o - Ap 21 2s 1 S +R b 1930 o - Ap 13 2s 1 S +R b 1931 o - Ap 19 2s 1 S +R b 1932 o - Ap 3 2s 1 S +R b 1933 o - Mar 26 2s 1 S +R b 1934 o - Ap 8 2s 1 S +R b 1935 o - Mar 31 2s 1 S +R b 1936 o - Ap 19 2s 1 S +R b 1937 o - Ap 4 2s 1 S +R b 1938 o - Mar 27 2s 1 S +R b 1939 o - Ap 16 2s 1 S +R b 1939 o - N 19 2s 0 - +R b 1940 o - F 25 2s 1 S +R b 1944 o - S 17 2s 0 - +R b 1945 o - Ap 2 2s 1 S +R b 1945 o - S 16 2s 0 - +R b 1946 o - May 19 2s 1 S +R b 1946 o - O 7 2s 0 - +R BG 1979 o - Mar 31 23 1 S +R BG 1979 o - O 1 1 0 - +R BG 1980 1982 - Ap Sa>=1 23 1 S +R BG 1980 o - S 29 1 0 - +R BG 1981 o - S 27 2 0 - +R CZ 1945 o - Ap M>=1 2s 1 S +R CZ 1945 o - O 1 2s 0 - +R CZ 1946 o - May 6 2s 1 S +R CZ 1946 1949 - O Su>=1 2s 0 - +R CZ 1947 1948 - Ap Su>=15 2s 1 S +R CZ 1949 o - Ap 9 2s 1 S +R Th 1991 1992 - Mar lastSu 2 1 D +R Th 1991 1992 - S lastSu 2 0 S +R Th 1993 2006 - Ap Su>=1 2 1 D +R Th 1993 2006 - O lastSu 2 0 S +R Th 2007 ma - Mar Su>=8 2 1 D +R Th 2007 ma - N Su>=1 2 0 S +R FI 1942 o - Ap 2 24 1 S +R FI 1942 o - O 4 1 0 - +R FI 1981 1982 - Mar lastSu 2 1 S +R FI 1981 1982 - S lastSu 3 0 - +R F 1916 o - Jun 14 23s 1 S +R F 1916 1919 - O Su>=1 23s 0 - +R F 1917 o - Mar 24 23s 1 S +R F 1918 o - Mar 9 23s 1 S +R F 1919 o - Mar 1 23s 1 S +R F 1920 o - F 14 23s 1 S +R F 1920 o - O 23 23s 0 - +R F 1921 o - Mar 14 23s 1 S +R F 1921 o - O 25 23s 0 - +R F 1922 o - Mar 25 23s 1 S +R F 1922 1938 - O Sa>=1 23s 0 - +R F 1923 o - May 26 23s 1 S +R F 1924 o - Mar 29 23s 1 S +R F 1925 o - Ap 4 23s 1 S +R F 1926 o - Ap 17 23s 1 S +R F 1927 o - Ap 9 23s 1 S +R F 1928 o - Ap 14 23s 1 S +R F 1929 o - Ap 20 23s 1 S +R F 1930 o - Ap 12 23s 1 S +R F 1931 o - Ap 18 23s 1 S +R F 1932 o - Ap 2 23s 1 S +R F 1933 o - Mar 25 23s 1 S +R F 1934 o - Ap 7 23s 1 S +R F 1935 o - Mar 30 23s 1 S +R F 1936 o - Ap 18 23s 1 S +R F 1937 o - Ap 3 23s 1 S +R F 1938 o - Mar 26 23s 1 S +R F 1939 o - Ap 15 23s 1 S +R F 1939 o - N 18 23s 0 - +R F 1940 o - F 25 2 1 S +R F 1941 o - May 5 0 2 M +R F 1941 o - O 6 0 1 S +R F 1942 o - Mar 9 0 2 M +R F 1942 o - N 2 3 1 S +R F 1943 o - Mar 29 2 2 M +R F 1943 o - O 4 3 1 S +R F 1944 o - Ap 3 2 2 M +R F 1944 o - O 8 1 1 S +R F 1945 o - Ap 2 2 2 M +R F 1945 o - S 16 3 0 - +R F 1976 o - Mar 28 1 1 S +R F 1976 o - S 26 1 0 - +R DE 1946 o - Ap 14 2s 1 S +R DE 1946 o - O 7 2s 0 - +R DE 1947 1949 - O Su>=1 2s 0 - +R DE 1947 o - Ap 6 3s 1 S +R DE 1947 o - May 11 2s 2 M +R DE 1947 o - Jun 29 3 1 S +R DE 1948 o - Ap 18 2s 1 S +R DE 1949 o - Ap 10 2s 1 S +R So 1945 o - May 24 2 2 M +R So 1945 o - S 24 3 1 S +R So 1945 o - N 18 2s 0 - +R g 1932 o - Jul 7 0 1 S +R g 1932 o - S 1 0 0 - +R g 1941 o - Ap 7 0 1 S +R g 1942 o - N 2 3 0 - +R g 1943 o - Mar 30 0 1 S +R g 1943 o - O 4 0 0 - +R g 1952 o - Jul 1 0 1 S +R g 1952 o - N 2 0 0 - +R g 1975 o - Ap 12 0s 1 S +R g 1975 o - N 26 0s 0 - +R g 1976 o - Ap 11 2s 1 S +R g 1976 o - O 10 2s 0 - +R g 1977 1978 - Ap Su>=1 2s 1 S +R g 1977 o - S 26 2s 0 - +R g 1978 o - S 24 4 0 - +R g 1979 o - Ap 1 9 1 S +R g 1979 o - S 29 2 0 - +R g 1980 o - Ap 1 0 1 S +R g 1980 o - S 28 0 0 - +R h 1918 1919 - Ap 15 2 1 S +R h 1918 1920 - S M>=15 3 0 - +R h 1920 o - Ap 5 2 1 S +R h 1945 o - May 1 23 1 S +R h 1945 o - N 1 1 0 - +R h 1946 o - Mar 31 2s 1 S +R h 1946 o - O 7 2 0 - +R h 1947 1949 - Ap Su>=4 2s 1 S +R h 1947 1949 - O Su>=1 2s 0 - +R h 1954 o - May 23 0 1 S +R h 1954 o - O 3 0 0 - +R h 1955 o - May 22 2 1 S +R h 1955 o - O 2 3 0 - +R h 1956 1957 - Jun Su>=1 2 1 S +R h 1956 1957 - S lastSu 3 0 - +R h 1980 o - Ap 6 0 1 S +R h 1980 o - S 28 1 0 - +R h 1981 1983 - Mar lastSu 0 1 S +R h 1981 1983 - S lastSu 1 0 - +R I 1916 o - Jun 3 24 1 S +R I 1916 1917 - S 30 24 0 - +R I 1917 o - Mar 31 24 1 S +R I 1918 o - Mar 9 24 1 S +R I 1918 o - O 6 24 0 - +R I 1919 o - Mar 1 24 1 S +R I 1919 o - O 4 24 0 - +R I 1920 o - Mar 20 24 1 S +R I 1920 o - S 18 24 0 - +R I 1940 o - Jun 14 24 1 S +R I 1942 o - N 2 2s 0 - +R I 1943 o - Mar 29 2s 1 S +R I 1943 o - O 4 2s 0 - +R I 1944 o - Ap 2 2s 1 S +R I 1944 o - S 17 2s 0 - +R I 1945 o - Ap 2 2 1 S +R I 1945 o - S 15 1 0 - +R I 1946 o - Mar 17 2s 1 S +R I 1946 o - O 6 2s 0 - +R I 1947 o - Mar 16 0s 1 S +R I 1947 o - O 5 0s 0 - +R I 1948 o - F 29 2s 1 S +R I 1948 o - O 3 2s 0 - +R I 1966 1968 - May Su>=22 0s 1 S +R I 1966 o - S 24 24 0 - +R I 1967 1969 - S Su>=22 0s 0 - +R I 1969 o - Jun 1 0s 1 S +R I 1970 o - May 31 0s 1 S +R I 1970 o - S lastSu 0s 0 - +R I 1971 1972 - May Su>=22 0s 1 S +R I 1971 o - S lastSu 0s 0 - +R I 1972 o - O 1 0s 0 - +R I 1973 o - Jun 3 0s 1 S +R I 1973 1974 - S lastSu 0s 0 - +R I 1974 o - May 26 0s 1 S +R I 1975 o - Jun 1 0s 1 S +R I 1975 1977 - S lastSu 0s 0 - +R I 1976 o - May 30 0s 1 S +R I 1977 1979 - May Su>=22 0s 1 S +R I 1978 o - O 1 0s 0 - +R I 1979 o - S 30 0s 0 - +R LV 1989 1996 - Mar lastSu 2s 1 S +R LV 1989 1996 - S lastSu 2s 0 - +R MT 1973 o - Mar 31 0s 1 S +R MT 1973 o - S 29 0s 0 - +R MT 1974 o - Ap 21 0s 1 S +R MT 1974 o - S 16 0s 0 - +R MT 1975 1979 - Ap Su>=15 2 1 S +R MT 1975 1980 - S Su>=15 2 0 - +R MT 1980 o - Mar 31 2 1 S +R MD 1997 ma - Mar lastSu 2 1 S +R MD 1997 ma - O lastSu 3 0 - +R O 1918 1919 - S 16 2s 0 - +R O 1919 o - Ap 15 2s 1 S +R O 1944 o - Ap 3 2s 1 S +R O 1944 o - O 4 2 0 - +R O 1945 o - Ap 29 0 1 S +R O 1945 o - N 1 0 0 - +R O 1946 o - Ap 14 0s 1 S +R O 1946 o - O 7 2s 0 - +R O 1947 o - May 4 2s 1 S +R O 1947 1949 - O Su>=1 2s 0 - +R O 1948 o - Ap 18 2s 1 S +R O 1949 o - Ap 10 2s 1 S +R O 1957 o - Jun 2 1s 1 S +R O 1957 1958 - S lastSu 1s 0 - +R O 1958 o - Mar 30 1s 1 S +R O 1959 o - May 31 1s 1 S +R O 1959 1961 - O Su>=1 1s 0 - +R O 1960 o - Ap 3 1s 1 S +R O 1961 1964 - May lastSu 1s 1 S +R O 1962 1964 - S lastSu 1s 0 - +R p 1916 o - Jun 17 23 1 S +R p 1916 o - N 1 1 0 - +R p 1917 1921 - Mar 1 0 1 S +R p 1917 1921 - O 14 24 0 - +R p 1924 o - Ap 16 23s 1 S +R p 1924 o - O 4 23s 0 - +R p 1926 o - Ap 17 23s 1 S +R p 1926 1929 - O Sa>=1 23s 0 - +R p 1927 o - Ap 9 23s 1 S +R p 1928 o - Ap 14 23s 1 S +R p 1929 o - Ap 20 23s 1 S +R p 1931 o - Ap 18 23s 1 S +R p 1931 1932 - O Sa>=1 23s 0 - +R p 1932 o - Ap 2 23s 1 S +R p 1934 o - Ap 7 23s 1 S +R p 1934 1938 - O Sa>=1 23s 0 - +R p 1935 o - Mar 30 23s 1 S +R p 1936 o - Ap 18 23s 1 S +R p 1937 o - Ap 3 23s 1 S +R p 1938 o - Mar 26 23s 1 S +R p 1939 o - Ap 15 23s 1 S +R p 1939 o - N 18 23s 0 - +R p 1940 o - F 24 23s 1 S +R p 1940 o - O 7 23s 0 - +R p 1941 o - Ap 5 23s 1 S +R p 1941 o - O 5 23s 0 - +R p 1942 1945 - Mar Sa>=8 23s 1 S +R p 1942 o - Ap 25 22s 2 M +R p 1942 o - Au 15 22s 1 S +R p 1942 1945 - O Sa>=24 23s 0 - +R p 1943 o - Ap 17 22s 2 M +R p 1943 1945 - Au Sa>=25 22s 1 S +R p 1944 1945 - Ap Sa>=21 22s 2 M +R p 1946 o - Ap Sa>=1 23s 1 S +R p 1946 o - O Sa>=1 23s 0 - +R p 1947 1966 - Ap Su>=1 2s 1 S +R p 1947 1965 - O Su>=1 2s 0 - +R p 1976 o - S lastSu 1 0 - +R p 1977 o - Mar lastSu 0s 1 S +R p 1977 o - S lastSu 0s 0 - +R p 1978 1980 - Ap Su>=1 1s 1 S +R p 1978 o - O 1 1s 0 - +R p 1979 1980 - S lastSu 1s 0 - +R p 1981 1986 - Mar lastSu 0s 1 S +R p 1981 1985 - S lastSu 0s 0 - +R z 1932 o - May 21 0s 1 S +R z 1932 1939 - O Su>=1 0s 0 - +R z 1933 1939 - Ap Su>=2 0s 1 S +R z 1979 o - May 27 0 1 S +R z 1979 o - S lastSu 0 0 - +R z 1980 o - Ap 5 23 1 S +R z 1980 o - S lastSu 1 0 - +R z 1991 1993 - Mar lastSu 0s 1 S +R z 1991 1993 - S lastSu 0s 0 - +R s 1918 o - Ap 15 23 1 S +R s 1918 1919 - O 6 24s 0 - +R s 1919 o - Ap 6 23 1 S +R s 1924 o - Ap 16 23 1 S +R s 1924 o - O 4 24s 0 - +R s 1926 o - Ap 17 23 1 S +R s 1926 1929 - O Sa>=1 24s 0 - +R s 1927 o - Ap 9 23 1 S +R s 1928 o - Ap 15 0 1 S +R s 1929 o - Ap 20 23 1 S +R s 1937 o - Jun 16 23 1 S +R s 1937 o - O 2 24s 0 - +R s 1938 o - Ap 2 23 1 S +R s 1938 o - Ap 30 23 2 M +R s 1938 o - O 2 24 1 S +R s 1939 o - O 7 24s 0 - +R s 1942 o - May 2 23 1 S +R s 1942 o - S 1 1 0 - +R s 1943 1946 - Ap Sa>=13 23 1 S +R s 1943 1944 - O Su>=1 1 0 - +R s 1945 1946 - S lastSu 1 0 - +R s 1949 o - Ap 30 23 1 S +R s 1949 o - O 2 1 0 - +R s 1974 1975 - Ap Sa>=12 23 1 S +R s 1974 1975 - O Su>=1 1 0 - +R s 1976 o - Mar 27 23 1 S +R s 1976 1977 - S lastSu 1 0 - +R s 1977 o - Ap 2 23 1 S +R s 1978 o - Ap 2 2s 1 S +R s 1978 o - O 1 2s 0 - +R Sp 1967 o - Jun 3 12 1 S +R Sp 1967 o - O 1 0 0 - +R Sp 1974 o - Jun 24 0 1 S +R Sp 1974 o - S 1 0 0 - +R Sp 1976 1977 - May 1 0 1 S +R Sp 1976 o - Au 1 0 0 - +R Sp 1977 o - S 28 0 0 - +R Sp 1978 o - Jun 1 0 1 S +R Sp 1978 o - Au 4 0 0 - +R CH 1941 1942 - May M>=1 1 1 S +R CH 1941 1942 - O M>=1 2 0 - +R T 1916 o - May 1 0 1 S +R T 1916 o - O 1 0 0 - +R T 1920 o - Mar 28 0 1 S +R T 1920 o - O 25 0 0 - +R T 1921 o - Ap 3 0 1 S +R T 1921 o - O 3 0 0 - +R T 1922 o - Mar 26 0 1 S +R T 1922 o - O 8 0 0 - +R T 1924 o - May 13 0 1 S +R T 1924 1925 - O 1 0 0 - +R T 1925 o - May 1 0 1 S +R T 1940 o - Jul 1 0 1 S +R T 1940 o - O 6 0 0 - +R T 1940 o - D 1 0 1 S +R T 1941 o - S 21 0 0 - +R T 1942 o - Ap 1 0 1 S +R T 1945 o - O 8 0 0 - +R T 1946 o - Jun 1 0 1 S +R T 1946 o - O 1 0 0 - +R T 1947 1948 - Ap Su>=16 0 1 S +R T 1947 1951 - O Su>=2 0 0 - +R T 1949 o - Ap 10 0 1 S +R T 1950 o - Ap 16 0 1 S +R T 1951 o - Ap 22 0 1 S +R T 1962 o - Jul 15 0 1 S +R T 1963 o - O 30 0 0 - +R T 1964 o - May 15 0 1 S +R T 1964 o - O 1 0 0 - +R T 1973 o - Jun 3 1 1 S +R T 1973 1976 - O Su>=31 2 0 - +R T 1974 o - Mar 31 2 1 S +R T 1975 o - Mar 22 2 1 S +R T 1976 o - Mar 21 2 1 S +R T 1977 1978 - Ap Su>=1 2 1 S +R T 1977 1978 - O Su>=15 2 0 - +R T 1978 o - Jun 29 0 0 - +R T 1983 o - Jul 31 2 1 S +R T 1983 o - O 2 2 0 - +R T 1985 o - Ap 20 1s 1 S +R T 1985 o - S 28 1s 0 - +R T 1986 1993 - Mar lastSu 1s 1 S +R T 1986 1995 - S lastSu 1s 0 - +R T 1994 o - Mar 20 1s 1 S +R T 1995 2006 - Mar lastSu 1s 1 S +R T 1996 2006 - O lastSu 1s 0 - +R u 1918 1919 - Mar lastSu 2 1 D +R u 1918 1919 - O lastSu 2 0 S +R u 1942 o - F 9 2 1 W +R u 1945 o - Au 14 23u 1 P +R u 1945 o - S 30 2 0 S +R u 1967 2006 - O lastSu 2 0 S +R u 1967 1973 - Ap lastSu 2 1 D +R u 1974 o - Ja 6 2 1 D +R u 1975 o - F lastSu 2 1 D +R u 1976 1986 - Ap lastSu 2 1 D +R u 1987 2006 - Ap Su>=1 2 1 D +R u 2007 ma - Mar Su>=8 2 1 D +R u 2007 ma - N Su>=1 2 0 S +R NY 1920 o - Mar lastSu 2 1 D +R NY 1920 o - O lastSu 2 0 S +R NY 1921 1966 - Ap lastSu 2 1 D +R NY 1921 1954 - S lastSu 2 0 S +R NY 1955 1966 - O lastSu 2 0 S +R Ch 1920 o - Jun 13 2 1 D +R Ch 1920 1921 - O lastSu 2 0 S +R Ch 1921 o - Mar lastSu 2 1 D +R Ch 1922 1966 - Ap lastSu 2 1 D +R Ch 1922 1954 - S lastSu 2 0 S +R Ch 1955 1966 - O lastSu 2 0 S +R De 1920 1921 - Mar lastSu 2 1 D +R De 1920 o - O lastSu 2 0 S +R De 1921 o - May 22 2 0 S +R De 1965 1966 - Ap lastSu 2 1 D +R De 1965 1966 - O lastSu 2 0 S +R CA 1948 o - Mar 14 2:1 1 D +R CA 1949 o - Ja 1 2 0 S +R CA 1950 1966 - Ap lastSu 1 1 D +R CA 1950 1961 - S lastSu 2 0 S +R CA 1962 1966 - O lastSu 2 0 S +R In 1941 o - Jun 22 2 1 D +R In 1941 1954 - S lastSu 2 0 S +R In 1946 1954 - Ap lastSu 2 1 D +R Ma 1951 o - Ap lastSu 2 1 D +R Ma 1951 o - S lastSu 2 0 S +R Ma 1954 1960 - Ap lastSu 2 1 D +R Ma 1954 1960 - S lastSu 2 0 S +R V 1946 o - Ap lastSu 2 1 D +R V 1946 o - S lastSu 2 0 S +R V 1953 1954 - Ap lastSu 2 1 D +R V 1953 1959 - S lastSu 2 0 S +R V 1955 o - May 1 0 1 D +R V 1956 1963 - Ap lastSu 2 1 D +R V 1960 o - O lastSu 2 0 S +R V 1961 o - S lastSu 2 0 S +R V 1962 1963 - O lastSu 2 0 S +R Pe 1955 o - May 1 0 1 D +R Pe 1955 1960 - S lastSu 2 0 S +R Pe 1956 1963 - Ap lastSu 2 1 D +R Pe 1961 1963 - O lastSu 2 0 S +R Pi 1955 o - May 1 0 1 D +R Pi 1955 1960 - S lastSu 2 0 S +R Pi 1956 1964 - Ap lastSu 2 1 D +R Pi 1961 1964 - O lastSu 2 0 S +R St 1947 1961 - Ap lastSu 2 1 D +R St 1947 1954 - S lastSu 2 0 S +R St 1955 1956 - O lastSu 2 0 S +R St 1957 1958 - S lastSu 2 0 S +R St 1959 1961 - O lastSu 2 0 S +R Pu 1946 1960 - Ap lastSu 2 1 D +R Pu 1946 1954 - S lastSu 2 0 S +R Pu 1955 1956 - O lastSu 2 0 S +R Pu 1957 1960 - S lastSu 2 0 S +R v 1921 o - May 1 2 1 D +R v 1921 o - S 1 2 0 S +R v 1941 o - Ap lastSu 2 1 D +R v 1941 o - S lastSu 2 0 S +R v 1946 o - Ap lastSu 0:1 1 D +R v 1946 o - Jun 2 2 0 S +R v 1950 1961 - Ap lastSu 2 1 D +R v 1950 1955 - S lastSu 2 0 S +R v 1956 1961 - O lastSu 2 0 S +R Dt 1948 o - Ap lastSu 2 1 D +R Dt 1948 o - S lastSu 2 0 S +R Me 1946 o - Ap lastSu 2 1 D +R Me 1946 o - S lastSu 2 0 S +R Me 1966 o - Ap lastSu 2 1 D +R Me 1966 o - O lastSu 2 0 S +R C 1918 o - Ap 14 2 1 D +R C 1918 o - O 27 2 0 S +R C 1942 o - F 9 2 1 W +R C 1945 o - Au 14 23u 1 P +R C 1945 o - S 30 2 0 S +R C 1974 1986 - Ap lastSu 2 1 D +R C 1974 2006 - O lastSu 2 0 S +R C 1987 2006 - Ap Su>=1 2 1 D +R C 2007 ma - Mar Su>=8 2 1 D +R C 2007 ma - N Su>=1 2 0 S +R j 1917 o - Ap 8 2 1 D +R j 1917 o - S 17 2 0 S +R j 1919 o - May 5 23 1 D +R j 1919 o - Au 12 23 0 S +R j 1920 1935 - May Su>=1 23 1 D +R j 1920 1935 - O lastSu 23 0 S +R j 1936 1941 - May M>=9 0 1 D +R j 1936 1941 - O M>=2 0 0 S +R j 1946 1950 - May Su>=8 2 1 D +R j 1946 1950 - O Su>=2 2 0 S +R j 1951 1986 - Ap lastSu 2 1 D +R j 1951 1959 - S lastSu 2 0 S +R j 1960 1986 - O lastSu 2 0 S +R j 1987 o - Ap Su>=1 0:1 1 D +R j 1987 2006 - O lastSu 0:1 0 S +R j 1988 o - Ap Su>=1 0:1 2 DD +R j 1989 2006 - Ap Su>=1 0:1 1 D +R j 2007 2011 - Mar Su>=8 0:1 1 D +R j 2007 2010 - N Su>=1 0:1 0 S +R H 1916 o - Ap 1 0 1 D +R H 1916 o - O 1 0 0 S +R H 1920 o - May 9 0 1 D +R H 1920 o - Au 29 0 0 S +R H 1921 o - May 6 0 1 D +R H 1921 1922 - S 5 0 0 S +R H 1922 o - Ap 30 0 1 D +R H 1923 1925 - May Su>=1 0 1 D +R H 1923 o - S 4 0 0 S +R H 1924 o - S 15 0 0 S +R H 1925 o - S 28 0 0 S +R H 1926 o - May 16 0 1 D +R H 1926 o - S 13 0 0 S +R H 1927 o - May 1 0 1 D +R H 1927 o - S 26 0 0 S +R H 1928 1931 - May Su>=8 0 1 D +R H 1928 o - S 9 0 0 S +R H 1929 o - S 3 0 0 S +R H 1930 o - S 15 0 0 S +R H 1931 1932 - S M>=24 0 0 S +R H 1932 o - May 1 0 1 D +R H 1933 o - Ap 30 0 1 D +R H 1933 o - O 2 0 0 S +R H 1934 o - May 20 0 1 D +R H 1934 o - S 16 0 0 S +R H 1935 o - Jun 2 0 1 D +R H 1935 o - S 30 0 0 S +R H 1936 o - Jun 1 0 1 D +R H 1936 o - S 14 0 0 S +R H 1937 1938 - May Su>=1 0 1 D +R H 1937 1941 - S M>=24 0 0 S +R H 1939 o - May 28 0 1 D +R H 1940 1941 - May Su>=1 0 1 D +R H 1946 1949 - Ap lastSu 2 1 D +R H 1946 1949 - S lastSu 2 0 S +R H 1951 1954 - Ap lastSu 2 1 D +R H 1951 1954 - S lastSu 2 0 S +R H 1956 1959 - Ap lastSu 2 1 D +R H 1956 1959 - S lastSu 2 0 S +R H 1962 1973 - Ap lastSu 2 1 D +R H 1962 1973 - O lastSu 2 0 S +R o 1933 1935 - Jun Su>=8 1 1 D +R o 1933 1935 - S Su>=8 1 0 S +R o 1936 1938 - Jun Su>=1 1 1 D +R o 1936 1938 - S Su>=1 1 0 S +R o 1939 o - May 27 1 1 D +R o 1939 1941 - S Sa>=21 1 0 S +R o 1940 o - May 19 1 1 D +R o 1941 o - May 4 1 1 D +R o 1946 1972 - Ap lastSu 2 1 D +R o 1946 1956 - S lastSu 2 0 S +R o 1957 1972 - O lastSu 2 0 S +R o 1993 2006 - Ap Su>=1 0:1 1 D +R o 1993 2006 - O lastSu 0:1 0 S +R t 1919 o - Mar 30 23:30 1 D +R t 1919 o - O 26 0 0 S +R t 1920 o - May 2 2 1 D +R t 1920 o - S 26 0 0 S +R t 1921 o - May 15 2 1 D +R t 1921 o - S 15 2 0 S +R t 1922 1923 - May Su>=8 2 1 D +R t 1922 1926 - S Su>=15 2 0 S +R t 1924 1927 - May Su>=1 2 1 D +R t 1927 1937 - S Su>=25 2 0 S +R t 1928 1937 - Ap Su>=25 2 1 D +R t 1938 1940 - Ap lastSu 2 1 D +R t 1938 1939 - S lastSu 2 0 S +R t 1945 1948 - S lastSu 2 0 S +R t 1946 1973 - Ap lastSu 2 1 D +R t 1949 1950 - N lastSu 2 0 S +R t 1951 1956 - S lastSu 2 0 S +R t 1957 1973 - O lastSu 2 0 S +R W 1916 o - Ap 23 0 1 D +R W 1916 o - S 17 0 0 S +R W 1918 o - Ap 14 2 1 D +R W 1918 o - O 27 2 0 S +R W 1937 o - May 16 2 1 D +R W 1937 o - S 26 2 0 S +R W 1942 o - F 9 2 1 W +R W 1945 o - Au 14 23u 1 P +R W 1945 o - S lastSu 2 0 S +R W 1946 o - May 12 2 1 D +R W 1946 o - O 13 2 0 S +R W 1947 1949 - Ap lastSu 2 1 D +R W 1947 1949 - S lastSu 2 0 S +R W 1950 o - May 1 2 1 D +R W 1950 o - S 30 2 0 S +R W 1951 1960 - Ap lastSu 2 1 D +R W 1951 1958 - S lastSu 2 0 S +R W 1959 o - O lastSu 2 0 S +R W 1960 o - S lastSu 2 0 S +R W 1963 o - Ap lastSu 2 1 D +R W 1963 o - S 22 2 0 S +R W 1966 1986 - Ap lastSu 2s 1 D +R W 1966 2005 - O lastSu 2s 0 S +R W 1987 2005 - Ap Su>=1 2s 1 D +R r 1918 o - Ap 14 2 1 D +R r 1918 o - O 27 2 0 S +R r 1930 1934 - May Su>=1 0 1 D +R r 1930 1934 - O Su>=1 0 0 S +R r 1937 1941 - Ap Su>=8 0 1 D +R r 1937 o - O Su>=8 0 0 S +R r 1938 o - O Su>=1 0 0 S +R r 1939 1941 - O Su>=8 0 0 S +R r 1942 o - F 9 2 1 W +R r 1945 o - Au 14 23u 1 P +R r 1945 o - S lastSu 2 0 S +R r 1946 o - Ap Su>=8 2 1 D +R r 1946 o - O Su>=8 2 0 S +R r 1947 1957 - Ap lastSu 2 1 D +R r 1947 1957 - S lastSu 2 0 S +R r 1959 o - Ap lastSu 2 1 D +R r 1959 o - O lastSu 2 0 S +R Sw 1957 o - Ap lastSu 2 1 D +R Sw 1957 o - O lastSu 2 0 S +R Sw 1959 1961 - Ap lastSu 2 1 D +R Sw 1959 o - O lastSu 2 0 S +R Sw 1960 1961 - S lastSu 2 0 S +R Ed 1918 1919 - Ap Su>=8 2 1 D +R Ed 1918 o - O 27 2 0 S +R Ed 1919 o - May 27 2 0 S +R Ed 1920 1923 - Ap lastSu 2 1 D +R Ed 1920 o - O lastSu 2 0 S +R Ed 1921 1923 - S lastSu 2 0 S +R Ed 1942 o - F 9 2 1 W +R Ed 1945 o - Au 14 23u 1 P +R Ed 1945 o - S lastSu 2 0 S +R Ed 1947 o - Ap lastSu 2 1 D +R Ed 1947 o - S lastSu 2 0 S +R Ed 1972 1986 - Ap lastSu 2 1 D +R Ed 1972 2006 - O lastSu 2 0 S +R Va 1918 o - Ap 14 2 1 D +R Va 1918 o - O 27 2 0 S +R Va 1942 o - F 9 2 1 W +R Va 1945 o - Au 14 23u 1 P +R Va 1945 o - S 30 2 0 S +R Va 1946 1986 - Ap lastSu 2 1 D +R Va 1946 o - S 29 2 0 S +R Va 1947 1961 - S lastSu 2 0 S +R Va 1962 2006 - O lastSu 2 0 S +R Y 1918 o - Ap 14 2 1 D +R Y 1918 o - O 27 2 0 S +R Y 1919 o - May 25 2 1 D +R Y 1919 o - N 1 0 0 S +R Y 1942 o - F 9 2 1 W +R Y 1945 o - Au 14 23u 1 P +R Y 1945 o - S 30 2 0 S +R Y 1972 1986 - Ap lastSu 2 1 D +R Y 1972 2006 - O lastSu 2 0 S +R Y 1987 2006 - Ap Su>=1 2 1 D +R Yu 1965 o - Ap lastSu 0 2 DD +R Yu 1965 o - O lastSu 2 0 S +R m 1931 o - Ap 30 0 1 D +R m 1931 o - O 1 0 0 S +R m 1939 o - F 5 0 1 D +R m 1939 o - Jun 25 0 0 S +R m 1940 o - D 9 0 1 D +R m 1941 o - Ap 1 0 0 S +R m 1943 o - D 16 0 1 W +R m 1944 o - May 1 0 0 S +R m 1950 o - F 12 0 1 D +R m 1950 o - Jul 30 0 0 S +R m 1996 2000 - Ap Su>=1 2 1 D +R m 1996 2000 - O lastSu 2 0 S +R m 2001 o - May Su>=1 2 1 D +R m 2001 o - S lastSu 2 0 S +R m 2002 2022 - Ap Su>=1 2 1 D +R m 2002 2022 - O lastSu 2 0 S +R BB 1942 o - Ap 19 5u 1 D +R BB 1942 o - Au 31 6u 0 S +R BB 1943 o - May 2 5u 1 D +R BB 1943 o - S 5 6u 0 S +R BB 1944 o - Ap 10 5u 0:30 - +R BB 1944 o - S 10 6u 0 S +R BB 1977 o - Jun 12 2 1 D +R BB 1977 1978 - O Su>=1 2 0 S +R BB 1978 1980 - Ap Su>=15 2 1 D +R BB 1979 o - S 30 2 0 S +R BB 1980 o - S 25 2 0 S +R BZ 1918 1941 - O Sa>=1 24 0:30 -0530 +R BZ 1919 1942 - F Sa>=8 24 0 CST +R BZ 1942 o - Jun 27 24 1 CWT +R BZ 1945 o - Au 14 23u 1 CPT +R BZ 1945 o - D 15 24 0 CST +R BZ 1947 1967 - O Sa>=1 24 0:30 -0530 +R BZ 1948 1968 - F Sa>=8 24 0 CST +R BZ 1973 o - D 5 0 1 CDT +R BZ 1974 o - F 9 0 0 CST +R BZ 1982 o - D 18 0 1 CDT +R BZ 1983 o - F 12 0 0 CST +R Be 1917 o - Ap 5 24 1 - +R Be 1917 o - S 30 24 0 - +R Be 1918 o - Ap 13 24 1 - +R Be 1918 o - S 15 24 0 S +R Be 1942 o - Ja 11 2 1 D +R Be 1942 o - O 18 2 0 S +R Be 1943 o - Mar 21 2 1 D +R Be 1943 o - O 31 2 0 S +R Be 1944 1945 - Mar Su>=8 2 1 D +R Be 1944 1945 - N Su>=1 2 0 S +R Be 1947 o - May Su>=15 2 1 D +R Be 1947 o - S Su>=8 2 0 S +R Be 1948 1952 - May Su>=22 2 1 D +R Be 1948 1952 - S Su>=1 2 0 S +R Be 1956 o - May Su>=22 2 1 D +R Be 1956 o - O lastSu 2 0 S +R CR 1979 1980 - F lastSu 0 1 D +R CR 1979 1980 - Jun Su>=1 0 0 S +R CR 1991 1992 - Ja Sa>=15 0 1 D +R CR 1991 o - Jul 1 0 0 S +R CR 1992 o - Mar 15 0 0 S +R Q 1928 o - Jun 10 0 1 D +R Q 1928 o - O 10 0 0 S +R Q 1940 1942 - Jun Su>=1 0 1 D +R Q 1940 1942 - S Su>=1 0 0 S +R Q 1945 1946 - Jun Su>=1 0 1 D +R Q 1945 1946 - S Su>=1 0 0 S +R Q 1965 o - Jun 1 0 1 D +R Q 1965 o - S 30 0 0 S +R Q 1966 o - May 29 0 1 D +R Q 1966 o - O 2 0 0 S +R Q 1967 o - Ap 8 0 1 D +R Q 1967 1968 - S Su>=8 0 0 S +R Q 1968 o - Ap 14 0 1 D +R Q 1969 1977 - Ap lastSu 0 1 D +R Q 1969 1971 - O lastSu 0 0 S +R Q 1972 1974 - O 8 0 0 S +R Q 1975 1977 - O lastSu 0 0 S +R Q 1978 o - May 7 0 1 D +R Q 1978 1990 - O Su>=8 0 0 S +R Q 1979 1980 - Mar Su>=15 0 1 D +R Q 1981 1985 - May Su>=5 0 1 D +R Q 1986 1989 - Mar Su>=14 0 1 D +R Q 1990 1997 - Ap Su>=1 0 1 D +R Q 1991 1995 - O Su>=8 0s 0 S +R Q 1996 o - O 6 0s 0 S +R Q 1997 o - O 12 0s 0 S +R Q 1998 1999 - Mar lastSu 0s 1 D +R Q 1998 2003 - O lastSu 0s 0 S +R Q 2000 2003 - Ap Su>=1 0s 1 D +R Q 2004 o - Mar lastSu 0s 1 D +R Q 2006 2010 - O lastSu 0s 0 S +R Q 2007 o - Mar Su>=8 0s 1 D +R Q 2008 o - Mar Su>=15 0s 1 D +R Q 2009 2010 - Mar Su>=8 0s 1 D +R Q 2011 o - Mar Su>=15 0s 1 D +R Q 2011 o - N 13 0s 0 S +R Q 2012 o - Ap 1 0s 1 D +R Q 2012 ma - N Su>=1 0s 0 S +R Q 2013 ma - Mar Su>=8 0s 1 D +R DO 1966 o - O 30 0 1 EDT +R DO 1967 o - F 28 0 0 EST +R DO 1969 1973 - O lastSu 0 0:30 -0430 +R DO 1970 o - F 21 0 0 EST +R DO 1971 o - Ja 20 0 0 EST +R DO 1972 1974 - Ja 21 0 0 EST +R SV 1987 1988 - May Su>=1 0 1 D +R SV 1987 1988 - S lastSu 0 0 S +R GT 1973 o - N 25 0 1 D +R GT 1974 o - F 24 0 0 S +R GT 1983 o - May 21 0 1 D +R GT 1983 o - S 22 0 0 S +R GT 1991 o - Mar 23 0 1 D +R GT 1991 o - S 7 0 0 S +R GT 2006 o - Ap 30 0 1 D +R GT 2006 o - O 1 0 0 S +R HT 1983 o - May 8 0 1 D +R HT 1984 1987 - Ap lastSu 0 1 D +R HT 1983 1987 - O lastSu 0 0 S +R HT 1988 1997 - Ap Su>=1 1s 1 D +R HT 1988 1997 - O lastSu 1s 0 S +R HT 2005 2006 - Ap Su>=1 0 1 D +R HT 2005 2006 - O lastSu 0 0 S +R HT 2012 2015 - Mar Su>=8 2 1 D +R HT 2012 2015 - N Su>=1 2 0 S +R HT 2017 ma - Mar Su>=8 2 1 D +R HT 2017 ma - N Su>=1 2 0 S +R HN 1987 1988 - May Su>=1 0 1 D +R HN 1987 1988 - S lastSu 0 0 S +R HN 2006 o - May Su>=1 0 1 D +R HN 2006 o - Au M>=1 0 0 S +R NI 1979 1980 - Mar Su>=16 0 1 D +R NI 1979 1980 - Jun M>=23 0 0 S +R NI 2005 o - Ap 10 0 1 D +R NI 2005 o - O Su>=1 0 0 S +R NI 2006 o - Ap 30 2 1 D +R NI 2006 o - O Su>=1 1 0 S +R A 1930 o - D 1 0 1 - +R A 1931 o - Ap 1 0 0 - +R A 1931 o - O 15 0 1 - +R A 1932 1940 - Mar 1 0 0 - +R A 1932 1939 - N 1 0 1 - +R A 1940 o - Jul 1 0 1 - +R A 1941 o - Jun 15 0 0 - +R A 1941 o - O 15 0 1 - +R A 1943 o - Au 1 0 0 - +R A 1943 o - O 15 0 1 - +R A 1946 o - Mar 1 0 0 - +R A 1946 o - O 1 0 1 - +R A 1963 o - O 1 0 0 - +R A 1963 o - D 15 0 1 - +R A 1964 1966 - Mar 1 0 0 - +R A 1964 1966 - O 15 0 1 - +R A 1967 o - Ap 2 0 0 - +R A 1967 1968 - O Su>=1 0 1 - +R A 1968 1969 - Ap Su>=1 0 0 - +R A 1974 o - Ja 23 0 1 - +R A 1974 o - May 1 0 0 - +R A 1988 o - D 1 0 1 - +R A 1989 1993 - Mar Su>=1 0 0 - +R A 1989 1992 - O Su>=15 0 1 - +R A 1999 o - O Su>=1 0 1 - +R A 2000 o - Mar 3 0 0 - +R A 2007 o - D 30 0 1 - +R A 2008 2009 - Mar Su>=15 0 0 - +R A 2008 o - O Su>=15 0 1 - +R Sa 2008 2009 - Mar Su>=8 0 0 - +R Sa 2007 2008 - O Su>=8 0 1 - +R B 1931 o - O 3 11 1 - +R B 1932 1933 - Ap 1 0 0 - +R B 1932 o - O 3 0 1 - +R B 1949 1952 - D 1 0 1 - +R B 1950 o - Ap 16 1 0 - +R B 1951 1952 - Ap 1 0 0 - +R B 1953 o - Mar 1 0 0 - +R B 1963 o - D 9 0 1 - +R B 1964 o - Mar 1 0 0 - +R B 1965 o - Ja 31 0 1 - +R B 1965 o - Mar 31 0 0 - +R B 1965 o - D 1 0 1 - +R B 1966 1968 - Mar 1 0 0 - +R B 1966 1967 - N 1 0 1 - +R B 1985 o - N 2 0 1 - +R B 1986 o - Mar 15 0 0 - +R B 1986 o - O 25 0 1 - +R B 1987 o - F 14 0 0 - +R B 1987 o - O 25 0 1 - +R B 1988 o - F 7 0 0 - +R B 1988 o - O 16 0 1 - +R B 1989 o - Ja 29 0 0 - +R B 1989 o - O 15 0 1 - +R B 1990 o - F 11 0 0 - +R B 1990 o - O 21 0 1 - +R B 1991 o - F 17 0 0 - +R B 1991 o - O 20 0 1 - +R B 1992 o - F 9 0 0 - +R B 1992 o - O 25 0 1 - +R B 1993 o - Ja 31 0 0 - +R B 1993 1995 - O Su>=11 0 1 - +R B 1994 1995 - F Su>=15 0 0 - +R B 1996 o - F 11 0 0 - +R B 1996 o - O 6 0 1 - +R B 1997 o - F 16 0 0 - +R B 1997 o - O 6 0 1 - +R B 1998 o - Mar 1 0 0 - +R B 1998 o - O 11 0 1 - +R B 1999 o - F 21 0 0 - +R B 1999 o - O 3 0 1 - +R B 2000 o - F 27 0 0 - +R B 2000 2001 - O Su>=8 0 1 - +R B 2001 2006 - F Su>=15 0 0 - +R B 2002 o - N 3 0 1 - +R B 2003 o - O 19 0 1 - +R B 2004 o - N 2 0 1 - +R B 2005 o - O 16 0 1 - +R B 2006 o - N 5 0 1 - +R B 2007 o - F 25 0 0 - +R B 2007 o - O Su>=8 0 1 - +R B 2008 2017 - O Su>=15 0 1 - +R B 2008 2011 - F Su>=15 0 0 - +R B 2012 o - F Su>=22 0 0 - +R B 2013 2014 - F Su>=15 0 0 - +R B 2015 o - F Su>=22 0 0 - +R B 2016 2019 - F Su>=15 0 0 - +R B 2018 o - N Su>=1 0 1 - +R x 1927 1931 - S 1 0 1 - +R x 1928 1932 - Ap 1 0 0 - +R x 1968 o - N 3 4u 1 - +R x 1969 o - Mar 30 3u 0 - +R x 1969 o - N 23 4u 1 - +R x 1970 o - Mar 29 3u 0 - +R x 1971 o - Mar 14 3u 0 - +R x 1970 1972 - O Su>=9 4u 1 - +R x 1972 1986 - Mar Su>=9 3u 0 - +R x 1973 o - S 30 4u 1 - +R x 1974 1987 - O Su>=9 4u 1 - +R x 1987 o - Ap 12 3u 0 - +R x 1988 1990 - Mar Su>=9 3u 0 - +R x 1988 1989 - O Su>=9 4u 1 - +R x 1990 o - S 16 4u 1 - +R x 1991 1996 - Mar Su>=9 3u 0 - +R x 1991 1997 - O Su>=9 4u 1 - +R x 1997 o - Mar 30 3u 0 - +R x 1998 o - Mar Su>=9 3u 0 - +R x 1998 o - S 27 4u 1 - +R x 1999 o - Ap 4 3u 0 - +R x 1999 2010 - O Su>=9 4u 1 - +R x 2000 2007 - Mar Su>=9 3u 0 - +R x 2008 o - Mar 30 3u 0 - +R x 2009 o - Mar Su>=9 3u 0 - +R x 2010 o - Ap Su>=1 3u 0 - +R x 2011 o - May Su>=2 3u 0 - +R x 2011 o - Au Su>=16 4u 1 - +R x 2012 2014 - Ap Su>=23 3u 0 - +R x 2012 2014 - S Su>=2 4u 1 - +R x 2016 2018 - May Su>=9 3u 0 - +R x 2016 2018 - Au Su>=9 4u 1 - +R x 2019 ma - Ap Su>=2 3u 0 - +R x 2019 2021 - S Su>=2 4u 1 - +R x 2022 o - S Su>=9 4u 1 - +R x 2023 ma - S Su>=2 4u 1 - +R CO 1992 o - May 3 0 1 - +R CO 1993 o - F 6 24 0 - +R EC 1992 o - N 28 0 1 - +R EC 1993 o - F 5 0 0 - +R FK 1937 1938 - S lastSu 0 1 - +R FK 1938 1942 - Mar Su>=19 0 0 - +R FK 1939 o - O 1 0 1 - +R FK 1940 1942 - S lastSu 0 1 - +R FK 1943 o - Ja 1 0 0 - +R FK 1983 o - S lastSu 0 1 - +R FK 1984 1985 - Ap lastSu 0 0 - +R FK 1984 o - S 16 0 1 - +R FK 1985 2000 - S Su>=9 0 1 - +R FK 1986 2000 - Ap Su>=16 0 0 - +R FK 2001 2010 - Ap Su>=15 2 0 - +R FK 2001 2010 - S Su>=1 2 1 - +R y 1975 1988 - O 1 0 1 - +R y 1975 1978 - Mar 1 0 0 - +R y 1979 1991 - Ap 1 0 0 - +R y 1989 o - O 22 0 1 - +R y 1990 o - O 1 0 1 - +R y 1991 o - O 6 0 1 - +R y 1992 o - Mar 1 0 0 - +R y 1992 o - O 5 0 1 - +R y 1993 o - Mar 31 0 0 - +R y 1993 1995 - O 1 0 1 - +R y 1994 1995 - F lastSu 0 0 - +R y 1996 o - Mar 1 0 0 - +R y 1996 2001 - O Su>=1 0 1 - +R y 1997 o - F lastSu 0 0 - +R y 1998 2001 - Mar Su>=1 0 0 - +R y 2002 2004 - Ap Su>=1 0 0 - +R y 2002 2003 - S Su>=1 0 1 - +R y 2004 2009 - O Su>=15 0 1 - +R y 2005 2009 - Mar Su>=8 0 0 - +R y 2010 2024 - O Su>=1 0 1 - +R y 2010 2012 - Ap Su>=8 0 0 - +R y 2013 2024 - Mar Su>=22 0 0 - +R PE 1938 o - Ja 1 0 1 - +R PE 1938 o - Ap 1 0 0 - +R PE 1938 1939 - S lastSu 0 1 - +R PE 1939 1940 - Mar Su>=24 0 0 - +R PE 1986 1987 - Ja 1 0 1 - +R PE 1986 1987 - Ap 1 0 0 - +R PE 1990 o - Ja 1 0 1 - +R PE 1990 o - Ap 1 0 0 - +R PE 1994 o - Ja 1 0 1 - +R PE 1994 o - Ap 1 0 0 - +R U 1923 1925 - O 1 0 0:30 - +R U 1924 1926 - Ap 1 0 0 - +R U 1933 1938 - O lastSu 0 0:30 - +R U 1934 1941 - Mar lastSa 24 0 - +R U 1939 o - O 1 0 0:30 - +R U 1940 o - O 27 0 0:30 - +R U 1941 o - Au 1 0 0:30 - +R U 1942 o - D 14 0 0:30 - +R U 1943 o - Mar 14 0 0 - +R U 1959 o - May 24 0 0:30 - +R U 1959 o - N 15 0 0 - +R U 1960 o - Ja 17 0 1 - +R U 1960 o - Mar 6 0 0 - +R U 1965 o - Ap 4 0 1 - +R U 1965 o - S 26 0 0 - +R U 1968 o - May 27 0 0:30 - +R U 1968 o - D 1 0 0 - +R U 1970 o - Ap 25 0 1 - +R U 1970 o - Jun 14 0 0 - +R U 1972 o - Ap 23 0 1 - +R U 1972 o - Jul 16 0 0 - +R U 1974 o - Ja 13 0 1:30 - +R U 1974 o - Mar 10 0 0:30 - +R U 1974 o - S 1 0 0 - +R U 1974 o - D 22 0 1 - +R U 1975 o - Mar 30 0 0 - +R U 1976 o - D 19 0 1 - +R U 1977 o - Mar 6 0 0 - +R U 1977 o - D 4 0 1 - +R U 1978 1979 - Mar Su>=1 0 0 - +R U 1978 o - D 17 0 1 - +R U 1979 o - Ap 29 0 1 - +R U 1980 o - Mar 16 0 0 - +R U 1987 o - D 14 0 1 - +R U 1988 o - F 28 0 0 - +R U 1988 o - D 11 0 1 - +R U 1989 o - Mar 5 0 0 - +R U 1989 o - O 29 0 1 - +R U 1990 o - F 25 0 0 - +R U 1990 1991 - O Su>=21 0 1 - +R U 1991 1992 - Mar Su>=1 0 0 - +R U 1992 o - O 18 0 1 - +R U 1993 o - F 28 0 0 - +R U 2004 o - S 19 0 1 - +R U 2005 o - Mar 27 2 0 - +R U 2005 o - O 9 2 1 - +R U 2006 2015 - Mar Su>=8 2 0 - +R U 2006 2014 - O Su>=1 2 1 - +Z Africa/Abidjan -0:16:8 - LMT 1912 +0 - GMT +Z Africa/Algiers 0:12:12 - LMT 1891 Mar 16 +0:9:21 - PMT 1911 Mar 11 +0 d WE%sT 1940 F 25 2 +1 d CE%sT 1946 O 7 +0 - WET 1956 Ja 29 +1 - CET 1963 Ap 14 +0 d WE%sT 1977 O 21 +1 d CE%sT 1979 O 26 +0 d WE%sT 1981 May +1 - CET +Z Africa/Bissau -1:2:20 - LMT 1912 Ja 1 1u +-1 - %z 1975 +0 - GMT +Z Africa/Cairo 2:5:9 - LMT 1900 O +2 K EE%sT +Z Africa/Casablanca -0:30:20 - LMT 1913 O 26 +0 M %z 1984 Mar 16 +1 - %z 1986 +0 M %z 2018 O 28 3 +1 M %z +Z Africa/Ceuta -0:21:16 - LMT 1901 Ja 1 0u +0 - WET 1918 May 6 23 +0 1 WEST 1918 O 7 23 +0 - WET 1924 +0 s WE%sT 1929 +0 - WET 1967 +0 Sp WE%sT 1984 Mar 16 +1 - CET 1986 +1 E CE%sT +Z Africa/El_Aaiun -0:52:48 - LMT 1934 +-1 - %z 1976 Ap 14 +0 M %z 2018 O 28 3 +1 M %z +Z Africa/Johannesburg 1:52 - LMT 1892 F 8 +1:30 - SAST 1903 Mar +2 SA SAST +Z Africa/Juba 2:6:28 - LMT 1931 +2 SD CA%sT 2000 Ja 15 12 +3 - EAT 2021 F +2 - CAT +Z Africa/Khartoum 2:10:8 - LMT 1931 +2 SD CA%sT 2000 Ja 15 12 +3 - EAT 2017 N +2 - CAT +Z Africa/Lagos 0:13:35 - LMT 1905 Jul +0 - GMT 1908 Jul +0:13:35 - LMT 1914 +0:30 - %z 1919 S +1 - WAT +Z Africa/Maputo 2:10:18 - LMT 1909 +2 - CAT +Z Africa/Monrovia -0:43:8 - LMT 1882 +-0:43:8 - MMT 1919 Mar +-0:44:30 - MMT 1972 Ja 7 +0 - GMT +Z Africa/Nairobi 2:27:16 - LMT 1908 May +2:30 - %z 1928 Jun 30 24 +3 - EAT 1930 Ja 4 24 +2:30 - %z 1936 D 31 24 +2:45 - %z 1942 Jul 31 24 +3 - EAT +Z Africa/Ndjamena 1:0:12 - LMT 1912 +1 - WAT 1979 O 14 +1 1 WAST 1980 Mar 8 +1 - WAT +Z Africa/Sao_Tome 0:26:56 - LMT 1884 +-0:36:45 - LMT 1912 Ja 1 0u +0 - GMT 2018 Ja 1 1 +1 - WAT 2019 Ja 1 2 +0 - GMT +Z Africa/Tripoli 0:52:44 - LMT 1920 +1 L CE%sT 1959 +2 - EET 1982 +1 L CE%sT 1990 May 4 +2 - EET 1996 S 30 +1 L CE%sT 1997 O 4 +2 - EET 2012 N 10 2 +1 L CE%sT 2013 O 25 2 +2 - EET +Z Africa/Tunis 0:40:44 - LMT 1881 May 12 +0:9:21 - PMT 1911 Mar 11 +1 n CE%sT +Z Africa/Windhoek 1:8:24 - LMT 1892 F 8 +1:30 - %z 1903 Mar +2 - SAST 1942 S 20 2 +2 1 SAST 1943 Mar 21 2 +2 - SAST 1990 Mar 21 +2 NA %s +Z America/Adak 12:13:22 - LMT 1867 O 19 12:44:35 +-11:46:38 - LMT 1900 Au 20 12 +-11 - NST 1942 +-11 u N%sT 1946 +-11 - NST 1967 Ap +-11 - BST 1969 +-11 u B%sT 1983 O 30 2 +-10 u AH%sT 1983 N 30 +-10 u H%sT +Z America/Anchorage 14:0:24 - LMT 1867 O 19 14:31:37 +-9:59:36 - LMT 1900 Au 20 12 +-10 - AST 1942 +-10 u A%sT 1967 Ap +-10 - AHST 1969 +-10 u AH%sT 1983 O 30 2 +-9 u Y%sT 1983 N 30 +-9 u AK%sT +Z America/Araguaina -3:12:48 - LMT 1914 +-3 B %z 1990 S 17 +-3 - %z 1995 S 14 +-3 B %z 2003 S 24 +-3 - %z 2012 O 21 +-3 B %z 2013 S +-3 - %z +Z America/Argentina/Buenos_Aires -3:53:48 - LMT 1894 O 31 +-4:16:48 - CMT 1920 May +-4 - %z 1930 D +-4 A %z 1969 O 5 +-3 A %z 1999 O 3 +-4 A %z 2000 Mar 3 +-3 A %z +Z America/Argentina/Catamarca -4:23:8 - LMT 1894 O 31 +-4:16:48 - CMT 1920 May +-4 - %z 1930 D +-4 A %z 1969 O 5 +-3 A %z 1991 Mar 3 +-4 - %z 1991 O 20 +-3 A %z 1999 O 3 +-4 A %z 2000 Mar 3 +-3 - %z 2004 Jun +-4 - %z 2004 Jun 20 +-3 A %z 2008 O 18 +-3 - %z +Z America/Argentina/Cordoba -4:16:48 - LMT 1894 O 31 +-4:16:48 - CMT 1920 May +-4 - %z 1930 D +-4 A %z 1969 O 5 +-3 A %z 1991 Mar 3 +-4 - %z 1991 O 20 +-3 A %z 1999 O 3 +-4 A %z 2000 Mar 3 +-3 A %z +Z America/Argentina/Jujuy -4:21:12 - LMT 1894 O 31 +-4:16:48 - CMT 1920 May +-4 - %z 1930 D +-4 A %z 1969 O 5 +-3 A %z 1990 Mar 4 +-4 - %z 1990 O 28 +-4 1 %z 1991 Mar 17 +-4 - %z 1991 O 6 +-3 1 %z 1992 +-3 A %z 1999 O 3 +-4 A %z 2000 Mar 3 +-3 A %z 2008 O 18 +-3 - %z +Z America/Argentina/La_Rioja -4:27:24 - LMT 1894 O 31 +-4:16:48 - CMT 1920 May +-4 - %z 1930 D +-4 A %z 1969 O 5 +-3 A %z 1991 Mar +-4 - %z 1991 May 7 +-3 A %z 1999 O 3 +-4 A %z 2000 Mar 3 +-3 - %z 2004 Jun +-4 - %z 2004 Jun 20 +-3 A %z 2008 O 18 +-3 - %z +Z America/Argentina/Mendoza -4:35:16 - LMT 1894 O 31 +-4:16:48 - CMT 1920 May +-4 - %z 1930 D +-4 A %z 1969 O 5 +-3 A %z 1990 Mar 4 +-4 - %z 1990 O 15 +-4 1 %z 1991 Mar +-4 - %z 1991 O 15 +-4 1 %z 1992 Mar +-4 - %z 1992 O 18 +-3 A %z 1999 O 3 +-4 A %z 2000 Mar 3 +-3 - %z 2004 May 23 +-4 - %z 2004 S 26 +-3 A %z 2008 O 18 +-3 - %z +Z America/Argentina/Rio_Gallegos -4:36:52 - LMT 1894 O 31 +-4:16:48 - CMT 1920 May +-4 - %z 1930 D +-4 A %z 1969 O 5 +-3 A %z 1999 O 3 +-4 A %z 2000 Mar 3 +-3 - %z 2004 Jun +-4 - %z 2004 Jun 20 +-3 A %z 2008 O 18 +-3 - %z +Z America/Argentina/Salta -4:21:40 - LMT 1894 O 31 +-4:16:48 - CMT 1920 May +-4 - %z 1930 D +-4 A %z 1969 O 5 +-3 A %z 1991 Mar 3 +-4 - %z 1991 O 20 +-3 A %z 1999 O 3 +-4 A %z 2000 Mar 3 +-3 A %z 2008 O 18 +-3 - %z +Z America/Argentina/San_Juan -4:34:4 - LMT 1894 O 31 +-4:16:48 - CMT 1920 May +-4 - %z 1930 D +-4 A %z 1969 O 5 +-3 A %z 1991 Mar +-4 - %z 1991 May 7 +-3 A %z 1999 O 3 +-4 A %z 2000 Mar 3 +-3 - %z 2004 May 31 +-4 - %z 2004 Jul 25 +-3 A %z 2008 O 18 +-3 - %z +Z America/Argentina/San_Luis -4:25:24 - LMT 1894 O 31 +-4:16:48 - CMT 1920 May +-4 - %z 1930 D +-4 A %z 1969 O 5 +-3 A %z 1990 +-3 1 %z 1990 Mar 14 +-4 - %z 1990 O 15 +-4 1 %z 1991 Mar +-4 - %z 1991 Jun +-3 - %z 1999 O 3 +-4 1 %z 2000 Mar 3 +-3 - %z 2004 May 31 +-4 - %z 2004 Jul 25 +-3 A %z 2008 Ja 21 +-4 Sa %z 2009 O 11 +-3 - %z +Z America/Argentina/Tucuman -4:20:52 - LMT 1894 O 31 +-4:16:48 - CMT 1920 May +-4 - %z 1930 D +-4 A %z 1969 O 5 +-3 A %z 1991 Mar 3 +-4 - %z 1991 O 20 +-3 A %z 1999 O 3 +-4 A %z 2000 Mar 3 +-3 - %z 2004 Jun +-4 - %z 2004 Jun 13 +-3 A %z +Z America/Argentina/Ushuaia -4:33:12 - LMT 1894 O 31 +-4:16:48 - CMT 1920 May +-4 - %z 1930 D +-4 A %z 1969 O 5 +-3 A %z 1999 O 3 +-4 A %z 2000 Mar 3 +-3 - %z 2004 May 30 +-4 - %z 2004 Jun 20 +-3 A %z 2008 O 18 +-3 - %z +Z America/Asuncion -3:50:40 - LMT 1890 +-3:50:40 - AMT 1931 O 10 +-4 - %z 1972 O +-3 - %z 1974 Ap +-4 y %z 2024 O 15 +-3 - %z +Z America/Bahia -2:34:4 - LMT 1914 +-3 B %z 2003 S 24 +-3 - %z 2011 O 16 +-3 B %z 2012 O 21 +-3 - %z +Z America/Bahia_Banderas -7:1 - LMT 1922 Ja 1 7u +-7 - MST 1927 Jun 10 +-6 - CST 1930 N 15 +-7 m M%sT 1932 Ap +-6 - CST 1942 Ap 24 +-7 - MST 1970 +-7 m M%sT 2010 Ap 4 2 +-6 m C%sT +Z America/Barbados -3:58:29 - LMT 1911 Au 28 +-4 BB A%sT 1944 +-4 BB AST/-0330 1945 +-4 BB A%sT +Z America/Belem -3:13:56 - LMT 1914 +-3 B %z 1988 S 12 +-3 - %z +Z America/Belize -5:52:48 - LMT 1912 Ap +-6 BZ %s +Z America/Boa_Vista -4:2:40 - LMT 1914 +-4 B %z 1988 S 12 +-4 - %z 1999 S 30 +-4 B %z 2000 O 15 +-4 - %z +Z America/Bogota -4:56:16 - LMT 1884 Mar 13 +-4:56:16 - BMT 1914 N 23 +-5 CO %z +Z America/Boise -7:44:49 - LMT 1883 N 18 20u +-8 u P%sT 1923 May 13 2 +-7 u M%sT 1974 +-7 - MST 1974 F 3 2 +-7 u M%sT +Z America/Cambridge_Bay 0 - -00 1920 +-7 Y M%sT 1999 O 31 2 +-6 C C%sT 2000 O 29 2 +-5 - EST 2000 N 5 +-6 - CST 2001 Ap 1 3 +-7 C M%sT +Z America/Campo_Grande -3:38:28 - LMT 1914 +-4 B %z +Z America/Cancun -5:47:4 - LMT 1922 Ja 1 6u +-6 - CST 1981 D 26 2 +-5 - EST 1983 Ja 4 +-6 m C%sT 1997 O 26 2 +-5 m E%sT 1998 Au 2 2 +-6 m C%sT 2015 F 1 2 +-5 - EST +Z America/Caracas -4:27:44 - LMT 1890 +-4:27:40 - CMT 1912 F 12 +-4:30 - %z 1965 +-4 - %z 2007 D 9 3 +-4:30 - %z 2016 May 1 2:30 +-4 - %z +Z America/Cayenne -3:29:20 - LMT 1911 Jul +-4 - %z 1967 O +-3 - %z +Z America/Chicago -5:50:36 - LMT 1883 N 18 18u +-6 u C%sT 1920 +-6 Ch C%sT 1936 Mar 1 2 +-5 - EST 1936 N 15 2 +-6 Ch C%sT 1942 +-6 u C%sT 1946 +-6 Ch C%sT 1967 +-6 u C%sT +Z America/Chihuahua -7:4:20 - LMT 1922 Ja 1 7u +-7 - MST 1927 Jun 10 +-6 - CST 1930 N 15 +-7 m M%sT 1932 Ap +-6 - CST 1996 +-6 m C%sT 1998 +-6 - CST 1998 Ap Su>=1 3 +-7 m M%sT 2022 O 30 2 +-6 - CST +Z America/Ciudad_Juarez -7:5:56 - LMT 1922 Ja 1 7u +-7 - MST 1927 Jun 10 +-6 - CST 1930 N 15 +-7 m M%sT 1932 Ap +-6 - CST 1996 +-6 m C%sT 1998 +-6 - CST 1998 Ap Su>=1 3 +-7 m M%sT 2010 +-7 u M%sT 2022 O 30 2 +-6 - CST 2022 N 30 +-7 u M%sT +Z America/Costa_Rica -5:36:13 - LMT 1890 +-5:36:13 - SJMT 1921 Ja 15 +-6 CR C%sT +Z America/Coyhaique -4:48:16 - LMT 1890 +-4:42:45 - SMT 1910 Ja 10 +-5 - %z 1916 Jul +-4:42:45 - SMT 1918 S 10 +-4 - %z 1919 Jul +-4:42:45 - SMT 1927 S +-5 x %z 1932 S +-4 - %z 1942 Jun +-5 - %z 1942 Au +-4 - %z 1946 Au 28 24 +-5 1 %z 1947 Mar 31 24 +-5 - %z 1947 May 21 23 +-4 x %z 2025 Mar 20 +-3 - %z +Z America/Cuiaba -3:44:20 - LMT 1914 +-4 B %z 2003 S 24 +-4 - %z 2004 O +-4 B %z +Z America/Danmarkshavn -1:14:40 - LMT 1916 Jul 28 +-3 - %z 1980 Ap 6 2 +-3 E %z 1996 +0 - GMT +Z America/Dawson -9:17:40 - LMT 1900 Au 20 +-9 Y Y%sT 1965 +-9 Yu Y%sT 1973 O 28 +-8 - PST 1980 +-8 C P%sT 2020 N +-7 - MST +Z America/Dawson_Creek -8:0:56 - LMT 1884 +-8 C P%sT 1947 +-8 Va P%sT 1972 Au 30 2 +-7 - MST +Z America/Denver -6:59:56 - LMT 1883 N 18 19u +-7 u M%sT 1920 +-7 De M%sT 1942 +-7 u M%sT 1946 +-7 De M%sT 1967 +-7 u M%sT +Z America/Detroit -5:32:11 - LMT 1905 +-6 - CST 1915 May 15 2 +-5 - EST 1942 +-5 u E%sT 1946 +-5 Dt E%sT 1967 Jun 14 0:1 +-5 u E%sT 1969 +-5 - EST 1973 +-5 u E%sT 1975 +-5 - EST 1975 Ap 27 2 +-5 u E%sT +Z America/Edmonton -7:33:52 - LMT 1906 S +-7 Ed M%sT 1987 +-7 C M%sT +Z America/Eirunepe -4:39:28 - LMT 1914 +-5 B %z 1988 S 12 +-5 - %z 1993 S 28 +-5 B %z 1994 S 22 +-5 - %z 2008 Jun 24 +-4 - %z 2013 N 10 +-5 - %z +Z America/El_Salvador -5:56:48 - LMT 1921 +-6 SV C%sT +Z America/Fort_Nelson -8:10:47 - LMT 1884 +-8 Va P%sT 1946 +-8 - PST 1947 +-8 Va P%sT 1987 +-8 C P%sT 2015 Mar 8 2 +-7 - MST +Z America/Fortaleza -2:34 - LMT 1914 +-3 B %z 1990 S 17 +-3 - %z 1999 S 30 +-3 B %z 2000 O 22 +-3 - %z 2001 S 13 +-3 B %z 2002 O +-3 - %z +Z America/Glace_Bay -3:59:48 - LMT 1902 Jun 15 +-4 C A%sT 1953 +-4 H A%sT 1954 +-4 - AST 1972 +-4 H A%sT 1974 +-4 C A%sT +Z America/Goose_Bay -4:1:40 - LMT 1884 +-3:30:52 - NST 1918 +-3:30:52 C N%sT 1919 +-3:30:52 - NST 1935 Mar 30 +-3:30 - NST 1936 +-3:30 j N%sT 1942 May 11 +-3:30 C N%sT 1946 +-3:30 j N%sT 1966 Mar 15 2 +-4 j A%sT 2011 N +-4 C A%sT +Z America/Grand_Turk -4:44:32 - LMT 1890 +-5:7:10 - KMT 1912 F +-5 - EST 1979 +-5 u E%sT 2015 Mar 8 2 +-4 - AST 2018 Mar 11 3 +-5 u E%sT +Z America/Guatemala -6:2:4 - LMT 1918 O 5 +-6 GT C%sT +Z America/Guayaquil -5:19:20 - LMT 1890 +-5:14 - QMT 1931 +-5 EC %z +Z America/Guyana -3:52:39 - LMT 1911 Au +-4 - %z 1915 Mar +-3:45 - %z 1975 Au +-3 - %z 1992 Mar 29 1 +-4 - %z +Z America/Halifax -4:14:24 - LMT 1902 Jun 15 +-4 H A%sT 1918 +-4 C A%sT 1919 +-4 H A%sT 1942 F 9 2s +-4 C A%sT 1946 +-4 H A%sT 1974 +-4 C A%sT +Z America/Havana -5:29:28 - LMT 1890 +-5:29:36 - HMT 1925 Jul 19 12 +-5 Q C%sT +Z America/Hermosillo -7:23:52 - LMT 1922 Ja 1 7u +-7 - MST 1927 Jun 10 +-6 - CST 1930 N 15 +-7 m M%sT 1932 Ap +-6 - CST 1942 Ap 24 +-7 - MST 1996 +-7 m M%sT 1999 +-7 - MST +Z America/Indiana/Indianapolis -5:44:38 - LMT 1883 N 18 18u +-6 u C%sT 1920 +-6 In C%sT 1942 +-6 u C%sT 1946 +-6 In C%sT 1955 Ap 24 2 +-5 - EST 1957 S 29 2 +-6 - CST 1958 Ap 27 2 +-5 - EST 1969 +-5 u E%sT 1971 +-5 - EST 2006 +-5 u E%sT +Z America/Indiana/Knox -5:46:30 - LMT 1883 N 18 18u +-6 u C%sT 1947 +-6 St C%sT 1962 Ap 29 2 +-5 - EST 1963 O 27 2 +-6 u C%sT 1991 O 27 2 +-5 - EST 2006 Ap 2 2 +-6 u C%sT +Z America/Indiana/Marengo -5:45:23 - LMT 1883 N 18 18u +-6 u C%sT 1951 +-6 Ma C%sT 1961 Ap 30 2 +-5 - EST 1969 +-5 u E%sT 1974 Ja 6 2 +-6 1 CDT 1974 O 27 2 +-5 u E%sT 1976 +-5 - EST 2006 +-5 u E%sT +Z America/Indiana/Petersburg -5:49:7 - LMT 1883 N 18 18u +-6 u C%sT 1955 +-6 Pi C%sT 1965 Ap 25 2 +-5 - EST 1966 O 30 2 +-6 u C%sT 1977 O 30 2 +-5 - EST 2006 Ap 2 2 +-6 u C%sT 2007 N 4 2 +-5 u E%sT +Z America/Indiana/Tell_City -5:47:3 - LMT 1883 N 18 18u +-6 u C%sT 1946 +-6 Pe C%sT 1964 Ap 26 2 +-5 - EST 1967 O 29 2 +-6 u C%sT 1969 Ap 27 2 +-5 u E%sT 1971 +-5 - EST 2006 Ap 2 2 +-6 u C%sT +Z America/Indiana/Vevay -5:40:16 - LMT 1883 N 18 18u +-6 u C%sT 1954 Ap 25 2 +-5 - EST 1969 +-5 u E%sT 1973 +-5 - EST 2006 +-5 u E%sT +Z America/Indiana/Vincennes -5:50:7 - LMT 1883 N 18 18u +-6 u C%sT 1946 +-6 V C%sT 1964 Ap 26 2 +-5 - EST 1969 +-5 u E%sT 1971 +-5 - EST 2006 Ap 2 2 +-6 u C%sT 2007 N 4 2 +-5 u E%sT +Z America/Indiana/Winamac -5:46:25 - LMT 1883 N 18 18u +-6 u C%sT 1946 +-6 Pu C%sT 1961 Ap 30 2 +-5 - EST 1969 +-5 u E%sT 1971 +-5 - EST 2006 Ap 2 2 +-6 u C%sT 2007 Mar 11 2 +-5 u E%sT +Z America/Inuvik 0 - -00 1953 +-8 Y P%sT 1979 Ap lastSu 2 +-7 Y M%sT 1980 +-7 C M%sT +Z America/Iqaluit 0 - -00 1942 Au +-5 Y E%sT 1999 O 31 2 +-6 C C%sT 2000 O 29 2 +-5 C E%sT +Z America/Jamaica -5:7:10 - LMT 1890 +-5:7:10 - KMT 1912 F +-5 - EST 1974 +-5 u E%sT 1984 +-5 - EST +Z America/Juneau 15:2:19 - LMT 1867 O 19 15:33:32 +-8:57:41 - LMT 1900 Au 20 12 +-8 - PST 1942 +-8 u P%sT 1946 +-8 - PST 1969 +-8 u P%sT 1980 Ap 27 2 +-9 u Y%sT 1980 O 26 2 +-8 u P%sT 1983 O 30 2 +-9 u Y%sT 1983 N 30 +-9 u AK%sT +Z America/Kentucky/Louisville -5:43:2 - LMT 1883 N 18 18u +-6 u C%sT 1921 +-6 v C%sT 1942 +-6 u C%sT 1946 +-6 v C%sT 1961 Jul 23 2 +-5 - EST 1968 +-5 u E%sT 1974 Ja 6 2 +-6 1 CDT 1974 O 27 2 +-5 u E%sT +Z America/Kentucky/Monticello -5:39:24 - LMT 1883 N 18 18u +-6 u C%sT 1946 +-6 - CST 1968 +-6 u C%sT 2000 O 29 2 +-5 u E%sT +Z America/La_Paz -4:32:36 - LMT 1890 +-4:32:36 - CMT 1931 O 15 +-4:32:36 1 BST 1932 Mar 21 +-4 - %z +Z America/Lima -5:8:12 - LMT 1890 +-5:8:36 - LMT 1908 Jul 28 +-5 PE %z +Z America/Los_Angeles -7:52:58 - LMT 1883 N 18 20u +-8 u P%sT 1946 +-8 CA P%sT 1967 +-8 u P%sT +Z America/Maceio -2:22:52 - LMT 1914 +-3 B %z 1990 S 17 +-3 - %z 1995 O 13 +-3 B %z 1996 S 4 +-3 - %z 1999 S 30 +-3 B %z 2000 O 22 +-3 - %z 2001 S 13 +-3 B %z 2002 O +-3 - %z +Z America/Managua -5:45:8 - LMT 1890 +-5:45:12 - MMT 1934 Jun 23 +-6 - CST 1973 May +-5 - EST 1975 F 16 +-6 NI C%sT 1992 Ja 1 4 +-5 - EST 1992 S 24 +-6 - CST 1993 +-5 - EST 1997 +-6 NI C%sT +Z America/Manaus -4:0:4 - LMT 1914 +-4 B %z 1988 S 12 +-4 - %z 1993 S 28 +-4 B %z 1994 S 22 +-4 - %z +Z America/Martinique -4:4:20 - LMT 1890 +-4:4:20 - FFMT 1911 May +-4 - AST 1980 Ap 6 +-4 1 ADT 1980 S 28 +-4 - AST +Z America/Matamoros -6:30 - LMT 1922 Ja 1 6u +-6 - CST 1988 +-6 u C%sT 1989 +-6 m C%sT 2010 +-6 u C%sT +Z America/Mazatlan -7:5:40 - LMT 1922 Ja 1 7u +-7 - MST 1927 Jun 10 +-6 - CST 1930 N 15 +-7 m M%sT 1932 Ap +-6 - CST 1942 Ap 24 +-7 - MST 1970 +-7 m M%sT +Z America/Menominee -5:50:27 - LMT 1885 S 18 12 +-6 u C%sT 1946 +-6 Me C%sT 1969 Ap 27 2 +-5 - EST 1973 Ap 29 2 +-6 u C%sT +Z America/Merida -5:58:28 - LMT 1922 Ja 1 6u +-6 - CST 1981 D 26 2 +-5 - EST 1982 N 2 2 +-6 m C%sT +Z America/Metlakatla 15:13:42 - LMT 1867 O 19 15:44:55 +-8:46:18 - LMT 1900 Au 20 12 +-8 - PST 1942 +-8 u P%sT 1946 +-8 - PST 1969 +-8 u P%sT 1983 O 30 2 +-8 - PST 2015 N 1 2 +-9 u AK%sT 2018 N 4 2 +-8 - PST 2019 Ja 20 2 +-9 u AK%sT +Z America/Mexico_City -6:36:36 - LMT 1922 Ja 1 7u +-7 - MST 1927 Jun 10 +-6 - CST 1930 N 15 +-7 m M%sT 1932 Ap +-6 m C%sT 2001 S 30 2 +-6 - CST 2002 F 20 +-6 m C%sT +Z America/Miquelon -3:44:40 - LMT 1911 Jun 15 +-4 - AST 1980 May +-3 - %z 1987 +-3 C %z +Z America/Moncton -4:19:8 - LMT 1883 D 9 +-5 - EST 1902 Jun 15 +-4 C A%sT 1933 +-4 o A%sT 1942 +-4 C A%sT 1946 +-4 o A%sT 1973 +-4 C A%sT 1993 +-4 o A%sT 2007 +-4 C A%sT +Z America/Monterrey -6:41:16 - LMT 1922 Ja 1 6u +-7 - MST 1927 Jun 10 +-6 - CST 1930 N 15 +-7 m M%sT 1932 Ap +-6 - CST 1988 +-6 u C%sT 1989 +-6 m C%sT +Z America/Montevideo -3:44:51 - LMT 1908 Jun 10 +-3:44:51 - MMT 1920 May +-4 - %z 1923 O +-3:30 U %z 1942 D 14 +-3 U %z 1960 +-3 U %z 1968 +-3 U %z 1970 +-3 U %z 1974 +-3 U %z 1974 Mar 10 +-3 U %z 1974 D 22 +-3 U %z +Z America/New_York -4:56:2 - LMT 1883 N 18 17u +-5 u E%sT 1920 +-5 NY E%sT 1942 +-5 u E%sT 1946 +-5 NY E%sT 1967 +-5 u E%sT +Z America/Nome 12:58:22 - LMT 1867 O 19 13:29:35 +-11:1:38 - LMT 1900 Au 20 12 +-11 - NST 1942 +-11 u N%sT 1946 +-11 - NST 1967 Ap +-11 - BST 1969 +-11 u B%sT 1983 O 30 2 +-9 u Y%sT 1983 N 30 +-9 u AK%sT +Z America/Noronha -2:9:40 - LMT 1914 +-2 B %z 1990 S 17 +-2 - %z 1999 S 30 +-2 B %z 2000 O 15 +-2 - %z 2001 S 13 +-2 B %z 2002 O +-2 - %z +Z America/North_Dakota/Beulah -6:47:7 - LMT 1883 N 18 19u +-7 u M%sT 2010 N 7 2 +-6 u C%sT +Z America/North_Dakota/Center -6:45:12 - LMT 1883 N 18 19u +-7 u M%sT 1992 O 25 2 +-6 u C%sT +Z America/North_Dakota/New_Salem -6:45:39 - LMT 1883 N 18 19u +-7 u M%sT 2003 O 26 2 +-6 u C%sT +Z America/Nuuk -3:26:56 - LMT 1916 Jul 28 +-3 - %z 1980 Ap 6 2 +-3 E %z 2023 Mar 26 1u +-2 - %z 2023 O 29 1u +-2 E %z +Z America/Ojinaga -6:57:40 - LMT 1922 Ja 1 7u +-7 - MST 1927 Jun 10 +-6 - CST 1930 N 15 +-7 m M%sT 1932 Ap +-6 - CST 1996 +-6 m C%sT 1998 +-6 - CST 1998 Ap Su>=1 3 +-7 m M%sT 2010 +-7 u M%sT 2022 O 30 2 +-6 - CST 2022 N 30 +-6 u C%sT +Z America/Panama -5:18:8 - LMT 1890 +-5:19:36 - CMT 1908 Ap 22 +-5 - EST +Z America/Paramaribo -3:40:40 - LMT 1911 +-3:40:52 - PMT 1935 +-3:40:36 - PMT 1945 O +-3:30 - %z 1984 O +-3 - %z +Z America/Phoenix -7:28:18 - LMT 1883 N 18 19u +-7 u M%sT 1944 Ja 1 0:1 +-7 - MST 1944 Ap 1 0:1 +-7 u M%sT 1944 O 1 0:1 +-7 - MST 1967 +-7 u M%sT 1968 Mar 21 +-7 - MST +Z America/Port-au-Prince -4:49:20 - LMT 1890 +-4:49 - PPMT 1917 Ja 24 12 +-5 HT E%sT +Z America/Porto_Velho -4:15:36 - LMT 1914 +-4 B %z 1988 S 12 +-4 - %z +Z America/Puerto_Rico -4:24:25 - LMT 1899 Mar 28 12 +-4 - AST 1942 May 3 +-4 u A%sT 1946 +-4 - AST +Z America/Punta_Arenas -4:43:40 - LMT 1890 +-4:42:45 - SMT 1910 Ja 10 +-5 - %z 1916 Jul +-4:42:45 - SMT 1918 S 10 +-4 - %z 1919 Jul +-4:42:45 - SMT 1927 S +-5 x %z 1932 S +-4 - %z 1942 Jun +-5 - %z 1942 Au +-4 - %z 1946 Au 28 24 +-5 1 %z 1947 Mar 31 24 +-5 - %z 1947 May 21 23 +-4 x %z 2016 D 4 +-3 - %z +Z America/Rankin_Inlet 0 - -00 1957 +-6 Y C%sT 2000 O 29 2 +-5 - EST 2001 Ap 1 3 +-6 C C%sT +Z America/Recife -2:19:36 - LMT 1914 +-3 B %z 1990 S 17 +-3 - %z 1999 S 30 +-3 B %z 2000 O 15 +-3 - %z 2001 S 13 +-3 B %z 2002 O +-3 - %z +Z America/Regina -6:58:36 - LMT 1905 S +-7 r M%sT 1960 Ap lastSu 2 +-6 - CST +Z America/Resolute 0 - -00 1947 Au 31 +-6 Y C%sT 2000 O 29 2 +-5 - EST 2001 Ap 1 3 +-6 C C%sT 2006 O 29 2 +-5 - EST 2007 Mar 11 3 +-6 C C%sT +Z America/Rio_Branco -4:31:12 - LMT 1914 +-5 B %z 1988 S 12 +-5 - %z 2008 Jun 24 +-4 - %z 2013 N 10 +-5 - %z +Z America/Santarem -3:38:48 - LMT 1914 +-4 B %z 1988 S 12 +-4 - %z 2008 Jun 24 +-3 - %z +Z America/Santiago -4:42:45 - LMT 1890 +-4:42:45 - SMT 1910 Ja 10 +-5 - %z 1916 Jul +-4:42:45 - SMT 1918 S 10 +-4 - %z 1919 Jul +-4:42:45 - SMT 1927 S +-5 x %z 1932 S +-4 - %z 1942 Jun +-5 - %z 1942 Au +-4 - %z 1946 Jul 14 24 +-4 1 %z 1946 Au 28 24 +-5 1 %z 1947 Mar 31 24 +-5 - %z 1947 May 21 23 +-4 x %z +Z America/Santo_Domingo -4:39:36 - LMT 1890 +-4:40 - SDMT 1933 Ap 1 12 +-5 DO %s 1974 O 27 +-4 - AST 2000 O 29 2 +-5 u E%sT 2000 D 3 1 +-4 - AST +Z America/Sao_Paulo -3:6:28 - LMT 1914 +-3 B %z 1963 O 23 +-3 1 %z 1964 +-3 B %z +Z America/Scoresbysund -1:27:52 - LMT 1916 Jul 28 +-2 - %z 1980 Ap 6 2 +-2 c %z 1981 Mar 29 +-1 E %z 2024 Mar 31 +-2 E %z +Z America/Sitka 14:58:47 - LMT 1867 O 19 15:30 +-9:1:13 - LMT 1900 Au 20 12 +-8 - PST 1942 +-8 u P%sT 1946 +-8 - PST 1969 +-8 u P%sT 1983 O 30 2 +-9 u Y%sT 1983 N 30 +-9 u AK%sT +Z America/St_Johns -3:30:52 - LMT 1884 +-3:30:52 j N%sT 1918 +-3:30:52 C N%sT 1919 +-3:30:52 j N%sT 1935 Mar 30 +-3:30 j N%sT 1942 May 11 +-3:30 C N%sT 1946 +-3:30 j N%sT 2011 N +-3:30 C N%sT +Z America/Swift_Current -7:11:20 - LMT 1905 S +-7 C M%sT 1946 Ap lastSu 2 +-7 r M%sT 1950 +-7 Sw M%sT 1972 Ap lastSu 2 +-6 - CST +Z America/Tegucigalpa -5:48:52 - LMT 1921 Ap +-6 HN C%sT +Z America/Thule -4:35:8 - LMT 1916 Jul 28 +-4 Th A%sT +Z America/Tijuana -7:48:4 - LMT 1922 Ja 1 7u +-7 - MST 1924 +-8 - PST 1927 Jun 10 +-7 - MST 1930 N 15 +-8 - PST 1931 Ap +-8 1 PDT 1931 S 30 +-8 - PST 1942 Ap 24 +-8 1 PWT 1945 Au 14 23u +-8 1 PPT 1945 N 15 +-8 - PST 1948 Ap 5 +-8 1 PDT 1949 Ja 14 +-8 - PST 1950 May +-8 1 PDT 1950 S 24 +-8 - PST 1951 Ap 29 2 +-8 1 PDT 1951 S 30 2 +-8 - PST 1952 Ap 27 2 +-8 1 PDT 1952 S 28 2 +-8 - PST 1954 +-8 CA P%sT 1961 +-8 - PST 1976 +-8 u P%sT 1996 +-8 m P%sT 2001 +-8 u P%sT 2002 F 20 +-8 m P%sT 2010 +-8 u P%sT +Z America/Toronto -5:17:32 - LMT 1895 +-5 C E%sT 1919 +-5 t E%sT 1942 F 9 2s +-5 C E%sT 1946 +-5 t E%sT 1974 +-5 C E%sT +Z America/Vancouver -8:12:28 - LMT 1884 +-8 Va P%sT 1987 +-8 C P%sT +Z America/Whitehorse -9:0:12 - LMT 1900 Au 20 +-9 Y Y%sT 1965 +-9 Yu Y%sT 1966 F 27 +-8 - PST 1980 +-8 C P%sT 2020 N +-7 - MST +Z America/Winnipeg -6:28:36 - LMT 1887 Jul 16 +-6 W C%sT 2006 +-6 C C%sT +Z America/Yakutat 14:41:5 - LMT 1867 O 19 15:12:18 +-9:18:55 - LMT 1900 Au 20 12 +-9 - YST 1942 +-9 u Y%sT 1946 +-9 - YST 1969 +-9 u Y%sT 1983 N 30 +-9 u AK%sT +Z Antarctica/Casey 0 - -00 1969 +8 - %z 2009 O 18 2 +11 - %z 2010 Mar 5 2 +8 - %z 2011 O 28 2 +11 - %z 2012 F 21 17u +8 - %z 2016 O 22 +11 - %z 2018 Mar 11 4 +8 - %z 2018 O 7 4 +11 - %z 2019 Mar 17 3 +8 - %z 2019 O 4 3 +11 - %z 2020 Mar 8 3 +8 - %z 2020 O 4 0:1 +11 - %z 2021 Mar 14 +8 - %z 2021 O 3 0:1 +11 - %z 2022 Mar 13 +8 - %z 2022 O 2 0:1 +11 - %z 2023 Mar 9 3 +8 - %z +Z Antarctica/Davis 0 - -00 1957 Ja 13 +7 - %z 1964 N +0 - -00 1969 F +7 - %z 2009 O 18 2 +5 - %z 2010 Mar 10 20u +7 - %z 2011 O 28 2 +5 - %z 2012 F 21 20u +7 - %z +Z Antarctica/Macquarie 0 - -00 1899 N +10 - AEST 1916 O 1 2 +10 1 AEDT 1917 F +10 AU AE%sT 1919 Ap 1 0s +0 - -00 1948 Mar 25 +10 AU AE%sT 1967 +10 AT AE%sT 2010 +10 1 AEDT 2011 +10 AT AE%sT +Z Antarctica/Mawson 0 - -00 1954 F 13 +6 - %z 2009 O 18 2 +5 - %z +Z Antarctica/Palmer 0 - -00 1965 +-4 A %z 1969 O 5 +-3 A %z 1982 May +-4 x %z 2016 D 4 +-3 - %z +Z Antarctica/Rothera 0 - -00 1976 D +-3 - %z +Z Antarctica/Troll 0 - -00 2005 F 12 +0 Tr %s +Z Antarctica/Vostok 0 - -00 1957 D 16 +7 - %z 1994 F +0 - -00 1994 N +7 - %z 2023 D 18 2 +5 - %z +Z Asia/Almaty 5:7:48 - LMT 1924 May 2 +5 - %z 1930 Jun 21 +6 R %z 1991 Mar 31 2s +5 R %z 1992 Ja 19 2s +6 R %z 2004 O 31 2s +6 - %z 2024 Mar +5 - %z +Z Asia/Amman 2:23:44 - LMT 1931 +2 J EE%sT 2022 O 28 0s +3 - %z +Z Asia/Anadyr 11:49:56 - LMT 1924 May 2 +12 - %z 1930 Jun 21 +13 R %z 1982 Ap 1 0s +12 R %z 1991 Mar 31 2s +11 R %z 1992 Ja 19 2s +12 R %z 2010 Mar 28 2s +11 R %z 2011 Mar 27 2s +12 - %z +Z Asia/Aqtau 3:21:4 - LMT 1924 May 2 +4 - %z 1930 Jun 21 +5 - %z 1981 O +6 - %z 1982 Ap +5 R %z 1991 Mar 31 2s +4 R %z 1992 Ja 19 2s +5 R %z 1994 S 25 2s +4 R %z 2004 O 31 2s +5 - %z +Z Asia/Aqtobe 3:48:40 - LMT 1924 May 2 +4 - %z 1930 Jun 21 +5 - %z 1981 Ap +5 1 %z 1981 O +6 - %z 1982 Ap +5 R %z 1991 Mar 31 2s +4 R %z 1992 Ja 19 2s +5 R %z 2004 O 31 2s +5 - %z +Z Asia/Ashgabat 3:53:32 - LMT 1924 May 2 +4 - %z 1930 Jun 21 +5 R %z 1991 Mar 31 2 +4 R %z 1992 Ja 19 2 +5 - %z +Z Asia/Atyrau 3:27:44 - LMT 1924 May 2 +3 - %z 1930 Jun 21 +5 - %z 1981 O +6 - %z 1982 Ap +5 R %z 1991 Mar 31 2s +4 R %z 1992 Ja 19 2s +5 R %z 1999 Mar 28 2s +4 R %z 2004 O 31 2s +5 - %z +Z Asia/Baghdad 2:57:40 - LMT 1890 +2:57:36 - BMT 1918 +3 - %z 1982 May +3 IQ %z +Z Asia/Baku 3:19:24 - LMT 1924 May 2 +3 - %z 1957 Mar +4 R %z 1991 Mar 31 2s +3 R %z 1992 S lastSu 2s +4 - %z 1996 +4 E %z 1997 +4 AZ %z +Z Asia/Bangkok 6:42:4 - LMT 1880 +6:42:4 - BMT 1920 Ap +7 - %z +Z Asia/Barnaul 5:35 - LMT 1919 D 10 +6 - %z 1930 Jun 21 +7 R %z 1991 Mar 31 2s +6 R %z 1992 Ja 19 2s +7 R %z 1995 May 28 +6 R %z 2011 Mar 27 2s +7 - %z 2014 O 26 2s +6 - %z 2016 Mar 27 2s +7 - %z +Z Asia/Beirut 2:22 - LMT 1880 +2 l EE%sT +Z Asia/Bishkek 4:58:24 - LMT 1924 May 2 +5 - %z 1930 Jun 21 +6 R %z 1991 Mar 31 2s +5 R %z 1991 Au 31 2 +5 KG %z 2005 Au 12 +6 - %z +Z Asia/Chita 7:33:52 - LMT 1919 D 15 +8 - %z 1930 Jun 21 +9 R %z 1991 Mar 31 2s +8 R %z 1992 Ja 19 2s +9 R %z 2011 Mar 27 2s +10 - %z 2014 O 26 2s +8 - %z 2016 Mar 27 2 +9 - %z +Z Asia/Colombo 5:19:24 - LMT 1880 +5:19:32 - MMT 1906 +5:30 - %z 1942 Ja 5 +5:30 0:30 %z 1942 S +5:30 1 %z 1945 O 16 2 +5:30 - %z 1996 May 25 +6:30 - %z 1996 O 26 0:30 +6 - %z 2006 Ap 15 0:30 +5:30 - %z +Z Asia/Damascus 2:25:12 - LMT 1920 +2 S EE%sT 2022 O 28 +3 - %z +Z Asia/Dhaka 6:1:40 - LMT 1890 +5:53:20 - HMT 1941 O +6:30 - %z 1942 May 15 +5:30 - %z 1942 S +6:30 - %z 1951 S 30 +6 - %z 2009 +6 BD %z +Z Asia/Dili 8:22:20 - LMT 1911 D 31 16u +8 - %z 1942 F 21 23 +9 - %z 1976 May 3 +8 - %z 2000 S 17 +9 - %z +Z Asia/Dubai 3:41:12 - LMT 1920 +4 - %z +Z Asia/Dushanbe 4:35:12 - LMT 1924 May 2 +5 - %z 1930 Jun 21 +6 R %z 1991 Mar 31 2s +5 1 %z 1991 S 9 2s +5 - %z +Z Asia/Famagusta 2:15:48 - LMT 1921 N 14 +2 CY EE%sT 1998 S +2 E EE%sT 2016 S 8 +3 - %z 2017 O 29 1u +2 E EE%sT +Z Asia/Gaza 2:17:52 - LMT 1900 O +2 Z EET/EEST 1948 May 15 +2 K EE%sT 1967 Jun 5 +2 Z I%sT 1996 +2 J EE%sT 1999 +2 P EE%sT 2008 Au 29 +2 - EET 2008 S +2 P EE%sT 2010 +2 - EET 2010 Mar 27 0:1 +2 P EE%sT 2011 Au +2 - EET 2012 +2 P EE%sT +Z Asia/Hebron 2:20:23 - LMT 1900 O +2 Z EET/EEST 1948 May 15 +2 K EE%sT 1967 Jun 5 +2 Z I%sT 1996 +2 J EE%sT 1999 +2 P EE%sT +Z Asia/Ho_Chi_Minh 7:6:30 - LMT 1906 Jul +7:6:30 - PLMT 1911 May +7 - %z 1942 D 31 23 +8 - %z 1945 Mar 14 23 +9 - %z 1945 S 1 24 +7 - %z 1947 Ap +8 - %z 1955 Jul 1 1 +7 - %z 1959 D 31 23 +8 - %z 1975 Jun 13 +7 - %z +Z Asia/Hong_Kong 7:36:42 - LMT 1904 O 29 17u +8 - HKT 1941 Jun 15 3 +8 1 HKST 1941 O 1 4 +8 0:30 HKWT 1941 D 25 +9 - JST 1945 N 18 2 +8 HK HK%sT +Z Asia/Hovd 6:6:36 - LMT 1905 Au +6 - %z 1978 +7 X %z +Z Asia/Irkutsk 6:57:5 - LMT 1880 +6:57:5 - IMT 1920 Ja 25 +7 - %z 1930 Jun 21 +8 R %z 1991 Mar 31 2s +7 R %z 1992 Ja 19 2s +8 R %z 2011 Mar 27 2s +9 - %z 2014 O 26 2s +8 - %z +Z Asia/Jakarta 7:7:12 - LMT 1867 Au 10 +7:7:12 - BMT 1923 D 31 16:40u +7:20 - %z 1932 N +7:30 - %z 1942 Mar 23 +9 - %z 1945 S 23 +7:30 - %z 1948 May +8 - %z 1950 May +7:30 - %z 1964 +7 - WIB +Z Asia/Jayapura 9:22:48 - LMT 1932 N +9 - %z 1944 S +9:30 - %z 1964 +9 - WIT +Z Asia/Jerusalem 2:20:54 - LMT 1880 +2:20:40 - JMT 1918 +2 Z I%sT +Z Asia/Kabul 4:36:48 - LMT 1890 +4 - %z 1945 +4:30 - %z +Z Asia/Kamchatka 10:34:36 - LMT 1922 N 10 +11 - %z 1930 Jun 21 +12 R %z 1991 Mar 31 2s +11 R %z 1992 Ja 19 2s +12 R %z 2010 Mar 28 2s +11 R %z 2011 Mar 27 2s +12 - %z +Z Asia/Karachi 4:28:12 - LMT 1907 +5:30 - %z 1942 S +5:30 1 %z 1945 O 15 +5:30 - %z 1951 S 30 +5 - %z 1971 Mar 26 +5 PK PK%sT +Z Asia/Kathmandu 5:41:16 - LMT 1920 +5:30 - %z 1986 +5:45 - %z +Z Asia/Khandyga 9:2:13 - LMT 1919 D 15 +8 - %z 1930 Jun 21 +9 R %z 1991 Mar 31 2s +8 R %z 1992 Ja 19 2s +9 R %z 2004 +10 R %z 2011 Mar 27 2s +11 - %z 2011 S 13 0s +10 - %z 2014 O 26 2s +9 - %z +Z Asia/Kolkata 5:53:28 - LMT 1854 Jun 28 +5:53:20 - HMT 1870 +5:21:10 - MMT 1906 +5:30 - IST 1941 O +5:30 1 %z 1942 May 15 +5:30 - IST 1942 S +5:30 1 %z 1945 O 15 +5:30 - IST +Z Asia/Krasnoyarsk 6:11:26 - LMT 1920 Ja 6 +6 - %z 1930 Jun 21 +7 R %z 1991 Mar 31 2s +6 R %z 1992 Ja 19 2s +7 R %z 2011 Mar 27 2s +8 - %z 2014 O 26 2s +7 - %z +Z Asia/Kuching 7:21:20 - LMT 1926 Mar +7:30 - %z 1933 +8 NB %z 1942 F 16 +9 - %z 1945 S 12 +8 - %z +Z Asia/Macau 7:34:10 - LMT 1904 O 30 +8 - CST 1941 D 21 23 +9 _ %z 1945 S 30 24 +8 _ C%sT +Z Asia/Magadan 10:3:12 - LMT 1924 May 2 +10 - %z 1930 Jun 21 +11 R %z 1991 Mar 31 2s +10 R %z 1992 Ja 19 2s +11 R %z 2011 Mar 27 2s +12 - %z 2014 O 26 2s +10 - %z 2016 Ap 24 2s +11 - %z +Z Asia/Makassar 7:57:36 - LMT 1920 +7:57:36 - MMT 1932 N +8 - %z 1942 F 9 +9 - %z 1945 S 23 +8 - WITA +Z Asia/Manila -15:56:8 - LMT 1844 D 31 +8:3:52 - LMT 1899 S 6 4u +8 PH P%sT 1942 F 11 24 +9 - JST 1945 Mar 4 +8 PH P%sT +Z Asia/Nicosia 2:13:28 - LMT 1921 N 14 +2 CY EE%sT 1998 S +2 E EE%sT +Z Asia/Novokuznetsk 5:48:48 - LMT 1924 May +6 - %z 1930 Jun 21 +7 R %z 1991 Mar 31 2s +6 R %z 1992 Ja 19 2s +7 R %z 2010 Mar 28 2s +6 R %z 2011 Mar 27 2s +7 - %z +Z Asia/Novosibirsk 5:31:40 - LMT 1919 D 14 6 +6 - %z 1930 Jun 21 +7 R %z 1991 Mar 31 2s +6 R %z 1992 Ja 19 2s +7 R %z 1993 May 23 +6 R %z 2011 Mar 27 2s +7 - %z 2014 O 26 2s +6 - %z 2016 Jul 24 2s +7 - %z +Z Asia/Omsk 4:53:30 - LMT 1919 N 14 +5 - %z 1930 Jun 21 +6 R %z 1991 Mar 31 2s +5 R %z 1992 Ja 19 2s +6 R %z 2011 Mar 27 2s +7 - %z 2014 O 26 2s +6 - %z +Z Asia/Oral 3:25:24 - LMT 1924 May 2 +3 - %z 1930 Jun 21 +5 - %z 1981 Ap +5 1 %z 1981 O +6 - %z 1982 Ap +5 R %z 1989 Mar 26 2s +4 R %z 1992 Ja 19 2s +5 R %z 1992 Mar 29 2s +4 R %z 2004 O 31 2s +5 - %z +Z Asia/Pontianak 7:17:20 - LMT 1908 May +7:17:20 - PMT 1932 N +7:30 - %z 1942 Ja 29 +9 - %z 1945 S 23 +7:30 - %z 1948 May +8 - %z 1950 May +7:30 - %z 1964 +8 - WITA 1988 +7 - WIB +Z Asia/Pyongyang 8:23 - LMT 1908 Ap +8:30 - KST 1912 +9 - JST 1945 Au 24 +9 - KST 2015 Au 15 +8:30 - KST 2018 May 4 23:30 +9 - KST +Z Asia/Qatar 3:26:8 - LMT 1920 +4 - %z 1972 Jun +3 - %z +Z Asia/Qostanay 4:14:28 - LMT 1924 May 2 +4 - %z 1930 Jun 21 +5 - %z 1981 Ap +5 1 %z 1981 O +6 - %z 1982 Ap +5 R %z 1991 Mar 31 2s +4 R %z 1992 Ja 19 2s +5 R %z 2004 O 31 2s +6 - %z 2024 Mar +5 - %z +Z Asia/Qyzylorda 4:21:52 - LMT 1924 May 2 +4 - %z 1930 Jun 21 +5 - %z 1981 Ap +5 1 %z 1981 O +6 - %z 1982 Ap +5 R %z 1991 Mar 31 2s +4 R %z 1991 S 29 2s +5 R %z 1992 Ja 19 2s +6 R %z 1992 Mar 29 2s +5 R %z 2004 O 31 2s +6 - %z 2018 D 21 +5 - %z +Z Asia/Riyadh 3:6:52 - LMT 1947 Mar 14 +3 - %z +Z Asia/Sakhalin 9:30:48 - LMT 1905 Au 23 +9 - %z 1945 Au 25 +11 R %z 1991 Mar 31 2s +10 R %z 1992 Ja 19 2s +11 R %z 1997 Mar lastSu 2s +10 R %z 2011 Mar 27 2s +11 - %z 2014 O 26 2s +10 - %z 2016 Mar 27 2s +11 - %z +Z Asia/Samarkand 4:27:53 - LMT 1924 May 2 +4 - %z 1930 Jun 21 +5 - %z 1981 Ap +5 1 %z 1981 O +6 - %z 1982 Ap +5 R %z 1992 +5 - %z +Z Asia/Seoul 8:27:52 - LMT 1908 Ap +8:30 - KST 1912 +9 - JST 1945 S 8 +9 KR K%sT 1954 Mar 21 +8:30 KR K%sT 1961 Au 10 +9 KR K%sT +Z Asia/Shanghai 8:5:43 - LMT 1901 +8 Sh C%sT 1949 May 28 +8 CN C%sT +Z Asia/Singapore 6:55:25 - LMT 1901 +6:55:25 - SMT 1905 Jun +7 - %z 1933 +7 0:20 %z 1936 +7:20 - %z 1941 S +7:30 - %z 1942 F 16 +9 - %z 1945 S 12 +7:30 - %z 1981 D 31 16u +8 - %z +Z Asia/Srednekolymsk 10:14:52 - LMT 1924 May 2 +10 - %z 1930 Jun 21 +11 R %z 1991 Mar 31 2s +10 R %z 1992 Ja 19 2s +11 R %z 2011 Mar 27 2s +12 - %z 2014 O 26 2s +11 - %z +Z Asia/Taipei 8:6 - LMT 1896 +8 - CST 1937 O +9 - JST 1945 S 21 1 +8 f C%sT +Z Asia/Tashkent 4:37:11 - LMT 1924 May 2 +5 - %z 1930 Jun 21 +6 R %z 1991 Mar 31 2 +5 R %z 1992 +5 - %z +Z Asia/Tbilisi 2:59:11 - LMT 1880 +2:59:11 - TBMT 1924 May 2 +3 - %z 1957 Mar +4 R %z 1991 Mar 31 2s +3 R %z 1992 +3 e %z 1994 S lastSu +4 e %z 1996 O lastSu +4 1 %z 1997 Mar lastSu +4 e %z 2004 Jun 27 +3 R %z 2005 Mar lastSu 2 +4 - %z +Z Asia/Tehran 3:25:44 - LMT 1916 +3:25:44 - TMT 1935 Jun 13 +3:30 i %z 1977 O 20 24 +4 i %z 1978 N 10 24 +3:30 i %z +Z Asia/Thimphu 5:58:36 - LMT 1947 Au 15 +5:30 - %z 1987 O +6 - %z +Z Asia/Tokyo 9:18:59 - LMT 1887 D 31 15u +9 JP J%sT +Z Asia/Tomsk 5:39:51 - LMT 1919 D 22 +6 - %z 1930 Jun 21 +7 R %z 1991 Mar 31 2s +6 R %z 1992 Ja 19 2s +7 R %z 2002 May 1 3 +6 R %z 2011 Mar 27 2s +7 - %z 2014 O 26 2s +6 - %z 2016 May 29 2s +7 - %z +Z Asia/Ulaanbaatar 7:7:32 - LMT 1905 Au +7 - %z 1978 +8 X %z +Z Asia/Urumqi 5:50:20 - LMT 1928 +6 - %z +Z Asia/Ust-Nera 9:32:54 - LMT 1919 D 15 +8 - %z 1930 Jun 21 +9 R %z 1981 Ap +11 R %z 1991 Mar 31 2s +10 R %z 1992 Ja 19 2s +11 R %z 2011 Mar 27 2s +12 - %z 2011 S 13 0s +11 - %z 2014 O 26 2s +10 - %z +Z Asia/Vladivostok 8:47:31 - LMT 1922 N 15 +9 - %z 1930 Jun 21 +10 R %z 1991 Mar 31 2s +9 R %z 1992 Ja 19 2s +10 R %z 2011 Mar 27 2s +11 - %z 2014 O 26 2s +10 - %z +Z Asia/Yakutsk 8:38:58 - LMT 1919 D 15 +8 - %z 1930 Jun 21 +9 R %z 1991 Mar 31 2s +8 R %z 1992 Ja 19 2s +9 R %z 2011 Mar 27 2s +10 - %z 2014 O 26 2s +9 - %z +Z Asia/Yangon 6:24:47 - LMT 1880 +6:24:47 - RMT 1920 +6:30 - %z 1942 May +9 - %z 1945 May 3 +6:30 - %z +Z Asia/Yekaterinburg 4:2:33 - LMT 1916 Jul 3 +3:45:5 - PMT 1919 Jul 15 4 +4 - %z 1930 Jun 21 +5 R %z 1991 Mar 31 2s +4 R %z 1992 Ja 19 2s +5 R %z 2011 Mar 27 2s +6 - %z 2014 O 26 2s +5 - %z +Z Asia/Yerevan 2:58 - LMT 1924 May 2 +3 - %z 1957 Mar +4 R %z 1991 Mar 31 2s +3 R %z 1995 S 24 2s +4 - %z 1997 +4 R %z 2011 +4 AM %z +Z Atlantic/Azores -1:42:40 - LMT 1884 +-1:54:32 - HMT 1912 Ja 1 2u +-2 p %z 1966 O 2 2s +-1 - %z 1982 Mar 28 0s +-1 p %z 1986 +-1 E %z 1992 D 27 1s +0 E WE%sT 1993 Jun 17 1u +-1 E %z +Z Atlantic/Bermuda -4:19:18 - LMT 1890 +-4:19:18 Be BMT/BST 1930 Ja 1 2 +-4 Be A%sT 1974 Ap 28 2 +-4 C A%sT 1976 +-4 u A%sT +Z Atlantic/Canary -1:1:36 - LMT 1922 Mar +-1 - %z 1946 S 30 1 +0 - WET 1980 Ap 6 0s +0 1 WEST 1980 S 28 1u +0 E WE%sT +Z Atlantic/Cape_Verde -1:34:4 - LMT 1912 Ja 1 2u +-2 - %z 1942 S +-2 1 %z 1945 O 15 +-2 - %z 1975 N 25 2 +-1 - %z +Z Atlantic/Faroe -0:27:4 - LMT 1908 Ja 11 +0 - WET 1981 +0 E WE%sT +Z Atlantic/Madeira -1:7:36 - LMT 1884 +-1:7:36 - FMT 1912 Ja 1 1u +-1 p %z 1966 O 2 2s +0 - WET 1982 Ap 4 +0 p WE%sT 1986 Jul 31 +0 E WE%sT +Z Atlantic/South_Georgia -2:26:8 - LMT 1890 +-2 - %z +Z Atlantic/Stanley -3:51:24 - LMT 1890 +-3:51:24 - SMT 1912 Mar 12 +-4 FK %z 1983 May +-3 FK %z 1985 S 15 +-4 FK %z 2010 S 5 2 +-3 - %z +Z Australia/Adelaide 9:14:20 - LMT 1895 F +9 - ACST 1899 May +9:30 AU AC%sT 1971 +9:30 AS AC%sT +Z Australia/Brisbane 10:12:8 - LMT 1895 +10 AU AE%sT 1971 +10 AQ AE%sT +Z Australia/Broken_Hill 9:25:48 - LMT 1895 F +10 - AEST 1896 Au 23 +9 - ACST 1899 May +9:30 AU AC%sT 1971 +9:30 AN AC%sT 2000 +9:30 AS AC%sT +Z Australia/Darwin 8:43:20 - LMT 1895 F +9 - ACST 1899 May +9:30 AU AC%sT +Z Australia/Eucla 8:35:28 - LMT 1895 D +8:45 AU %z 1943 Jul +8:45 AW %z +Z Australia/Hobart 9:49:16 - LMT 1895 S +10 AT AE%sT 1919 O 24 +10 AU AE%sT 1967 +10 AT AE%sT +Z Australia/Lindeman 9:55:56 - LMT 1895 +10 AU AE%sT 1971 +10 AQ AE%sT 1992 Jul +10 Ho AE%sT +Z Australia/Lord_Howe 10:36:20 - LMT 1895 F +10 - AEST 1981 Mar +10:30 LH %z 1985 Jul +10:30 LH %z +Z Australia/Melbourne 9:39:52 - LMT 1895 F +10 AU AE%sT 1971 +10 AV AE%sT +Z Australia/Perth 7:43:24 - LMT 1895 D +8 AU AW%sT 1943 Jul +8 AW AW%sT +Z Australia/Sydney 10:4:52 - LMT 1895 F +10 AU AE%sT 1971 +10 AN AE%sT +Z Etc/GMT 0 - GMT +Z Etc/GMT+1 -1 - %z +Z Etc/GMT+10 -10 - %z +Z Etc/GMT+11 -11 - %z +Z Etc/GMT+12 -12 - %z +Z Etc/GMT+2 -2 - %z +Z Etc/GMT+3 -3 - %z +Z Etc/GMT+4 -4 - %z +Z Etc/GMT+5 -5 - %z +Z Etc/GMT+6 -6 - %z +Z Etc/GMT+7 -7 - %z +Z Etc/GMT+8 -8 - %z +Z Etc/GMT+9 -9 - %z +Z Etc/GMT-1 1 - %z +Z Etc/GMT-10 10 - %z +Z Etc/GMT-11 11 - %z +Z Etc/GMT-12 12 - %z +Z Etc/GMT-13 13 - %z +Z Etc/GMT-14 14 - %z +Z Etc/GMT-2 2 - %z +Z Etc/GMT-3 3 - %z +Z Etc/GMT-4 4 - %z +Z Etc/GMT-5 5 - %z +Z Etc/GMT-6 6 - %z +Z Etc/GMT-7 7 - %z +Z Etc/GMT-8 8 - %z +Z Etc/GMT-9 9 - %z +Z Etc/UTC 0 - UTC +Z Europe/Andorra 0:6:4 - LMT 1901 +0 - WET 1946 S 30 +1 - CET 1985 Mar 31 2 +1 E CE%sT +Z Europe/Astrakhan 3:12:12 - LMT 1924 May +3 - %z 1930 Jun 21 +4 R %z 1989 Mar 26 2s +3 R %z 1991 Mar 31 2s +4 - %z 1992 Mar 29 2s +3 R %z 2011 Mar 27 2s +4 - %z 2014 O 26 2s +3 - %z 2016 Mar 27 2s +4 - %z +Z Europe/Athens 1:34:52 - LMT 1895 S 14 +1:34:52 - AMT 1916 Jul 28 0:1 +2 g EE%sT 1941 Ap 30 +1 g CE%sT 1944 Ap 4 +2 g EE%sT 1981 +2 E EE%sT +Z Europe/Belgrade 1:22 - LMT 1884 +1 - CET 1941 Ap 18 23 +1 c CE%sT 1945 +1 - CET 1945 May 8 2s +1 1 CEST 1945 S 16 2s +1 - CET 1982 N 27 +1 E CE%sT +Z Europe/Berlin 0:53:28 - LMT 1893 Ap +1 c CE%sT 1945 May 24 2 +1 So CE%sT 1946 +1 DE CE%sT 1980 +1 E CE%sT +Z Europe/Brussels 0:17:30 - LMT 1880 +0:17:30 - BMT 1892 May 1 0:17:30 +0 - WET 1914 N 8 +1 - CET 1916 May +1 c CE%sT 1918 N 11 11u +0 b WE%sT 1940 May 20 2s +1 c CE%sT 1944 S 3 +1 b CE%sT 1977 +1 E CE%sT +Z Europe/Bucharest 1:44:24 - LMT 1891 O +1:44:24 - BMT 1931 Jul 24 +2 z EE%sT 1981 Mar 29 2s +2 c EE%sT 1991 +2 z EE%sT 1994 +2 e EE%sT 1997 +2 E EE%sT +Z Europe/Budapest 1:16:20 - LMT 1890 N +1 c CE%sT 1918 +1 h CE%sT 1941 Ap 7 23 +1 c CE%sT 1945 +1 h CE%sT 1984 +1 E CE%sT +Z Europe/Chisinau 1:55:20 - LMT 1880 +1:55 - CMT 1918 F 15 +1:44:24 - BMT 1931 Jul 24 +2 z EE%sT 1940 Au 15 +2 1 EEST 1941 Jul 17 +1 c CE%sT 1944 Au 24 +3 R MSK/MSD 1990 May 6 2 +2 R EE%sT 1992 +2 e EE%sT 1997 +2 MD EE%sT +Z Europe/Dublin -0:25:21 - LMT 1880 Au 2 +-0:25:21 - DMT 1916 May 21 2s +-0:25:21 1 IST 1916 O 1 2s +0 G %s 1921 D 6 +0 G GMT/IST 1940 F 25 2s +0 1 IST 1946 O 6 2s +0 - GMT 1947 Mar 16 2s +0 1 IST 1947 N 2 2s +0 - GMT 1948 Ap 18 2s +0 G GMT/IST 1968 O 27 +1 IE IST/GMT +Z Europe/Gibraltar -0:21:24 - LMT 1880 Au 2 +0 G %s 1957 Ap 14 2 +1 - CET 1982 +1 E CE%sT +Z Europe/Helsinki 1:39:49 - LMT 1878 May 31 +1:39:49 - HMT 1921 May +2 FI EE%sT 1983 +2 E EE%sT +Z Europe/Istanbul 1:55:52 - LMT 1880 +1:56:56 - IMT 1910 O +2 T EE%sT 1978 Jun 29 +3 T %z 1984 N 1 2 +2 T EE%sT 2007 +2 E EE%sT 2011 Mar 27 1u +2 - EET 2011 Mar 28 1u +2 E EE%sT 2014 Mar 30 1u +2 - EET 2014 Mar 31 1u +2 E EE%sT 2015 O 25 1u +2 1 EEST 2015 N 8 1u +2 E EE%sT 2016 S 7 +3 - %z +Z Europe/Kaliningrad 1:22 - LMT 1893 Ap +1 c CE%sT 1945 Ap 10 +2 O EE%sT 1946 Ap 7 +3 R MSK/MSD 1989 Mar 26 2s +2 R EE%sT 2011 Mar 27 2s +3 - %z 2014 O 26 2s +2 - EET +Z Europe/Kirov 3:18:48 - LMT 1919 Jul 1 0u +3 - %z 1930 Jun 21 +4 R %z 1989 Mar 26 2s +3 R MSK/MSD 1991 Mar 31 2s +4 - %z 1992 Mar 29 2s +3 R MSK/MSD 2011 Mar 27 2s +4 - MSK 2014 O 26 2s +3 - MSK +Z Europe/Kyiv 2:2:4 - LMT 1880 +2:2:4 - KMT 1924 May 2 +2 - EET 1930 Jun 21 +3 - MSK 1941 S 20 +1 c CE%sT 1943 N 6 +3 R MSK/MSD 1990 Jul 1 2 +2 1 EEST 1991 S 29 3 +2 c EE%sT 1996 May 13 +2 E EE%sT +Z Europe/Lisbon -0:36:45 - LMT 1884 +-0:36:45 - LMT 1912 Ja 1 0u +0 p WE%sT 1966 O 2 2s +1 - CET 1976 S 26 1 +0 p WE%sT 1986 +0 E WE%sT 1992 S 27 1u +1 E CE%sT 1996 Mar 31 1u +0 E WE%sT +Z Europe/London -0:1:15 - LMT 1847 D +0 G %s 1968 O 27 +1 - BST 1971 O 31 2u +0 G %s 1996 +0 E GMT/BST +Z Europe/Madrid -0:14:44 - LMT 1901 Ja 1 0u +0 s WE%sT 1940 Mar 16 23 +1 s CE%sT 1979 +1 E CE%sT +Z Europe/Malta 0:58:4 - LMT 1893 N 2 +1 I CE%sT 1973 Mar 31 +1 MT CE%sT 1981 +1 E CE%sT +Z Europe/Minsk 1:50:16 - LMT 1880 +1:50 - MMT 1924 May 2 +2 - EET 1930 Jun 21 +3 - MSK 1941 Jun 28 +1 c CE%sT 1944 Jul 3 +3 R MSK/MSD 1990 +3 - MSK 1991 Mar 31 2s +2 R EE%sT 2011 Mar 27 2s +3 - %z +Z Europe/Moscow 2:30:17 - LMT 1880 +2:30:17 - MMT 1916 Jul 3 +2:31:19 R %s 1919 Jul 1 0u +3 R %s 1921 O +3 R MSK/MSD 1922 O +2 - EET 1930 Jun 21 +3 R MSK/MSD 1991 Mar 31 2s +2 R EE%sT 1992 Ja 19 2s +3 R MSK/MSD 2011 Mar 27 2s +4 - MSK 2014 O 26 2s +3 - MSK +Z Europe/Paris 0:9:21 - LMT 1891 Mar 16 +0:9:21 - PMT 1911 Mar 11 +0 F WE%sT 1940 Jun 14 23 +1 c CE%sT 1944 Au 25 +0 F WE%sT 1945 S 16 3 +1 F CE%sT 1977 +1 E CE%sT +Z Europe/Prague 0:57:44 - LMT 1850 +0:57:44 - PMT 1891 O +1 c CE%sT 1945 May 9 +1 CZ CE%sT 1946 D 1 3 +1 -1 GMT 1947 F 23 2 +1 CZ CE%sT 1979 +1 E CE%sT +Z Europe/Riga 1:36:34 - LMT 1880 +1:36:34 - RMT 1918 Ap 15 2 +1:36:34 1 LST 1918 S 16 3 +1:36:34 - RMT 1919 Ap 1 2 +1:36:34 1 LST 1919 May 22 3 +1:36:34 - RMT 1926 May 11 +2 - EET 1940 Au 5 +3 - MSK 1941 Jul +1 c CE%sT 1944 O 13 +3 R MSK/MSD 1989 Mar lastSu 2s +2 1 EEST 1989 S lastSu 2s +2 LV EE%sT 1997 Ja 21 +2 E EE%sT 2000 F 29 +2 - EET 2001 Ja 2 +2 E EE%sT +Z Europe/Rome 0:49:56 - LMT 1866 D 12 +0:49:56 - RMT 1893 O 31 23u +1 I CE%sT 1943 S 10 +1 c CE%sT 1944 Jun 4 +1 I CE%sT 1980 +1 E CE%sT +Z Europe/Samara 3:20:20 - LMT 1919 Jul 1 0u +3 - %z 1930 Jun 21 +4 - %z 1935 Ja 27 +4 R %z 1989 Mar 26 2s +3 R %z 1991 Mar 31 2s +2 R %z 1991 S 29 2s +3 - %z 1991 O 20 3 +4 R %z 2010 Mar 28 2s +3 R %z 2011 Mar 27 2s +4 - %z +Z Europe/Saratov 3:4:18 - LMT 1919 Jul 1 0u +3 - %z 1930 Jun 21 +4 R %z 1988 Mar 27 2s +3 R %z 1991 Mar 31 2s +4 - %z 1992 Mar 29 2s +3 R %z 2011 Mar 27 2s +4 - %z 2014 O 26 2s +3 - %z 2016 D 4 2s +4 - %z +Z Europe/Simferopol 2:16:24 - LMT 1880 +2:16 - SMT 1924 May 2 +2 - EET 1930 Jun 21 +3 - MSK 1941 N +1 c CE%sT 1944 Ap 13 +3 R MSK/MSD 1990 +3 - MSK 1990 Jul 1 2 +2 - EET 1992 Mar 20 +2 c EE%sT 1994 May +3 c MSK/MSD 1996 Mar 31 0s +3 1 MSD 1996 O 27 3s +3 - MSK 1997 Mar lastSu 1u +2 E EE%sT 2014 Mar 30 2 +4 - MSK 2014 O 26 2s +3 - MSK +Z Europe/Sofia 1:33:16 - LMT 1880 +1:56:56 - IMT 1894 N 30 +2 - EET 1942 N 2 3 +1 c CE%sT 1945 +1 - CET 1945 Ap 2 3 +2 - EET 1979 Mar 31 23 +2 BG EE%sT 1982 S 26 3 +2 c EE%sT 1991 +2 e EE%sT 1997 +2 E EE%sT +Z Europe/Tallinn 1:39 - LMT 1880 +1:39 - TMT 1918 F +1 c CE%sT 1919 Jul +1:39 - TMT 1921 May +2 - EET 1940 Au 6 +3 - MSK 1941 S 15 +1 c CE%sT 1944 S 22 +3 R MSK/MSD 1989 Mar 26 2s +2 1 EEST 1989 S 24 2s +2 c EE%sT 1998 S 22 +2 E EE%sT 1999 O 31 4 +2 - EET 2002 F 21 +2 E EE%sT +Z Europe/Tirane 1:19:20 - LMT 1914 +1 - CET 1940 Jun 16 +1 q CE%sT 1984 Jul +1 E CE%sT +Z Europe/Ulyanovsk 3:13:36 - LMT 1919 Jul 1 0u +3 - %z 1930 Jun 21 +4 R %z 1989 Mar 26 2s +3 R %z 1991 Mar 31 2s +2 R %z 1992 Ja 19 2s +3 R %z 2011 Mar 27 2s +4 - %z 2014 O 26 2s +3 - %z 2016 Mar 27 2s +4 - %z +Z Europe/Vienna 1:5:21 - LMT 1893 Ap +1 c CE%sT 1920 +1 a CE%sT 1940 Ap 1 2s +1 c CE%sT 1945 Ap 2 2s +1 1 CEST 1945 Ap 12 2s +1 - CET 1946 +1 a CE%sT 1981 +1 E CE%sT +Z Europe/Vilnius 1:41:16 - LMT 1880 +1:24 - WMT 1917 +1:35:36 - KMT 1919 O 10 +1 - CET 1920 Jul 12 +2 - EET 1920 O 9 +1 - CET 1940 Au 3 +3 - MSK 1941 Jun 24 +1 c CE%sT 1944 Au +3 R MSK/MSD 1989 Mar 26 2s +2 R EE%sT 1991 S 29 2s +2 c EE%sT 1998 +2 - EET 1998 Mar 29 1u +1 E CE%sT 1999 O 31 1u +2 - EET 2003 +2 E EE%sT +Z Europe/Volgograd 2:57:40 - LMT 1920 Ja 3 +3 - %z 1930 Jun 21 +4 - %z 1961 N 11 +4 R %z 1988 Mar 27 2s +3 R MSK/MSD 1991 Mar 31 2s +4 - %z 1992 Mar 29 2s +3 R MSK/MSD 2011 Mar 27 2s +4 - MSK 2014 O 26 2s +3 - MSK 2018 O 28 2s +4 - %z 2020 D 27 2s +3 - MSK +Z Europe/Warsaw 1:24 - LMT 1880 +1:24 - WMT 1915 Au 5 +1 c CE%sT 1918 S 16 3 +2 O EE%sT 1922 Jun +1 O CE%sT 1940 Jun 23 2 +1 c CE%sT 1944 O +1 O CE%sT 1977 +1 W- CE%sT 1988 +1 E CE%sT +Z Europe/Zurich 0:34:8 - LMT 1853 Jul 16 +0:29:46 - BMT 1894 Jun +1 CH CE%sT 1981 +1 E CE%sT +Z Factory 0 - -00 +Z Indian/Chagos 4:49:40 - LMT 1907 +5 - %z 1996 +6 - %z +Z Indian/Maldives 4:54 - LMT 1880 +4:54 - MMT 1960 +5 - %z +Z Indian/Mauritius 3:50 - LMT 1907 +4 MU %z +Z Pacific/Apia 12:33:4 - LMT 1892 Jul 5 +-11:26:56 - LMT 1911 +-11:30 - %z 1950 +-11 WS %z 2011 D 29 24 +13 WS %z +Z Pacific/Auckland 11:39:4 - LMT 1868 N 2 +11:30 NZ NZ%sT 1946 +12 NZ NZ%sT +Z Pacific/Bougainville 10:22:16 - LMT 1880 +9:48:32 - PMMT 1895 +10 - %z 1942 Jul +9 - %z 1945 Au 21 +10 - %z 2014 D 28 2 +11 - %z +Z Pacific/Chatham 12:13:48 - LMT 1868 N 2 +12:15 - %z 1946 +12:45 k %z +Z Pacific/Easter -7:17:28 - LMT 1890 +-7:17:28 - EMT 1932 S +-7 x %z 1982 Mar 14 3u +-6 x %z +Z Pacific/Efate 11:13:16 - LMT 1912 Ja 13 +11 VU %z +Z Pacific/Fakaofo -11:24:56 - LMT 1901 +-11 - %z 2011 D 30 +13 - %z +Z Pacific/Fiji 11:55:44 - LMT 1915 O 26 +12 FJ %z +Z Pacific/Galapagos -5:58:24 - LMT 1931 +-5 - %z 1986 +-6 EC %z +Z Pacific/Gambier -8:59:48 - LMT 1912 O +-9 - %z +Z Pacific/Guadalcanal 10:39:48 - LMT 1912 O +11 - %z +Z Pacific/Guam -14:21 - LMT 1844 D 31 +9:39 - LMT 1901 +10 - GST 1941 D 10 +9 - %z 1944 Jul 31 +10 Gu G%sT 2000 D 23 +10 - ChST +Z Pacific/Honolulu -10:31:26 - LMT 1896 Ja 13 12 +-10:30 - HST 1933 Ap 30 2 +-10:30 1 HDT 1933 May 21 12 +-10:30 u H%sT 1947 Jun 8 2 +-10 - HST +Z Pacific/Kanton 0 - -00 1937 Au 31 +-12 - %z 1979 O +-11 - %z 1994 D 31 +13 - %z +Z Pacific/Kiritimati -10:29:20 - LMT 1901 +-10:40 - %z 1979 O +-10 - %z 1994 D 31 +14 - %z +Z Pacific/Kosrae -13:8:4 - LMT 1844 D 31 +10:51:56 - LMT 1901 +11 - %z 1914 O +9 - %z 1919 F +11 - %z 1937 +10 - %z 1941 Ap +9 - %z 1945 Au +11 - %z 1969 O +12 - %z 1999 +11 - %z +Z Pacific/Kwajalein 11:9:20 - LMT 1901 +11 - %z 1937 +10 - %z 1941 Ap +9 - %z 1944 F 6 +11 - %z 1969 O +-12 - %z 1993 Au 20 24 +12 - %z +Z Pacific/Marquesas -9:18 - LMT 1912 O +-9:30 - %z +Z Pacific/Nauru 11:7:40 - LMT 1921 Ja 15 +11:30 - %z 1942 Au 29 +9 - %z 1945 S 8 +11:30 - %z 1979 F 10 2 +12 - %z +Z Pacific/Niue -11:19:40 - LMT 1952 O 16 +-11:20 - %z 1964 Jul +-11 - %z +Z Pacific/Norfolk 11:11:52 - LMT 1901 +11:12 - %z 1951 +11:30 - %z 1974 O 27 2s +11:30 1 %z 1975 Mar 2 2s +11:30 - %z 2015 O 4 2s +11 - %z 2019 Jul +11 AN %z +Z Pacific/Noumea 11:5:48 - LMT 1912 Ja 13 +11 NC %z +Z Pacific/Pago_Pago 12:37:12 - LMT 1892 Jul 5 +-11:22:48 - LMT 1911 +-11 - SST +Z Pacific/Palau -15:2:4 - LMT 1844 D 31 +8:57:56 - LMT 1901 +9 - %z +Z Pacific/Pitcairn -8:40:20 - LMT 1901 +-8:30 - %z 1998 Ap 27 +-8 - %z +Z Pacific/Port_Moresby 9:48:40 - LMT 1880 +9:48:32 - PMMT 1895 +10 - %z +Z Pacific/Rarotonga 13:20:56 - LMT 1899 D 26 +-10:39:4 - LMT 1952 O 16 +-10:30 - %z 1978 N 12 +-10 CK %z +Z Pacific/Tahiti -9:58:16 - LMT 1912 O +-10 - %z +Z Pacific/Tarawa 11:32:4 - LMT 1901 +12 - %z +Z Pacific/Tongatapu 12:19:12 - LMT 1945 S 10 +12:20 - %z 1961 +13 - %z 1999 +13 TO %z +L Etc/GMT GMT +L Australia/Sydney Australia/ACT +L Australia/Lord_Howe Australia/LHI +L Australia/Sydney Australia/NSW +L Australia/Darwin Australia/North +L Australia/Brisbane Australia/Queensland +L Australia/Adelaide Australia/South +L Australia/Hobart Australia/Tasmania +L Australia/Melbourne Australia/Victoria +L Australia/Perth Australia/West +L Australia/Broken_Hill Australia/Yancowinna +L America/Rio_Branco Brazil/Acre +L America/Noronha Brazil/DeNoronha +L America/Sao_Paulo Brazil/East +L America/Manaus Brazil/West +L Europe/Brussels CET +L America/Chicago CST6CDT +L America/Halifax Canada/Atlantic +L America/Winnipeg Canada/Central +L America/Toronto Canada/Eastern +L America/Edmonton Canada/Mountain +L America/St_Johns Canada/Newfoundland +L America/Vancouver Canada/Pacific +L America/Regina Canada/Saskatchewan +L America/Whitehorse Canada/Yukon +L America/Santiago Chile/Continental +L Pacific/Easter Chile/EasterIsland +L America/Havana Cuba +L Europe/Athens EET +L America/Panama EST +L America/New_York EST5EDT +L Africa/Cairo Egypt +L Europe/Dublin Eire +L Etc/GMT Etc/GMT+0 +L Etc/GMT Etc/GMT-0 +L Etc/GMT Etc/GMT0 +L Etc/GMT Etc/Greenwich +L Etc/UTC Etc/UCT +L Etc/UTC Etc/Universal +L Etc/UTC Etc/Zulu +L Europe/London GB +L Europe/London GB-Eire +L Etc/GMT GMT+0 +L Etc/GMT GMT-0 +L Etc/GMT GMT0 +L Etc/GMT Greenwich +L Asia/Hong_Kong Hongkong +L Africa/Abidjan Iceland +L Asia/Tehran Iran +L Asia/Jerusalem Israel +L America/Jamaica Jamaica +L Asia/Tokyo Japan +L Pacific/Kwajalein Kwajalein +L Africa/Tripoli Libya +L Europe/Brussels MET +L America/Phoenix MST +L America/Denver MST7MDT +L America/Tijuana Mexico/BajaNorte +L America/Mazatlan Mexico/BajaSur +L America/Mexico_City Mexico/General +L Pacific/Auckland NZ +L Pacific/Chatham NZ-CHAT +L America/Denver Navajo +L Asia/Shanghai PRC +L Europe/Warsaw Poland +L Europe/Lisbon Portugal +L Asia/Taipei ROC +L Asia/Seoul ROK +L Asia/Singapore Singapore +L Europe/Istanbul Turkey +L Etc/UTC UCT +L America/Anchorage US/Alaska +L America/Adak US/Aleutian +L America/Phoenix US/Arizona +L America/Chicago US/Central +L America/Indiana/Indianapolis US/East-Indiana +L America/New_York US/Eastern +L Pacific/Honolulu US/Hawaii +L America/Indiana/Knox US/Indiana-Starke +L America/Detroit US/Michigan +L America/Denver US/Mountain +L America/Los_Angeles US/Pacific +L Pacific/Pago_Pago US/Samoa +L Etc/UTC UTC +L Etc/UTC Universal +L Europe/Moscow W-SU +L Etc/UTC Zulu +L America/Argentina/Buenos_Aires America/Buenos_Aires +L America/Argentina/Catamarca America/Catamarca +L America/Argentina/Cordoba America/Cordoba +L America/Indiana/Indianapolis America/Indianapolis +L America/Argentina/Jujuy America/Jujuy +L America/Indiana/Knox America/Knox_IN +L America/Kentucky/Louisville America/Louisville +L America/Argentina/Mendoza America/Mendoza +L America/Puerto_Rico America/Virgin +L Pacific/Pago_Pago Pacific/Samoa +L Africa/Abidjan Africa/Accra +L Africa/Nairobi Africa/Addis_Ababa +L Africa/Nairobi Africa/Asmara +L Africa/Abidjan Africa/Bamako +L Africa/Lagos Africa/Bangui +L Africa/Abidjan Africa/Banjul +L Africa/Maputo Africa/Blantyre +L Africa/Lagos Africa/Brazzaville +L Africa/Maputo Africa/Bujumbura +L Africa/Abidjan Africa/Conakry +L Africa/Abidjan Africa/Dakar +L Africa/Nairobi Africa/Dar_es_Salaam +L Africa/Nairobi Africa/Djibouti +L Africa/Lagos Africa/Douala +L Africa/Abidjan Africa/Freetown +L Africa/Maputo Africa/Gaborone +L Africa/Maputo Africa/Harare +L Africa/Nairobi Africa/Kampala +L Africa/Maputo Africa/Kigali +L Africa/Lagos Africa/Kinshasa +L Africa/Lagos Africa/Libreville +L Africa/Abidjan Africa/Lome +L Africa/Lagos Africa/Luanda +L Africa/Maputo Africa/Lubumbashi +L Africa/Maputo Africa/Lusaka +L Africa/Lagos Africa/Malabo +L Africa/Johannesburg Africa/Maseru +L Africa/Johannesburg Africa/Mbabane +L Africa/Nairobi Africa/Mogadishu +L Africa/Lagos Africa/Niamey +L Africa/Abidjan Africa/Nouakchott +L Africa/Abidjan Africa/Ouagadougou +L Africa/Lagos Africa/Porto-Novo +L America/Puerto_Rico America/Anguilla +L America/Puerto_Rico America/Antigua +L America/Puerto_Rico America/Aruba +L America/Panama America/Atikokan +L America/Puerto_Rico America/Blanc-Sablon +L America/Panama America/Cayman +L America/Phoenix America/Creston +L America/Puerto_Rico America/Curacao +L America/Puerto_Rico America/Dominica +L America/Puerto_Rico America/Grenada +L America/Puerto_Rico America/Guadeloupe +L America/Puerto_Rico America/Kralendijk +L America/Puerto_Rico America/Lower_Princes +L America/Puerto_Rico America/Marigot +L America/Puerto_Rico America/Montserrat +L America/Toronto America/Nassau +L America/Puerto_Rico America/Port_of_Spain +L America/Puerto_Rico America/St_Barthelemy +L America/Puerto_Rico America/St_Kitts +L America/Puerto_Rico America/St_Lucia +L America/Puerto_Rico America/St_Thomas +L America/Puerto_Rico America/St_Vincent +L America/Puerto_Rico America/Tortola +L Pacific/Port_Moresby Antarctica/DumontDUrville +L Pacific/Auckland Antarctica/McMurdo +L Asia/Riyadh Antarctica/Syowa +L Europe/Berlin Arctic/Longyearbyen +L Asia/Riyadh Asia/Aden +L Asia/Qatar Asia/Bahrain +L Asia/Kuching Asia/Brunei +L Asia/Singapore Asia/Kuala_Lumpur +L Asia/Riyadh Asia/Kuwait +L Asia/Dubai Asia/Muscat +L Asia/Bangkok Asia/Phnom_Penh +L Asia/Bangkok Asia/Vientiane +L Africa/Abidjan Atlantic/Reykjavik +L Africa/Abidjan Atlantic/St_Helena +L Europe/Brussels Europe/Amsterdam +L Europe/Prague Europe/Bratislava +L Europe/Zurich Europe/Busingen +L Europe/Berlin Europe/Copenhagen +L Europe/London Europe/Guernsey +L Europe/London Europe/Isle_of_Man +L Europe/London Europe/Jersey +L Europe/Belgrade Europe/Ljubljana +L Europe/Brussels Europe/Luxembourg +L Europe/Helsinki Europe/Mariehamn +L Europe/Paris Europe/Monaco +L Europe/Berlin Europe/Oslo +L Europe/Belgrade Europe/Podgorica +L Europe/Rome Europe/San_Marino +L Europe/Belgrade Europe/Sarajevo +L Europe/Belgrade Europe/Skopje +L Europe/Berlin Europe/Stockholm +L Europe/Zurich Europe/Vaduz +L Europe/Rome Europe/Vatican +L Europe/Belgrade Europe/Zagreb +L Africa/Nairobi Indian/Antananarivo +L Asia/Bangkok Indian/Christmas +L Asia/Yangon Indian/Cocos +L Africa/Nairobi Indian/Comoro +L Indian/Maldives Indian/Kerguelen +L Asia/Dubai Indian/Mahe +L Africa/Nairobi Indian/Mayotte +L Asia/Dubai Indian/Reunion +L Pacific/Port_Moresby Pacific/Chuuk +L Pacific/Tarawa Pacific/Funafuti +L Pacific/Tarawa Pacific/Majuro +L Pacific/Pago_Pago Pacific/Midway +L Pacific/Guadalcanal Pacific/Pohnpei +L Pacific/Guam Pacific/Saipan +L Pacific/Tarawa Pacific/Wake +L Pacific/Tarawa Pacific/Wallis +L Africa/Abidjan Africa/Timbuktu +L America/Argentina/Catamarca America/Argentina/ComodRivadavia +L America/Adak America/Atka +L America/Panama America/Coral_Harbour +L America/Tijuana America/Ensenada +L America/Indiana/Indianapolis America/Fort_Wayne +L America/Toronto America/Montreal +L America/Toronto America/Nipigon +L America/Iqaluit America/Pangnirtung +L America/Rio_Branco America/Porto_Acre +L America/Winnipeg America/Rainy_River +L America/Argentina/Cordoba America/Rosario +L America/Tijuana America/Santa_Isabel +L America/Denver America/Shiprock +L America/Toronto America/Thunder_Bay +L America/Edmonton America/Yellowknife +L Pacific/Auckland Antarctica/South_Pole +L Asia/Ulaanbaatar Asia/Choibalsan +L Asia/Shanghai Asia/Chongqing +L Asia/Shanghai Asia/Harbin +L Asia/Urumqi Asia/Kashgar +L Asia/Jerusalem Asia/Tel_Aviv +L Europe/Berlin Atlantic/Jan_Mayen +L Australia/Sydney Australia/Canberra +L Australia/Hobart Australia/Currie +L Europe/London Europe/Belfast +L Europe/Chisinau Europe/Tiraspol +L Europe/Kyiv Europe/Uzhgorod +L Europe/Kyiv Europe/Zaporozhye +L Pacific/Kanton Pacific/Enderbury +L Pacific/Honolulu Pacific/Johnston +L Pacific/Port_Moresby Pacific/Yap +L Europe/Lisbon WET +L Africa/Nairobi Africa/Asmera +L America/Nuuk America/Godthab +L Asia/Ashgabat Asia/Ashkhabad +L Asia/Kolkata Asia/Calcutta +L Asia/Shanghai Asia/Chungking +L Asia/Dhaka Asia/Dacca +L Europe/Istanbul Asia/Istanbul +L Asia/Kathmandu Asia/Katmandu +L Asia/Macau Asia/Macao +L Asia/Yangon Asia/Rangoon +L Asia/Ho_Chi_Minh Asia/Saigon +L Asia/Thimphu Asia/Thimbu +L Asia/Makassar Asia/Ujung_Pandang +L Asia/Ulaanbaatar Asia/Ulan_Bator +L Atlantic/Faroe Atlantic/Faeroe +L Europe/Kyiv Europe/Kiev +L Asia/Nicosia Europe/Nicosia +L Pacific/Honolulu HST +L America/Los_Angeles PST8PDT +L Pacific/Guadalcanal Pacific/Ponape +L Pacific/Port_Moresby Pacific/Truk diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/zone.tab b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/zone.tab new file mode 100644 index 0000000000000000000000000000000000000000..2626b0550341a0605087f33cac6952d5fbb24e67 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/zone.tab @@ -0,0 +1,448 @@ +# tzdb timezone descriptions (deprecated version) +# +# This file is in the public domain, so clarified as of +# 2009-05-17 by Arthur David Olson. +# +# From Paul Eggert (2021-09-20): +# This file is intended as a backward-compatibility aid for older programs. +# New programs should use zone1970.tab. This file is like zone1970.tab (see +# zone1970.tab's comments), but with the following additional restrictions: +# +# 1. This file contains only ASCII characters. +# 2. The first data column contains exactly one country code. +# +# Because of (2), each row stands for an area that is the intersection +# of a region identified by a country code and of a timezone where civil +# clocks have agreed since 1970; this is a narrower definition than +# that of zone1970.tab. +# +# Unlike zone1970.tab, a row's third column can be a Link from +# 'backward' instead of a Zone. +# +# This table is intended as an aid for users, to help them select timezones +# appropriate for their practical needs. It is not intended to take or +# endorse any position on legal or territorial claims. +# +#country- +#code coordinates TZ comments +AD +4230+00131 Europe/Andorra +AE +2518+05518 Asia/Dubai +AF +3431+06912 Asia/Kabul +AG +1703-06148 America/Antigua +AI +1812-06304 America/Anguilla +AL +4120+01950 Europe/Tirane +AM +4011+04430 Asia/Yerevan +AO -0848+01314 Africa/Luanda +AQ -7750+16636 Antarctica/McMurdo New Zealand time - McMurdo, South Pole +AQ -6617+11031 Antarctica/Casey Casey +AQ -6835+07758 Antarctica/Davis Davis +AQ -6640+14001 Antarctica/DumontDUrville Dumont-d'Urville +AQ -6736+06253 Antarctica/Mawson Mawson +AQ -6448-06406 Antarctica/Palmer Palmer +AQ -6734-06808 Antarctica/Rothera Rothera +AQ -690022+0393524 Antarctica/Syowa Syowa +AQ -720041+0023206 Antarctica/Troll Troll +AQ -7824+10654 Antarctica/Vostok Vostok +AR -3436-05827 America/Argentina/Buenos_Aires Buenos Aires (BA, CF) +AR -3124-06411 America/Argentina/Cordoba Argentina (most areas: CB, CC, CN, ER, FM, MN, SE, SF) +AR -2447-06525 America/Argentina/Salta Salta (SA, LP, NQ, RN) +AR -2411-06518 America/Argentina/Jujuy Jujuy (JY) +AR -2649-06513 America/Argentina/Tucuman Tucuman (TM) +AR -2828-06547 America/Argentina/Catamarca Catamarca (CT), Chubut (CH) +AR -2926-06651 America/Argentina/La_Rioja La Rioja (LR) +AR -3132-06831 America/Argentina/San_Juan San Juan (SJ) +AR -3253-06849 America/Argentina/Mendoza Mendoza (MZ) +AR -3319-06621 America/Argentina/San_Luis San Luis (SL) +AR -5138-06913 America/Argentina/Rio_Gallegos Santa Cruz (SC) +AR -5448-06818 America/Argentina/Ushuaia Tierra del Fuego (TF) +AS -1416-17042 Pacific/Pago_Pago +AT +4813+01620 Europe/Vienna +AU -3133+15905 Australia/Lord_Howe Lord Howe Island +AU -5430+15857 Antarctica/Macquarie Macquarie Island +AU -4253+14719 Australia/Hobart Tasmania +AU -3749+14458 Australia/Melbourne Victoria +AU -3352+15113 Australia/Sydney New South Wales (most areas) +AU -3157+14127 Australia/Broken_Hill New South Wales (Yancowinna) +AU -2728+15302 Australia/Brisbane Queensland (most areas) +AU -2016+14900 Australia/Lindeman Queensland (Whitsunday Islands) +AU -3455+13835 Australia/Adelaide South Australia +AU -1228+13050 Australia/Darwin Northern Territory +AU -3157+11551 Australia/Perth Western Australia (most areas) +AU -3143+12852 Australia/Eucla Western Australia (Eucla) +AW +1230-06958 America/Aruba +AX +6006+01957 Europe/Mariehamn +AZ +4023+04951 Asia/Baku +BA +4352+01825 Europe/Sarajevo +BB +1306-05937 America/Barbados +BD +2343+09025 Asia/Dhaka +BE +5050+00420 Europe/Brussels +BF +1222-00131 Africa/Ouagadougou +BG +4241+02319 Europe/Sofia +BH +2623+05035 Asia/Bahrain +BI -0323+02922 Africa/Bujumbura +BJ +0629+00237 Africa/Porto-Novo +BL +1753-06251 America/St_Barthelemy +BM +3217-06446 Atlantic/Bermuda +BN +0456+11455 Asia/Brunei +BO -1630-06809 America/La_Paz +BQ +120903-0681636 America/Kralendijk +BR -0351-03225 America/Noronha Atlantic islands +BR -0127-04829 America/Belem Para (east), Amapa +BR -0343-03830 America/Fortaleza Brazil (northeast: MA, PI, CE, RN, PB) +BR -0803-03454 America/Recife Pernambuco +BR -0712-04812 America/Araguaina Tocantins +BR -0940-03543 America/Maceio Alagoas, Sergipe +BR -1259-03831 America/Bahia Bahia +BR -2332-04637 America/Sao_Paulo Brazil (southeast: GO, DF, MG, ES, RJ, SP, PR, SC, RS) +BR -2027-05437 America/Campo_Grande Mato Grosso do Sul +BR -1535-05605 America/Cuiaba Mato Grosso +BR -0226-05452 America/Santarem Para (west) +BR -0846-06354 America/Porto_Velho Rondonia +BR +0249-06040 America/Boa_Vista Roraima +BR -0308-06001 America/Manaus Amazonas (east) +BR -0640-06952 America/Eirunepe Amazonas (west) +BR -0958-06748 America/Rio_Branco Acre +BS +2505-07721 America/Nassau +BT +2728+08939 Asia/Thimphu +BW -2439+02555 Africa/Gaborone +BY +5354+02734 Europe/Minsk +BZ +1730-08812 America/Belize +CA +4734-05243 America/St_Johns Newfoundland, Labrador (SE) +CA +4439-06336 America/Halifax Atlantic - NS (most areas), PE +CA +4612-05957 America/Glace_Bay Atlantic - NS (Cape Breton) +CA +4606-06447 America/Moncton Atlantic - New Brunswick +CA +5320-06025 America/Goose_Bay Atlantic - Labrador (most areas) +CA +5125-05707 America/Blanc-Sablon AST - QC (Lower North Shore) +CA +4339-07923 America/Toronto Eastern - ON & QC (most areas) +CA +6344-06828 America/Iqaluit Eastern - NU (most areas) +CA +484531-0913718 America/Atikokan EST - ON (Atikokan), NU (Coral H) +CA +4953-09709 America/Winnipeg Central - ON (west), Manitoba +CA +744144-0944945 America/Resolute Central - NU (Resolute) +CA +624900-0920459 America/Rankin_Inlet Central - NU (central) +CA +5024-10439 America/Regina CST - SK (most areas) +CA +5017-10750 America/Swift_Current CST - SK (midwest) +CA +5333-11328 America/Edmonton Mountain - AB, BC(E), NT(E), SK(W) +CA +690650-1050310 America/Cambridge_Bay Mountain - NU (west) +CA +682059-1334300 America/Inuvik Mountain - NT (west) +CA +4906-11631 America/Creston MST - BC (Creston) +CA +5546-12014 America/Dawson_Creek MST - BC (Dawson Cr, Ft St John) +CA +5848-12242 America/Fort_Nelson MST - BC (Ft Nelson) +CA +6043-13503 America/Whitehorse MST - Yukon (east) +CA +6404-13925 America/Dawson MST - Yukon (west) +CA +4916-12307 America/Vancouver Pacific - BC (most areas) +CC -1210+09655 Indian/Cocos +CD -0418+01518 Africa/Kinshasa Dem. Rep. of Congo (west) +CD -1140+02728 Africa/Lubumbashi Dem. Rep. of Congo (east) +CF +0422+01835 Africa/Bangui +CG -0416+01517 Africa/Brazzaville +CH +4723+00832 Europe/Zurich +CI +0519-00402 Africa/Abidjan +CK -2114-15946 Pacific/Rarotonga +CL -3327-07040 America/Santiago most of Chile +CL -4534-07204 America/Coyhaique Aysen Region +CL -5309-07055 America/Punta_Arenas Magallanes Region +CL -2709-10926 Pacific/Easter Easter Island +CM +0403+00942 Africa/Douala +CN +3114+12128 Asia/Shanghai Beijing Time +CN +4348+08735 Asia/Urumqi Xinjiang Time +CO +0436-07405 America/Bogota +CR +0956-08405 America/Costa_Rica +CU +2308-08222 America/Havana +CV +1455-02331 Atlantic/Cape_Verde +CW +1211-06900 America/Curacao +CX -1025+10543 Indian/Christmas +CY +3510+03322 Asia/Nicosia most of Cyprus +CY +3507+03357 Asia/Famagusta Northern Cyprus +CZ +5005+01426 Europe/Prague +DE +5230+01322 Europe/Berlin most of Germany +DE +4742+00841 Europe/Busingen Busingen +DJ +1136+04309 Africa/Djibouti +DK +5540+01235 Europe/Copenhagen +DM +1518-06124 America/Dominica +DO +1828-06954 America/Santo_Domingo +DZ +3647+00303 Africa/Algiers +EC -0210-07950 America/Guayaquil Ecuador (mainland) +EC -0054-08936 Pacific/Galapagos Galapagos Islands +EE +5925+02445 Europe/Tallinn +EG +3003+03115 Africa/Cairo +EH +2709-01312 Africa/El_Aaiun +ER +1520+03853 Africa/Asmara +ES +4024-00341 Europe/Madrid Spain (mainland) +ES +3553-00519 Africa/Ceuta Ceuta, Melilla +ES +2806-01524 Atlantic/Canary Canary Islands +ET +0902+03842 Africa/Addis_Ababa +FI +6010+02458 Europe/Helsinki +FJ -1808+17825 Pacific/Fiji +FK -5142-05751 Atlantic/Stanley +FM +0725+15147 Pacific/Chuuk Chuuk/Truk, Yap +FM +0658+15813 Pacific/Pohnpei Pohnpei/Ponape +FM +0519+16259 Pacific/Kosrae Kosrae +FO +6201-00646 Atlantic/Faroe +FR +4852+00220 Europe/Paris +GA +0023+00927 Africa/Libreville +GB +513030-0000731 Europe/London +GD +1203-06145 America/Grenada +GE +4143+04449 Asia/Tbilisi +GF +0456-05220 America/Cayenne +GG +492717-0023210 Europe/Guernsey +GH +0533-00013 Africa/Accra +GI +3608-00521 Europe/Gibraltar +GL +6411-05144 America/Nuuk most of Greenland +GL +7646-01840 America/Danmarkshavn National Park (east coast) +GL +7029-02158 America/Scoresbysund Scoresbysund/Ittoqqortoormiit +GL +7634-06847 America/Thule Thule/Pituffik +GM +1328-01639 Africa/Banjul +GN +0931-01343 Africa/Conakry +GP +1614-06132 America/Guadeloupe +GQ +0345+00847 Africa/Malabo +GR +3758+02343 Europe/Athens +GS -5416-03632 Atlantic/South_Georgia +GT +1438-09031 America/Guatemala +GU +1328+14445 Pacific/Guam +GW +1151-01535 Africa/Bissau +GY +0648-05810 America/Guyana +HK +2217+11409 Asia/Hong_Kong +HN +1406-08713 America/Tegucigalpa +HR +4548+01558 Europe/Zagreb +HT +1832-07220 America/Port-au-Prince +HU +4730+01905 Europe/Budapest +ID -0610+10648 Asia/Jakarta Java, Sumatra +ID -0002+10920 Asia/Pontianak Borneo (west, central) +ID -0507+11924 Asia/Makassar Borneo (east, south), Sulawesi/Celebes, Bali, Nusa Tengarra, Timor (west) +ID -0232+14042 Asia/Jayapura New Guinea (West Papua / Irian Jaya), Malukus/Moluccas +IE +5320-00615 Europe/Dublin +IL +314650+0351326 Asia/Jerusalem +IM +5409-00428 Europe/Isle_of_Man +IN +2232+08822 Asia/Kolkata +IO -0720+07225 Indian/Chagos +IQ +3321+04425 Asia/Baghdad +IR +3540+05126 Asia/Tehran +IS +6409-02151 Atlantic/Reykjavik +IT +4154+01229 Europe/Rome +JE +491101-0020624 Europe/Jersey +JM +175805-0764736 America/Jamaica +JO +3157+03556 Asia/Amman +JP +353916+1394441 Asia/Tokyo +KE -0117+03649 Africa/Nairobi +KG +4254+07436 Asia/Bishkek +KH +1133+10455 Asia/Phnom_Penh +KI +0125+17300 Pacific/Tarawa Gilbert Islands +KI -0247-17143 Pacific/Kanton Phoenix Islands +KI +0152-15720 Pacific/Kiritimati Line Islands +KM -1141+04316 Indian/Comoro +KN +1718-06243 America/St_Kitts +KP +3901+12545 Asia/Pyongyang +KR +3733+12658 Asia/Seoul +KW +2920+04759 Asia/Kuwait +KY +1918-08123 America/Cayman +KZ +4315+07657 Asia/Almaty most of Kazakhstan +KZ +4448+06528 Asia/Qyzylorda Qyzylorda/Kyzylorda/Kzyl-Orda +KZ +5312+06337 Asia/Qostanay Qostanay/Kostanay/Kustanay +KZ +5017+05710 Asia/Aqtobe Aqtobe/Aktobe +KZ +4431+05016 Asia/Aqtau Mangghystau/Mankistau +KZ +4707+05156 Asia/Atyrau Atyrau/Atirau/Gur'yev +KZ +5113+05121 Asia/Oral West Kazakhstan +LA +1758+10236 Asia/Vientiane +LB +3353+03530 Asia/Beirut +LC +1401-06100 America/St_Lucia +LI +4709+00931 Europe/Vaduz +LK +0656+07951 Asia/Colombo +LR +0618-01047 Africa/Monrovia +LS -2928+02730 Africa/Maseru +LT +5441+02519 Europe/Vilnius +LU +4936+00609 Europe/Luxembourg +LV +5657+02406 Europe/Riga +LY +3254+01311 Africa/Tripoli +MA +3339-00735 Africa/Casablanca +MC +4342+00723 Europe/Monaco +MD +4700+02850 Europe/Chisinau +ME +4226+01916 Europe/Podgorica +MF +1804-06305 America/Marigot +MG -1855+04731 Indian/Antananarivo +MH +0709+17112 Pacific/Majuro most of Marshall Islands +MH +0905+16720 Pacific/Kwajalein Kwajalein +MK +4159+02126 Europe/Skopje +ML +1239-00800 Africa/Bamako +MM +1647+09610 Asia/Yangon +MN +4755+10653 Asia/Ulaanbaatar most of Mongolia +MN +4801+09139 Asia/Hovd Bayan-Olgii, Hovd, Uvs +MO +221150+1133230 Asia/Macau +MP +1512+14545 Pacific/Saipan +MQ +1436-06105 America/Martinique +MR +1806-01557 Africa/Nouakchott +MS +1643-06213 America/Montserrat +MT +3554+01431 Europe/Malta +MU -2010+05730 Indian/Mauritius +MV +0410+07330 Indian/Maldives +MW -1547+03500 Africa/Blantyre +MX +1924-09909 America/Mexico_City Central Mexico +MX +2105-08646 America/Cancun Quintana Roo +MX +2058-08937 America/Merida Campeche, Yucatan +MX +2540-10019 America/Monterrey Durango; Coahuila, Nuevo Leon, Tamaulipas (most areas) +MX +2550-09730 America/Matamoros Coahuila, Nuevo Leon, Tamaulipas (US border) +MX +2838-10605 America/Chihuahua Chihuahua (most areas) +MX +3144-10629 America/Ciudad_Juarez Chihuahua (US border - west) +MX +2934-10425 America/Ojinaga Chihuahua (US border - east) +MX +2313-10625 America/Mazatlan Baja California Sur, Nayarit (most areas), Sinaloa +MX +2048-10515 America/Bahia_Banderas Bahia de Banderas +MX +2904-11058 America/Hermosillo Sonora +MX +3232-11701 America/Tijuana Baja California +MY +0310+10142 Asia/Kuala_Lumpur Malaysia (peninsula) +MY +0133+11020 Asia/Kuching Sabah, Sarawak +MZ -2558+03235 Africa/Maputo +NA -2234+01706 Africa/Windhoek +NC -2216+16627 Pacific/Noumea +NE +1331+00207 Africa/Niamey +NF -2903+16758 Pacific/Norfolk +NG +0627+00324 Africa/Lagos +NI +1209-08617 America/Managua +NL +5222+00454 Europe/Amsterdam +NO +5955+01045 Europe/Oslo +NP +2743+08519 Asia/Kathmandu +NR -0031+16655 Pacific/Nauru +NU -1901-16955 Pacific/Niue +NZ -3652+17446 Pacific/Auckland most of New Zealand +NZ -4357-17633 Pacific/Chatham Chatham Islands +OM +2336+05835 Asia/Muscat +PA +0858-07932 America/Panama +PE -1203-07703 America/Lima +PF -1732-14934 Pacific/Tahiti Society Islands +PF -0900-13930 Pacific/Marquesas Marquesas Islands +PF -2308-13457 Pacific/Gambier Gambier Islands +PG -0930+14710 Pacific/Port_Moresby most of Papua New Guinea +PG -0613+15534 Pacific/Bougainville Bougainville +PH +143512+1205804 Asia/Manila +PK +2452+06703 Asia/Karachi +PL +5215+02100 Europe/Warsaw +PM +4703-05620 America/Miquelon +PN -2504-13005 Pacific/Pitcairn +PR +182806-0660622 America/Puerto_Rico +PS +3130+03428 Asia/Gaza Gaza Strip +PS +313200+0350542 Asia/Hebron West Bank +PT +3843-00908 Europe/Lisbon Portugal (mainland) +PT +3238-01654 Atlantic/Madeira Madeira Islands +PT +3744-02540 Atlantic/Azores Azores +PW +0720+13429 Pacific/Palau +PY -2516-05740 America/Asuncion +QA +2517+05132 Asia/Qatar +RE -2052+05528 Indian/Reunion +RO +4426+02606 Europe/Bucharest +RS +4450+02030 Europe/Belgrade +RU +5443+02030 Europe/Kaliningrad MSK-01 - Kaliningrad +RU +554521+0373704 Europe/Moscow MSK+00 - Moscow area +# The obsolescent zone.tab format cannot represent Europe/Simferopol well. +# Put it in RU section and list as UA. See "territorial claims" above. +# Programs should use zone1970.tab instead; see above. +UA +4457+03406 Europe/Simferopol Crimea +RU +5836+04939 Europe/Kirov MSK+00 - Kirov +RU +4844+04425 Europe/Volgograd MSK+00 - Volgograd +RU +4621+04803 Europe/Astrakhan MSK+01 - Astrakhan +RU +5134+04602 Europe/Saratov MSK+01 - Saratov +RU +5420+04824 Europe/Ulyanovsk MSK+01 - Ulyanovsk +RU +5312+05009 Europe/Samara MSK+01 - Samara, Udmurtia +RU +5651+06036 Asia/Yekaterinburg MSK+02 - Urals +RU +5500+07324 Asia/Omsk MSK+03 - Omsk +RU +5502+08255 Asia/Novosibirsk MSK+04 - Novosibirsk +RU +5322+08345 Asia/Barnaul MSK+04 - Altai +RU +5630+08458 Asia/Tomsk MSK+04 - Tomsk +RU +5345+08707 Asia/Novokuznetsk MSK+04 - Kemerovo +RU +5601+09250 Asia/Krasnoyarsk MSK+04 - Krasnoyarsk area +RU +5216+10420 Asia/Irkutsk MSK+05 - Irkutsk, Buryatia +RU +5203+11328 Asia/Chita MSK+06 - Zabaykalsky +RU +6200+12940 Asia/Yakutsk MSK+06 - Lena River +RU +623923+1353314 Asia/Khandyga MSK+06 - Tomponsky, Ust-Maysky +RU +4310+13156 Asia/Vladivostok MSK+07 - Amur River +RU +643337+1431336 Asia/Ust-Nera MSK+07 - Oymyakonsky +RU +5934+15048 Asia/Magadan MSK+08 - Magadan +RU +4658+14242 Asia/Sakhalin MSK+08 - Sakhalin Island +RU +6728+15343 Asia/Srednekolymsk MSK+08 - Sakha (E), N Kuril Is +RU +5301+15839 Asia/Kamchatka MSK+09 - Kamchatka +RU +6445+17729 Asia/Anadyr MSK+09 - Bering Sea +RW -0157+03004 Africa/Kigali +SA +2438+04643 Asia/Riyadh +SB -0932+16012 Pacific/Guadalcanal +SC -0440+05528 Indian/Mahe +SD +1536+03232 Africa/Khartoum +SE +5920+01803 Europe/Stockholm +SG +0117+10351 Asia/Singapore +SH -1555-00542 Atlantic/St_Helena +SI +4603+01431 Europe/Ljubljana +SJ +7800+01600 Arctic/Longyearbyen +SK +4809+01707 Europe/Bratislava +SL +0830-01315 Africa/Freetown +SM +4355+01228 Europe/San_Marino +SN +1440-01726 Africa/Dakar +SO +0204+04522 Africa/Mogadishu +SR +0550-05510 America/Paramaribo +SS +0451+03137 Africa/Juba +ST +0020+00644 Africa/Sao_Tome +SV +1342-08912 America/El_Salvador +SX +180305-0630250 America/Lower_Princes +SY +3330+03618 Asia/Damascus +SZ -2618+03106 Africa/Mbabane +TC +2128-07108 America/Grand_Turk +TD +1207+01503 Africa/Ndjamena +TF -492110+0701303 Indian/Kerguelen +TG +0608+00113 Africa/Lome +TH +1345+10031 Asia/Bangkok +TJ +3835+06848 Asia/Dushanbe +TK -0922-17114 Pacific/Fakaofo +TL -0833+12535 Asia/Dili +TM +3757+05823 Asia/Ashgabat +TN +3648+01011 Africa/Tunis +TO -210800-1751200 Pacific/Tongatapu +TR +4101+02858 Europe/Istanbul +TT +1039-06131 America/Port_of_Spain +TV -0831+17913 Pacific/Funafuti +TW +2503+12130 Asia/Taipei +TZ -0648+03917 Africa/Dar_es_Salaam +UA +5026+03031 Europe/Kyiv most of Ukraine +UG +0019+03225 Africa/Kampala +UM +2813-17722 Pacific/Midway Midway Islands +UM +1917+16637 Pacific/Wake Wake Island +US +404251-0740023 America/New_York Eastern (most areas) +US +421953-0830245 America/Detroit Eastern - MI (most areas) +US +381515-0854534 America/Kentucky/Louisville Eastern - KY (Louisville area) +US +364947-0845057 America/Kentucky/Monticello Eastern - KY (Wayne) +US +394606-0860929 America/Indiana/Indianapolis Eastern - IN (most areas) +US +384038-0873143 America/Indiana/Vincennes Eastern - IN (Da, Du, K, Mn) +US +410305-0863611 America/Indiana/Winamac Eastern - IN (Pulaski) +US +382232-0862041 America/Indiana/Marengo Eastern - IN (Crawford) +US +382931-0871643 America/Indiana/Petersburg Eastern - IN (Pike) +US +384452-0850402 America/Indiana/Vevay Eastern - IN (Switzerland) +US +415100-0873900 America/Chicago Central (most areas) +US +375711-0864541 America/Indiana/Tell_City Central - IN (Perry) +US +411745-0863730 America/Indiana/Knox Central - IN (Starke) +US +450628-0873651 America/Menominee Central - MI (Wisconsin border) +US +470659-1011757 America/North_Dakota/Center Central - ND (Oliver) +US +465042-1012439 America/North_Dakota/New_Salem Central - ND (Morton rural) +US +471551-1014640 America/North_Dakota/Beulah Central - ND (Mercer) +US +394421-1045903 America/Denver Mountain (most areas) +US +433649-1161209 America/Boise Mountain - ID (south), OR (east) +US +332654-1120424 America/Phoenix MST - AZ (except Navajo) +US +340308-1181434 America/Los_Angeles Pacific +US +611305-1495401 America/Anchorage Alaska (most areas) +US +581807-1342511 America/Juneau Alaska - Juneau area +US +571035-1351807 America/Sitka Alaska - Sitka area +US +550737-1313435 America/Metlakatla Alaska - Annette Island +US +593249-1394338 America/Yakutat Alaska - Yakutat +US +643004-1652423 America/Nome Alaska (west) +US +515248-1763929 America/Adak Alaska - western Aleutians +US +211825-1575130 Pacific/Honolulu Hawaii +UY -345433-0561245 America/Montevideo +UZ +3940+06648 Asia/Samarkand Uzbekistan (west) +UZ +4120+06918 Asia/Tashkent Uzbekistan (east) +VA +415408+0122711 Europe/Vatican +VC +1309-06114 America/St_Vincent +VE +1030-06656 America/Caracas +VG +1827-06437 America/Tortola +VI +1821-06456 America/St_Thomas +VN +1045+10640 Asia/Ho_Chi_Minh +VU -1740+16825 Pacific/Efate +WF -1318-17610 Pacific/Wallis +WS -1350-17144 Pacific/Apia +YE +1245+04512 Asia/Aden +YT -1247+04514 Indian/Mayotte +ZA -2615+02800 Africa/Johannesburg +ZM -1525+02817 Africa/Lusaka +ZW -1750+03103 Africa/Harare diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/zone1970.tab b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/zone1970.tab new file mode 100644 index 0000000000000000000000000000000000000000..36535bdf5cfbdedfc70b4d7899de7351b8eb5070 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/zone1970.tab @@ -0,0 +1,375 @@ +# tzdb timezone descriptions +# +# This file is in the public domain. +# +# From Paul Eggert (2018-06-27): +# This file contains a table where each row stands for a timezone where +# civil timestamps have agreed since 1970. Columns are separated by +# a single tab. Lines beginning with '#' are comments. All text uses +# UTF-8 encoding. The columns of the table are as follows: +# +# 1. The countries that overlap the timezone, as a comma-separated list +# of ISO 3166 2-character country codes. See the file 'iso3166.tab'. +# 2. Latitude and longitude of the timezone's principal location +# in ISO 6709 sign-degrees-minutes-seconds format, +# either ±DDMM±DDDMM or ±DDMMSS±DDDMMSS, +# first latitude (+ is north), then longitude (+ is east). +# 3. Timezone name used in value of TZ environment variable. +# Please see the theory.html file for how these names are chosen. +# If multiple timezones overlap a country, each has a row in the +# table, with each column 1 containing the country code. +# 4. Comments; present if and only if countries have multiple timezones, +# and useful only for those countries. For example, the comments +# for the row with countries CH,DE,LI and name Europe/Zurich +# are useful only for DE, since CH and LI have no other timezones. +# +# If a timezone covers multiple countries, the most-populous city is used, +# and that country is listed first in column 1; any other countries +# are listed alphabetically by country code. The table is sorted +# first by country code, then (if possible) by an order within the +# country that (1) makes some geographical sense, and (2) puts the +# most populous timezones first, where that does not contradict (1). +# +# This table is intended as an aid for users, to help them select timezones +# appropriate for their practical needs. It is not intended to take or +# endorse any position on legal or territorial claims. +# +#country- +#codes coordinates TZ comments +AD +4230+00131 Europe/Andorra +AE,OM,RE,SC,TF +2518+05518 Asia/Dubai Crozet +AF +3431+06912 Asia/Kabul +AL +4120+01950 Europe/Tirane +AM +4011+04430 Asia/Yerevan +AQ -6617+11031 Antarctica/Casey Casey +AQ -6835+07758 Antarctica/Davis Davis +AQ -6736+06253 Antarctica/Mawson Mawson +AQ -6448-06406 Antarctica/Palmer Palmer +AQ -6734-06808 Antarctica/Rothera Rothera +AQ -720041+0023206 Antarctica/Troll Troll +AQ -7824+10654 Antarctica/Vostok Vostok +AR -3436-05827 America/Argentina/Buenos_Aires Buenos Aires (BA, CF) +AR -3124-06411 America/Argentina/Cordoba most areas: CB, CC, CN, ER, FM, MN, SE, SF +AR -2447-06525 America/Argentina/Salta Salta (SA, LP, NQ, RN) +AR -2411-06518 America/Argentina/Jujuy Jujuy (JY) +AR -2649-06513 America/Argentina/Tucuman Tucumán (TM) +AR -2828-06547 America/Argentina/Catamarca Catamarca (CT), Chubut (CH) +AR -2926-06651 America/Argentina/La_Rioja La Rioja (LR) +AR -3132-06831 America/Argentina/San_Juan San Juan (SJ) +AR -3253-06849 America/Argentina/Mendoza Mendoza (MZ) +AR -3319-06621 America/Argentina/San_Luis San Luis (SL) +AR -5138-06913 America/Argentina/Rio_Gallegos Santa Cruz (SC) +AR -5448-06818 America/Argentina/Ushuaia Tierra del Fuego (TF) +AS,UM -1416-17042 Pacific/Pago_Pago Midway +AT +4813+01620 Europe/Vienna +AU -3133+15905 Australia/Lord_Howe Lord Howe Island +AU -5430+15857 Antarctica/Macquarie Macquarie Island +AU -4253+14719 Australia/Hobart Tasmania +AU -3749+14458 Australia/Melbourne Victoria +AU -3352+15113 Australia/Sydney New South Wales (most areas) +AU -3157+14127 Australia/Broken_Hill New South Wales (Yancowinna) +AU -2728+15302 Australia/Brisbane Queensland (most areas) +AU -2016+14900 Australia/Lindeman Queensland (Whitsunday Islands) +AU -3455+13835 Australia/Adelaide South Australia +AU -1228+13050 Australia/Darwin Northern Territory +AU -3157+11551 Australia/Perth Western Australia (most areas) +AU -3143+12852 Australia/Eucla Western Australia (Eucla) +AZ +4023+04951 Asia/Baku +BB +1306-05937 America/Barbados +BD +2343+09025 Asia/Dhaka +BE,LU,NL +5050+00420 Europe/Brussels +BG +4241+02319 Europe/Sofia +BM +3217-06446 Atlantic/Bermuda +BO -1630-06809 America/La_Paz +BR -0351-03225 America/Noronha Atlantic islands +BR -0127-04829 America/Belem Pará (east), Amapá +BR -0343-03830 America/Fortaleza Brazil (northeast: MA, PI, CE, RN, PB) +BR -0803-03454 America/Recife Pernambuco +BR -0712-04812 America/Araguaina Tocantins +BR -0940-03543 America/Maceio Alagoas, Sergipe +BR -1259-03831 America/Bahia Bahia +BR -2332-04637 America/Sao_Paulo Brazil (southeast: GO, DF, MG, ES, RJ, SP, PR, SC, RS) +BR -2027-05437 America/Campo_Grande Mato Grosso do Sul +BR -1535-05605 America/Cuiaba Mato Grosso +BR -0226-05452 America/Santarem Pará (west) +BR -0846-06354 America/Porto_Velho Rondônia +BR +0249-06040 America/Boa_Vista Roraima +BR -0308-06001 America/Manaus Amazonas (east) +BR -0640-06952 America/Eirunepe Amazonas (west) +BR -0958-06748 America/Rio_Branco Acre +BT +2728+08939 Asia/Thimphu +BY +5354+02734 Europe/Minsk +BZ +1730-08812 America/Belize +CA +4734-05243 America/St_Johns Newfoundland, Labrador (SE) +CA +4439-06336 America/Halifax Atlantic - NS (most areas), PE +CA +4612-05957 America/Glace_Bay Atlantic - NS (Cape Breton) +CA +4606-06447 America/Moncton Atlantic - New Brunswick +CA +5320-06025 America/Goose_Bay Atlantic - Labrador (most areas) +CA,BS +4339-07923 America/Toronto Eastern - ON & QC (most areas) +CA +6344-06828 America/Iqaluit Eastern - NU (most areas) +CA +4953-09709 America/Winnipeg Central - ON (west), Manitoba +CA +744144-0944945 America/Resolute Central - NU (Resolute) +CA +624900-0920459 America/Rankin_Inlet Central - NU (central) +CA +5024-10439 America/Regina CST - SK (most areas) +CA +5017-10750 America/Swift_Current CST - SK (midwest) +CA +5333-11328 America/Edmonton Mountain - AB, BC(E), NT(E), SK(W) +CA +690650-1050310 America/Cambridge_Bay Mountain - NU (west) +CA +682059-1334300 America/Inuvik Mountain - NT (west) +CA +5546-12014 America/Dawson_Creek MST - BC (Dawson Cr, Ft St John) +CA +5848-12242 America/Fort_Nelson MST - BC (Ft Nelson) +CA +6043-13503 America/Whitehorse MST - Yukon (east) +CA +6404-13925 America/Dawson MST - Yukon (west) +CA +4916-12307 America/Vancouver Pacific - BC (most areas) +CH,DE,LI +4723+00832 Europe/Zurich Büsingen +CI,BF,GH,GM,GN,IS,ML,MR,SH,SL,SN,TG +0519-00402 Africa/Abidjan +CK -2114-15946 Pacific/Rarotonga +CL -3327-07040 America/Santiago most of Chile +CL -4534-07204 America/Coyhaique Aysén Region +CL -5309-07055 America/Punta_Arenas Magallanes Region +CL -2709-10926 Pacific/Easter Easter Island +CN +3114+12128 Asia/Shanghai Beijing Time +CN +4348+08735 Asia/Urumqi Xinjiang Time +CO +0436-07405 America/Bogota +CR +0956-08405 America/Costa_Rica +CU +2308-08222 America/Havana +CV +1455-02331 Atlantic/Cape_Verde +CY +3510+03322 Asia/Nicosia most of Cyprus +CY +3507+03357 Asia/Famagusta Northern Cyprus +CZ,SK +5005+01426 Europe/Prague +DE,DK,NO,SE,SJ +5230+01322 Europe/Berlin most of Germany +DO +1828-06954 America/Santo_Domingo +DZ +3647+00303 Africa/Algiers +EC -0210-07950 America/Guayaquil Ecuador (mainland) +EC -0054-08936 Pacific/Galapagos Galápagos Islands +EE +5925+02445 Europe/Tallinn +EG +3003+03115 Africa/Cairo +EH +2709-01312 Africa/El_Aaiun +ES +4024-00341 Europe/Madrid Spain (mainland) +ES +3553-00519 Africa/Ceuta Ceuta, Melilla +ES +2806-01524 Atlantic/Canary Canary Islands +FI,AX +6010+02458 Europe/Helsinki +FJ -1808+17825 Pacific/Fiji +FK -5142-05751 Atlantic/Stanley +FM +0519+16259 Pacific/Kosrae Kosrae +FO +6201-00646 Atlantic/Faroe +FR,MC +4852+00220 Europe/Paris +GB,GG,IM,JE +513030-0000731 Europe/London +GE +4143+04449 Asia/Tbilisi +GF +0456-05220 America/Cayenne +GI +3608-00521 Europe/Gibraltar +GL +6411-05144 America/Nuuk most of Greenland +GL +7646-01840 America/Danmarkshavn National Park (east coast) +GL +7029-02158 America/Scoresbysund Scoresbysund/Ittoqqortoormiit +GL +7634-06847 America/Thule Thule/Pituffik +GR +3758+02343 Europe/Athens +GS -5416-03632 Atlantic/South_Georgia +GT +1438-09031 America/Guatemala +GU,MP +1328+14445 Pacific/Guam +GW +1151-01535 Africa/Bissau +GY +0648-05810 America/Guyana +HK +2217+11409 Asia/Hong_Kong +HN +1406-08713 America/Tegucigalpa +HT +1832-07220 America/Port-au-Prince +HU +4730+01905 Europe/Budapest +ID -0610+10648 Asia/Jakarta Java, Sumatra +ID -0002+10920 Asia/Pontianak Borneo (west, central) +ID -0507+11924 Asia/Makassar Borneo (east, south), Sulawesi/Celebes, Bali, Nusa Tengarra, Timor (west) +ID -0232+14042 Asia/Jayapura New Guinea (West Papua / Irian Jaya), Malukus/Moluccas +IE +5320-00615 Europe/Dublin +IL +314650+0351326 Asia/Jerusalem +IN +2232+08822 Asia/Kolkata +IO -0720+07225 Indian/Chagos +IQ +3321+04425 Asia/Baghdad +IR +3540+05126 Asia/Tehran +IT,SM,VA +4154+01229 Europe/Rome +JM +175805-0764736 America/Jamaica +JO +3157+03556 Asia/Amman +JP,AU +353916+1394441 Asia/Tokyo Eyre Bird Observatory +KE,DJ,ER,ET,KM,MG,SO,TZ,UG,YT -0117+03649 Africa/Nairobi +KG +4254+07436 Asia/Bishkek +KI,MH,TV,UM,WF +0125+17300 Pacific/Tarawa Gilberts, Marshalls, Wake +KI -0247-17143 Pacific/Kanton Phoenix Islands +KI +0152-15720 Pacific/Kiritimati Line Islands +KP +3901+12545 Asia/Pyongyang +KR +3733+12658 Asia/Seoul +KZ +4315+07657 Asia/Almaty most of Kazakhstan +KZ +4448+06528 Asia/Qyzylorda Qyzylorda/Kyzylorda/Kzyl-Orda +KZ +5312+06337 Asia/Qostanay Qostanay/Kostanay/Kustanay +KZ +5017+05710 Asia/Aqtobe Aqtöbe/Aktobe +KZ +4431+05016 Asia/Aqtau Mangghystaū/Mankistau +KZ +4707+05156 Asia/Atyrau Atyraū/Atirau/Gur'yev +KZ +5113+05121 Asia/Oral West Kazakhstan +LB +3353+03530 Asia/Beirut +LK +0656+07951 Asia/Colombo +LR +0618-01047 Africa/Monrovia +LT +5441+02519 Europe/Vilnius +LV +5657+02406 Europe/Riga +LY +3254+01311 Africa/Tripoli +MA +3339-00735 Africa/Casablanca +MD +4700+02850 Europe/Chisinau +MH +0905+16720 Pacific/Kwajalein Kwajalein +MM,CC +1647+09610 Asia/Yangon +MN +4755+10653 Asia/Ulaanbaatar most of Mongolia +MN +4801+09139 Asia/Hovd Bayan-Ölgii, Hovd, Uvs +MO +221150+1133230 Asia/Macau +MQ +1436-06105 America/Martinique +MT +3554+01431 Europe/Malta +MU -2010+05730 Indian/Mauritius +MV,TF +0410+07330 Indian/Maldives Kerguelen, St Paul I, Amsterdam I +MX +1924-09909 America/Mexico_City Central Mexico +MX +2105-08646 America/Cancun Quintana Roo +MX +2058-08937 America/Merida Campeche, Yucatán +MX +2540-10019 America/Monterrey Durango; Coahuila, Nuevo León, Tamaulipas (most areas) +MX +2550-09730 America/Matamoros Coahuila, Nuevo León, Tamaulipas (US border) +MX +2838-10605 America/Chihuahua Chihuahua (most areas) +MX +3144-10629 America/Ciudad_Juarez Chihuahua (US border - west) +MX +2934-10425 America/Ojinaga Chihuahua (US border - east) +MX +2313-10625 America/Mazatlan Baja California Sur, Nayarit (most areas), Sinaloa +MX +2048-10515 America/Bahia_Banderas Bahía de Banderas +MX +2904-11058 America/Hermosillo Sonora +MX +3232-11701 America/Tijuana Baja California +MY,BN +0133+11020 Asia/Kuching Sabah, Sarawak +MZ,BI,BW,CD,MW,RW,ZM,ZW -2558+03235 Africa/Maputo Central Africa Time +NA -2234+01706 Africa/Windhoek +NC -2216+16627 Pacific/Noumea +NF -2903+16758 Pacific/Norfolk +NG,AO,BJ,CD,CF,CG,CM,GA,GQ,NE +0627+00324 Africa/Lagos West Africa Time +NI +1209-08617 America/Managua +NP +2743+08519 Asia/Kathmandu +NR -0031+16655 Pacific/Nauru +NU -1901-16955 Pacific/Niue +NZ,AQ -3652+17446 Pacific/Auckland New Zealand time +NZ -4357-17633 Pacific/Chatham Chatham Islands +PA,CA,KY +0858-07932 America/Panama EST - ON (Atikokan), NU (Coral H) +PE -1203-07703 America/Lima +PF -1732-14934 Pacific/Tahiti Society Islands +PF -0900-13930 Pacific/Marquesas Marquesas Islands +PF -2308-13457 Pacific/Gambier Gambier Islands +PG,AQ,FM -0930+14710 Pacific/Port_Moresby Papua New Guinea (most areas), Chuuk, Yap, Dumont d'Urville +PG -0613+15534 Pacific/Bougainville Bougainville +PH +143512+1205804 Asia/Manila +PK +2452+06703 Asia/Karachi +PL +5215+02100 Europe/Warsaw +PM +4703-05620 America/Miquelon +PN -2504-13005 Pacific/Pitcairn +PR,AG,CA,AI,AW,BL,BQ,CW,DM,GD,GP,KN,LC,MF,MS,SX,TT,VC,VG,VI +182806-0660622 America/Puerto_Rico AST - QC (Lower North Shore) +PS +3130+03428 Asia/Gaza Gaza Strip +PS +313200+0350542 Asia/Hebron West Bank +PT +3843-00908 Europe/Lisbon Portugal (mainland) +PT +3238-01654 Atlantic/Madeira Madeira Islands +PT +3744-02540 Atlantic/Azores Azores +PW +0720+13429 Pacific/Palau +PY -2516-05740 America/Asuncion +QA,BH +2517+05132 Asia/Qatar +RO +4426+02606 Europe/Bucharest +RS,BA,HR,ME,MK,SI +4450+02030 Europe/Belgrade +RU +5443+02030 Europe/Kaliningrad MSK-01 - Kaliningrad +RU +554521+0373704 Europe/Moscow MSK+00 - Moscow area +# Mention RU and UA alphabetically. See "territorial claims" above. +RU,UA +4457+03406 Europe/Simferopol Crimea +RU +5836+04939 Europe/Kirov MSK+00 - Kirov +RU +4844+04425 Europe/Volgograd MSK+00 - Volgograd +RU +4621+04803 Europe/Astrakhan MSK+01 - Astrakhan +RU +5134+04602 Europe/Saratov MSK+01 - Saratov +RU +5420+04824 Europe/Ulyanovsk MSK+01 - Ulyanovsk +RU +5312+05009 Europe/Samara MSK+01 - Samara, Udmurtia +RU +5651+06036 Asia/Yekaterinburg MSK+02 - Urals +RU +5500+07324 Asia/Omsk MSK+03 - Omsk +RU +5502+08255 Asia/Novosibirsk MSK+04 - Novosibirsk +RU +5322+08345 Asia/Barnaul MSK+04 - Altai +RU +5630+08458 Asia/Tomsk MSK+04 - Tomsk +RU +5345+08707 Asia/Novokuznetsk MSK+04 - Kemerovo +RU +5601+09250 Asia/Krasnoyarsk MSK+04 - Krasnoyarsk area +RU +5216+10420 Asia/Irkutsk MSK+05 - Irkutsk, Buryatia +RU +5203+11328 Asia/Chita MSK+06 - Zabaykalsky +RU +6200+12940 Asia/Yakutsk MSK+06 - Lena River +RU +623923+1353314 Asia/Khandyga MSK+06 - Tomponsky, Ust-Maysky +RU +4310+13156 Asia/Vladivostok MSK+07 - Amur River +RU +643337+1431336 Asia/Ust-Nera MSK+07 - Oymyakonsky +RU +5934+15048 Asia/Magadan MSK+08 - Magadan +RU +4658+14242 Asia/Sakhalin MSK+08 - Sakhalin Island +RU +6728+15343 Asia/Srednekolymsk MSK+08 - Sakha (E), N Kuril Is +RU +5301+15839 Asia/Kamchatka MSK+09 - Kamchatka +RU +6445+17729 Asia/Anadyr MSK+09 - Bering Sea +SA,AQ,KW,YE +2438+04643 Asia/Riyadh Syowa +SB,FM -0932+16012 Pacific/Guadalcanal Pohnpei +SD +1536+03232 Africa/Khartoum +SG,AQ,MY +0117+10351 Asia/Singapore peninsular Malaysia, Concordia +SR +0550-05510 America/Paramaribo +SS +0451+03137 Africa/Juba +ST +0020+00644 Africa/Sao_Tome +SV +1342-08912 America/El_Salvador +SY +3330+03618 Asia/Damascus +TC +2128-07108 America/Grand_Turk +TD +1207+01503 Africa/Ndjamena +TH,CX,KH,LA,VN +1345+10031 Asia/Bangkok north Vietnam +TJ +3835+06848 Asia/Dushanbe +TK -0922-17114 Pacific/Fakaofo +TL -0833+12535 Asia/Dili +TM +3757+05823 Asia/Ashgabat +TN +3648+01011 Africa/Tunis +TO -210800-1751200 Pacific/Tongatapu +TR +4101+02858 Europe/Istanbul +TW +2503+12130 Asia/Taipei +UA +5026+03031 Europe/Kyiv most of Ukraine +US +404251-0740023 America/New_York Eastern (most areas) +US +421953-0830245 America/Detroit Eastern - MI (most areas) +US +381515-0854534 America/Kentucky/Louisville Eastern - KY (Louisville area) +US +364947-0845057 America/Kentucky/Monticello Eastern - KY (Wayne) +US +394606-0860929 America/Indiana/Indianapolis Eastern - IN (most areas) +US +384038-0873143 America/Indiana/Vincennes Eastern - IN (Da, Du, K, Mn) +US +410305-0863611 America/Indiana/Winamac Eastern - IN (Pulaski) +US +382232-0862041 America/Indiana/Marengo Eastern - IN (Crawford) +US +382931-0871643 America/Indiana/Petersburg Eastern - IN (Pike) +US +384452-0850402 America/Indiana/Vevay Eastern - IN (Switzerland) +US +415100-0873900 America/Chicago Central (most areas) +US +375711-0864541 America/Indiana/Tell_City Central - IN (Perry) +US +411745-0863730 America/Indiana/Knox Central - IN (Starke) +US +450628-0873651 America/Menominee Central - MI (Wisconsin border) +US +470659-1011757 America/North_Dakota/Center Central - ND (Oliver) +US +465042-1012439 America/North_Dakota/New_Salem Central - ND (Morton rural) +US +471551-1014640 America/North_Dakota/Beulah Central - ND (Mercer) +US +394421-1045903 America/Denver Mountain (most areas) +US +433649-1161209 America/Boise Mountain - ID (south), OR (east) +US,CA +332654-1120424 America/Phoenix MST - AZ (most areas), Creston BC +US +340308-1181434 America/Los_Angeles Pacific +US +611305-1495401 America/Anchorage Alaska (most areas) +US +581807-1342511 America/Juneau Alaska - Juneau area +US +571035-1351807 America/Sitka Alaska - Sitka area +US +550737-1313435 America/Metlakatla Alaska - Annette Island +US +593249-1394338 America/Yakutat Alaska - Yakutat +US +643004-1652423 America/Nome Alaska (west) +US +515248-1763929 America/Adak Alaska - western Aleutians +US +211825-1575130 Pacific/Honolulu Hawaii +UY -345433-0561245 America/Montevideo +UZ +3940+06648 Asia/Samarkand Uzbekistan (west) +UZ +4120+06918 Asia/Tashkent Uzbekistan (east) +VE +1030-06656 America/Caracas +VN +1045+10640 Asia/Ho_Chi_Minh south Vietnam +VU -1740+16825 Pacific/Efate +WS -1350-17144 Pacific/Apia +ZA,LS,SZ -2615+02800 Africa/Johannesburg +# +# The next section contains experimental tab-separated comments for +# use by user agents like tzselect that identify continents and oceans. +# +# For example, the comment "#@AQAntarctica/" means the country code +# AQ is in the continent Antarctica regardless of the Zone name, +# so Pacific/Auckland should be listed under Antarctica as well as +# under the Pacific because its line's country codes include AQ. +# +# If more than one country code is affected each is listed separated +# by commas, e.g., #@IS,SHAtlantic/". If a country code is in +# more than one continent or ocean, each is listed separated by +# commas, e.g., the second column of "#@CY,TRAsia/,Europe/". +# +# These experimental comments are present only for country codes where +# the continent or ocean is not already obvious from the Zone name. +# For example, there is no such comment for RU since it already +# corresponds to Zone names starting with both "Europe/" and "Asia/". +# +#@AQ Antarctica/ +#@IS,SH Atlantic/ +#@CY,TR Asia/,Europe/ +#@SJ Arctic/ +#@CC,CX,KM,MG,YT Indian/ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/zonenow.tab b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/zonenow.tab new file mode 100644 index 0000000000000000000000000000000000000000..093f0a0cb7495b5d50751bc0cb5b22df4a67c763 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zoneinfo/zonenow.tab @@ -0,0 +1,296 @@ +# tzdb timezone descriptions, for users who do not care about old timestamps +# +# This file is in the public domain. +# +# From Paul Eggert (2023-12-18): +# This file contains a table where each row stands for a timezone +# where civil timestamps are predicted to agree from now on. +# This file is like zone1970.tab (see zone1970.tab's comments), +# but with the following changes: +# +# 1. Each timezone corresponds to a set of clocks that are planned +# to agree from now on. This is a larger set of clocks than in +# zone1970.tab, where each timezone's clocks must agree from 1970 on. +# 2. The first column is irrelevant and ignored. +# 3. The table is sorted in a different way: +# first by standard time UTC offset; +# then, if DST is used, by daylight saving UTC offset; +# then by time zone abbreviation. +# 4. Every timezone has a nonempty comments column, with wording +# distinguishing the timezone only from other timezones with the +# same UTC offset at some point during the year. +# +# The format of this table is experimental, and may change in future versions. +# +# This table is intended as an aid for users, to help them select timezones +# appropriate for their practical needs. It is not intended to take or +# endorse any position on legal or territorial claims. +# +#XX coordinates TZ comments +# +# -11 - SST +XX -1416-17042 Pacific/Pago_Pago Midway; Samoa ("SST") +# +# -11 +XX -1901-16955 Pacific/Niue Niue +# +# -10 - HST +XX +211825-1575130 Pacific/Honolulu Hawaii ("HST") +# +# -10 +XX -1732-14934 Pacific/Tahiti Tahiti; Cook Islands +# +# -10/-09 - HST / HDT (North America DST) +XX +515248-1763929 America/Adak western Aleutians in Alaska ("HST/HDT") +# +# -09:30 +XX -0900-13930 Pacific/Marquesas Marquesas +# +# -09 +XX -2308-13457 Pacific/Gambier Gambier +# +# -09/-08 - AKST/AKDT (North America DST) +XX +611305-1495401 America/Anchorage most of Alaska ("AKST/AKDT") +# +# -08 +XX -2504-13005 Pacific/Pitcairn Pitcairn +# +# -08/-07 - PST/PDT (North America DST) +XX +340308-1181434 America/Los_Angeles Pacific ("PST/PDT") - US & Canada; Mexico near US border +# +# -07 - MST +XX +332654-1120424 America/Phoenix Mountain Standard ("MST") - Arizona; western Mexico; Yukon +# +# -07/-06 - MST/MDT (North America DST) +XX +394421-1045903 America/Denver Mountain ("MST/MDT") - US & Canada; Mexico near US border +# +# -06 +XX -0054-08936 Pacific/Galapagos Galápagos +# +# -06 - CST +XX +1924-09909 America/Mexico_City Central Standard ("CST") - Saskatchewan; central Mexico; Central America +# +# -06/-05 (Chile DST) +XX -2709-10926 Pacific/Easter Easter Island +# +# -06/-05 - CST/CDT (North America DST) +XX +415100-0873900 America/Chicago Central ("CST/CDT") - US & Canada; Mexico near US border +# +# -05 +XX -1203-07703 America/Lima eastern South America +# +# -05 - EST +XX +175805-0764736 America/Jamaica Eastern Standard ("EST") - Caymans; Jamaica; eastern Mexico; Panama +# +# -05/-04 - CST/CDT (Cuba DST) +XX +2308-08222 America/Havana Cuba +# +# -05/-04 - EST/EDT (North America DST) +XX +404251-0740023 America/New_York Eastern ("EST/EDT") - US & Canada +# +# -04 +XX +1030-06656 America/Caracas western South America +# +# -04 - AST +XX +1828-06954 America/Santo_Domingo Atlantic Standard ("AST") - eastern Caribbean +# +# -04/-03 (Chile DST) +XX -3327-07040 America/Santiago most of Chile +# +# -04/-03 - AST/ADT (North America DST) +XX +4439-06336 America/Halifax Atlantic ("AST/ADT") - Canada; Bermuda +# +# -03:30/-02:30 - NST/NDT (North America DST) +XX +4734-05243 America/St_Johns Newfoundland ("NST/NDT") +# +# -03 +XX -2332-04637 America/Sao_Paulo eastern and southern South America +# +# -03/-02 (North America DST) +XX +4703-05620 America/Miquelon St Pierre & Miquelon +# +# -02 +XX -0351-03225 America/Noronha Fernando de Noronha; South Georgia +# +# -02/-01 (EU DST) +XX +6411-05144 America/Nuuk most of Greenland +# +# -01 +XX +1455-02331 Atlantic/Cape_Verde Cape Verde +# +# -01/+00 (EU DST) +XX +3744-02540 Atlantic/Azores Azores +# +# +00 - GMT +XX +0519-00402 Africa/Abidjan far western Africa; Iceland ("GMT") +# +# +00/+01 - GMT/BST (EU DST) +XX +513030-0000731 Europe/London United Kingdom ("GMT/BST") +# +# +00/+01 - WET/WEST (EU DST) +XX +3843-00908 Europe/Lisbon western Europe ("WET/WEST") +# +# +00/+02 - Troll DST +XX -720041+0023206 Antarctica/Troll Troll Station in Antarctica +# +# +01 - CET +XX +3647+00303 Africa/Algiers Algeria, Tunisia ("CET") +# +# +01 - WAT +XX +0627+00324 Africa/Lagos western Africa ("WAT") +# +# +01/+00 - IST/GMT (EU DST in reverse) +XX +5320-00615 Europe/Dublin Ireland ("IST/GMT") +# +# +01/+00 - (Morocco DST) +XX +3339-00735 Africa/Casablanca Morocco +# +# +01/+02 - CET/CEST (EU DST) +XX +4852+00220 Europe/Paris central Europe ("CET/CEST") +# +# +02 - CAT +XX -2558+03235 Africa/Maputo central Africa ("CAT") +# +# +02 - EET +XX +3254+01311 Africa/Tripoli Libya; Kaliningrad ("EET") +# +# +02 - SAST +XX -2615+02800 Africa/Johannesburg southern Africa ("SAST") +# +# +02/+03 - EET/EEST (EU DST) +XX +3758+02343 Europe/Athens eastern Europe ("EET/EEST") +# +# +02/+03 - EET/EEST (Egypt DST) +XX +3003+03115 Africa/Cairo Egypt +# +# +02/+03 - EET/EEST (Lebanon DST) +XX +3353+03530 Asia/Beirut Lebanon +# +# +02/+03 - EET/EEST (Moldova DST) +XX +4700+02850 Europe/Chisinau Moldova +# +# +02/+03 - EET/EEST (Palestine DST) +XX +3130+03428 Asia/Gaza Palestine +# +# +02/+03 - IST/IDT (Israel DST) +XX +314650+0351326 Asia/Jerusalem Israel +# +# +03 +XX +4101+02858 Europe/Istanbul Near East; Belarus +# +# +03 - EAT +XX -0117+03649 Africa/Nairobi eastern Africa ("EAT") +# +# +03 - MSK +XX +554521+0373704 Europe/Moscow Moscow ("MSK") +# +# +03:30 +XX +3540+05126 Asia/Tehran Iran +# +# +04 +XX +2518+05518 Asia/Dubai Russia; Caucasus; Persian Gulf; Seychelles; Réunion +# +# +04:30 +XX +3431+06912 Asia/Kabul Afghanistan +# +# +05 +XX +4120+06918 Asia/Tashkent Russia; Kazakhstan; Tajikistan; Turkmenistan; Uzbekistan; Maldives +# +# +05 - PKT +XX +2452+06703 Asia/Karachi Pakistan ("PKT") +# +# +05:30 +XX +0656+07951 Asia/Colombo Sri Lanka +# +# +05:30 - IST +XX +2232+08822 Asia/Kolkata India ("IST") +# +# +05:45 +XX +2743+08519 Asia/Kathmandu Nepal +# +# +06 +XX +2343+09025 Asia/Dhaka Russia; Kyrgyzstan; Bhutan; Bangladesh; Chagos +# +# +06:30 +XX +1647+09610 Asia/Yangon Myanmar; Cocos +# +# +07 +XX +1345+10031 Asia/Bangkok Russia; Indochina; Christmas Island +# +# +07 - WIB +XX -0610+10648 Asia/Jakarta Indonesia ("WIB") +# +# +08 +XX +0117+10351 Asia/Singapore Russia; Brunei; Malaysia; Singapore; Concordia +# +# +08 - AWST +XX -3157+11551 Australia/Perth Western Australia ("AWST") +# +# +08 - CST +XX +3114+12128 Asia/Shanghai China ("CST") +# +# +08 - HKT +XX +2217+11409 Asia/Hong_Kong Hong Kong ("HKT") +# +# +08 - PHT +XX +143512+1205804 Asia/Manila Philippines ("PHT") +# +# +08 - WITA +XX -0507+11924 Asia/Makassar Indonesia ("WITA") +# +# +08:45 +XX -3143+12852 Australia/Eucla Eucla +# +# +09 +XX +5203+11328 Asia/Chita Russia; Palau; East Timor +# +# +09 - JST +XX +353916+1394441 Asia/Tokyo Japan ("JST"); Eyre Bird Observatory +# +# +09 - KST +XX +3733+12658 Asia/Seoul Korea ("KST") +# +# +09 - WIT +XX -0232+14042 Asia/Jayapura Indonesia ("WIT") +# +# +09:30 - ACST +XX -1228+13050 Australia/Darwin Northern Territory ("ACST") +# +# +09:30/+10:30 - ACST/ACDT (Australia DST) +XX -3455+13835 Australia/Adelaide South Australia ("ACST/ACDT") +# +# +10 +XX +4310+13156 Asia/Vladivostok Russia; Yap; Chuuk; Papua New Guinea; Dumont d'Urville +# +# +10 - AEST +XX -2728+15302 Australia/Brisbane Queensland ("AEST") +# +# +10 - ChST +XX +1328+14445 Pacific/Guam Mariana Islands ("ChST") +# +# +10/+11 - AEST/AEDT (Australia DST) +XX -3352+15113 Australia/Sydney southeast Australia ("AEST/AEDT") +# +# +10:30/+11 +XX -3133+15905 Australia/Lord_Howe Lord Howe Island +# +# +11 +XX -0613+15534 Pacific/Bougainville Russia; Kosrae; Bougainville; Solomons +# +# +11/+12 (Australia DST) +XX -2903+16758 Pacific/Norfolk Norfolk Island +# +# +12 +XX +5301+15839 Asia/Kamchatka Russia; Tuvalu; Fiji; etc. +# +# +12/+13 (New Zealand DST) +XX -3652+17446 Pacific/Auckland New Zealand ("NZST/NZDT") +# +# +12:45/+13:45 (Chatham DST) +XX -4357-17633 Pacific/Chatham Chatham Islands +# +# +13 +XX -210800-1751200 Pacific/Tongatapu Kanton; Tokelau; Samoa (western); Tonga +# +# +14 +XX +0152-15720 Pacific/Kiritimati Kiritimati diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zones b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zones new file mode 100644 index 0000000000000000000000000000000000000000..d4c3ef55638268a2ab4d17f7db071075db94747d --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/tzdata/zones @@ -0,0 +1,598 @@ +Africa/Abidjan +Africa/Algiers +Africa/Bissau +Africa/Cairo +Africa/Casablanca +Africa/Ceuta +Africa/El_Aaiun +Africa/Johannesburg +Africa/Juba +Africa/Khartoum +Africa/Lagos +Africa/Maputo +Africa/Monrovia +Africa/Nairobi +Africa/Ndjamena +Africa/Sao_Tome +Africa/Tripoli +Africa/Tunis +Africa/Windhoek +America/Adak +America/Anchorage +America/Araguaina +America/Argentina/Buenos_Aires +America/Argentina/Catamarca +America/Argentina/Cordoba +America/Argentina/Jujuy +America/Argentina/La_Rioja +America/Argentina/Mendoza +America/Argentina/Rio_Gallegos +America/Argentina/Salta +America/Argentina/San_Juan +America/Argentina/San_Luis +America/Argentina/Tucuman +America/Argentina/Ushuaia +America/Asuncion +America/Bahia +America/Bahia_Banderas +America/Barbados +America/Belem +America/Belize +America/Boa_Vista +America/Bogota +America/Boise +America/Cambridge_Bay +America/Campo_Grande +America/Cancun +America/Caracas +America/Cayenne +America/Chicago +America/Chihuahua +America/Ciudad_Juarez +America/Costa_Rica +America/Coyhaique +America/Cuiaba +America/Danmarkshavn +America/Dawson +America/Dawson_Creek +America/Denver +America/Detroit +America/Edmonton +America/Eirunepe +America/El_Salvador +America/Fort_Nelson +America/Fortaleza +America/Glace_Bay +America/Goose_Bay +America/Grand_Turk +America/Guatemala +America/Guayaquil +America/Guyana +America/Halifax +America/Havana +America/Hermosillo +America/Indiana/Indianapolis +America/Indiana/Knox +America/Indiana/Marengo +America/Indiana/Petersburg +America/Indiana/Tell_City +America/Indiana/Vevay +America/Indiana/Vincennes +America/Indiana/Winamac +America/Inuvik +America/Iqaluit +America/Jamaica +America/Juneau +America/Kentucky/Louisville +America/Kentucky/Monticello +America/La_Paz +America/Lima +America/Los_Angeles +America/Maceio +America/Managua +America/Manaus +America/Martinique +America/Matamoros +America/Mazatlan +America/Menominee +America/Merida +America/Metlakatla +America/Mexico_City +America/Miquelon +America/Moncton +America/Monterrey +America/Montevideo +America/New_York +America/Nome +America/Noronha +America/North_Dakota/Beulah +America/North_Dakota/Center +America/North_Dakota/New_Salem +America/Nuuk +America/Ojinaga +America/Panama +America/Paramaribo +America/Phoenix +America/Port-au-Prince +America/Porto_Velho +America/Puerto_Rico +America/Punta_Arenas +America/Rankin_Inlet +America/Recife +America/Regina +America/Resolute +America/Rio_Branco +America/Santarem +America/Santiago +America/Santo_Domingo +America/Sao_Paulo +America/Scoresbysund +America/Sitka +America/St_Johns +America/Swift_Current +America/Tegucigalpa +America/Thule +America/Tijuana +America/Toronto +America/Vancouver +America/Whitehorse +America/Winnipeg +America/Yakutat +Antarctica/Casey +Antarctica/Davis +Antarctica/Macquarie +Antarctica/Mawson +Antarctica/Palmer +Antarctica/Rothera +Antarctica/Troll +Antarctica/Vostok +Asia/Almaty +Asia/Amman +Asia/Anadyr +Asia/Aqtau +Asia/Aqtobe +Asia/Ashgabat +Asia/Atyrau +Asia/Baghdad +Asia/Baku +Asia/Bangkok +Asia/Barnaul +Asia/Beirut +Asia/Bishkek +Asia/Chita +Asia/Colombo +Asia/Damascus +Asia/Dhaka +Asia/Dili +Asia/Dubai +Asia/Dushanbe +Asia/Famagusta +Asia/Gaza +Asia/Hebron +Asia/Ho_Chi_Minh +Asia/Hong_Kong +Asia/Hovd +Asia/Irkutsk +Asia/Jakarta +Asia/Jayapura +Asia/Jerusalem +Asia/Kabul +Asia/Kamchatka +Asia/Karachi +Asia/Kathmandu +Asia/Khandyga +Asia/Kolkata +Asia/Krasnoyarsk +Asia/Kuching +Asia/Macau +Asia/Magadan +Asia/Makassar +Asia/Manila +Asia/Nicosia +Asia/Novokuznetsk +Asia/Novosibirsk +Asia/Omsk +Asia/Oral +Asia/Pontianak +Asia/Pyongyang +Asia/Qatar +Asia/Qostanay +Asia/Qyzylorda +Asia/Riyadh +Asia/Sakhalin +Asia/Samarkand +Asia/Seoul +Asia/Shanghai +Asia/Singapore +Asia/Srednekolymsk +Asia/Taipei +Asia/Tashkent +Asia/Tbilisi +Asia/Tehran +Asia/Thimphu +Asia/Tokyo +Asia/Tomsk +Asia/Ulaanbaatar +Asia/Urumqi +Asia/Ust-Nera +Asia/Vladivostok +Asia/Yakutsk +Asia/Yangon +Asia/Yekaterinburg +Asia/Yerevan +Atlantic/Azores +Atlantic/Bermuda +Atlantic/Canary +Atlantic/Cape_Verde +Atlantic/Faroe +Atlantic/Madeira +Atlantic/South_Georgia +Atlantic/Stanley +Australia/Adelaide +Australia/Brisbane +Australia/Broken_Hill +Australia/Darwin +Australia/Eucla +Australia/Hobart +Australia/Lindeman +Australia/Lord_Howe +Australia/Melbourne +Australia/Perth +Australia/Sydney +Etc/GMT +Etc/GMT+1 +Etc/GMT+10 +Etc/GMT+11 +Etc/GMT+12 +Etc/GMT+2 +Etc/GMT+3 +Etc/GMT+4 +Etc/GMT+5 +Etc/GMT+6 +Etc/GMT+7 +Etc/GMT+8 +Etc/GMT+9 +Etc/GMT-1 +Etc/GMT-10 +Etc/GMT-11 +Etc/GMT-12 +Etc/GMT-13 +Etc/GMT-14 +Etc/GMT-2 +Etc/GMT-3 +Etc/GMT-4 +Etc/GMT-5 +Etc/GMT-6 +Etc/GMT-7 +Etc/GMT-8 +Etc/GMT-9 +Etc/UTC +Europe/Andorra +Europe/Astrakhan +Europe/Athens +Europe/Belgrade +Europe/Berlin +Europe/Brussels +Europe/Bucharest +Europe/Budapest +Europe/Chisinau +Europe/Dublin +Europe/Gibraltar +Europe/Helsinki +Europe/Istanbul +Europe/Kaliningrad +Europe/Kirov +Europe/Kyiv +Europe/Lisbon +Europe/London +Europe/Madrid +Europe/Malta +Europe/Minsk +Europe/Moscow +Europe/Paris +Europe/Prague +Europe/Riga +Europe/Rome +Europe/Samara +Europe/Saratov +Europe/Simferopol +Europe/Sofia +Europe/Tallinn +Europe/Tirane +Europe/Ulyanovsk +Europe/Vienna +Europe/Vilnius +Europe/Volgograd +Europe/Warsaw +Europe/Zurich +Factory +Indian/Chagos +Indian/Maldives +Indian/Mauritius +Pacific/Apia +Pacific/Auckland +Pacific/Bougainville +Pacific/Chatham +Pacific/Easter +Pacific/Efate +Pacific/Fakaofo +Pacific/Fiji +Pacific/Galapagos +Pacific/Gambier +Pacific/Guadalcanal +Pacific/Guam +Pacific/Honolulu +Pacific/Kanton +Pacific/Kiritimati +Pacific/Kosrae +Pacific/Kwajalein +Pacific/Marquesas +Pacific/Nauru +Pacific/Niue +Pacific/Norfolk +Pacific/Noumea +Pacific/Pago_Pago +Pacific/Palau +Pacific/Pitcairn +Pacific/Port_Moresby +Pacific/Rarotonga +Pacific/Tahiti +Pacific/Tarawa +Pacific/Tongatapu +GMT +Australia/ACT +Australia/LHI +Australia/NSW +Australia/North +Australia/Queensland +Australia/South +Australia/Tasmania +Australia/Victoria +Australia/West +Australia/Yancowinna +Brazil/Acre +Brazil/DeNoronha +Brazil/East +Brazil/West +CET +CST6CDT +Canada/Atlantic +Canada/Central +Canada/Eastern +Canada/Mountain +Canada/Newfoundland +Canada/Pacific +Canada/Saskatchewan +Canada/Yukon +Chile/Continental +Chile/EasterIsland +Cuba +EET +EST +EST5EDT +Egypt +Eire +Etc/GMT+0 +Etc/GMT-0 +Etc/GMT0 +Etc/Greenwich +Etc/UCT +Etc/Universal +Etc/Zulu +GB +GB-Eire +GMT+0 +GMT-0 +GMT0 +Greenwich +Hongkong +Iceland +Iran +Israel +Jamaica +Japan +Kwajalein +Libya +MET +MST +MST7MDT +Mexico/BajaNorte +Mexico/BajaSur +Mexico/General +NZ +NZ-CHAT +Navajo +PRC +Poland +Portugal +ROC +ROK +Singapore +Turkey +UCT +US/Alaska +US/Aleutian +US/Arizona +US/Central +US/East-Indiana +US/Eastern +US/Hawaii +US/Indiana-Starke +US/Michigan +US/Mountain +US/Pacific +US/Samoa +UTC +Universal +W-SU +Zulu +America/Buenos_Aires +America/Catamarca +America/Cordoba +America/Indianapolis +America/Jujuy +America/Knox_IN +America/Louisville +America/Mendoza +America/Virgin +Pacific/Samoa +Africa/Accra +Africa/Addis_Ababa +Africa/Asmara +Africa/Bamako +Africa/Bangui +Africa/Banjul +Africa/Blantyre +Africa/Brazzaville +Africa/Bujumbura +Africa/Conakry +Africa/Dakar +Africa/Dar_es_Salaam +Africa/Djibouti +Africa/Douala +Africa/Freetown +Africa/Gaborone +Africa/Harare +Africa/Kampala +Africa/Kigali +Africa/Kinshasa +Africa/Libreville +Africa/Lome +Africa/Luanda +Africa/Lubumbashi +Africa/Lusaka +Africa/Malabo +Africa/Maseru +Africa/Mbabane +Africa/Mogadishu +Africa/Niamey +Africa/Nouakchott +Africa/Ouagadougou +Africa/Porto-Novo +America/Anguilla +America/Antigua +America/Aruba +America/Atikokan +America/Blanc-Sablon +America/Cayman +America/Creston +America/Curacao +America/Dominica +America/Grenada +America/Guadeloupe +America/Kralendijk +America/Lower_Princes +America/Marigot +America/Montserrat +America/Nassau +America/Port_of_Spain +America/St_Barthelemy +America/St_Kitts +America/St_Lucia +America/St_Thomas +America/St_Vincent +America/Tortola +Antarctica/DumontDUrville +Antarctica/McMurdo +Antarctica/Syowa +Arctic/Longyearbyen +Asia/Aden +Asia/Bahrain +Asia/Brunei +Asia/Kuala_Lumpur +Asia/Kuwait +Asia/Muscat +Asia/Phnom_Penh +Asia/Vientiane +Atlantic/Reykjavik +Atlantic/St_Helena +Europe/Amsterdam +Europe/Bratislava +Europe/Busingen +Europe/Copenhagen +Europe/Guernsey +Europe/Isle_of_Man +Europe/Jersey +Europe/Ljubljana +Europe/Luxembourg +Europe/Mariehamn +Europe/Monaco +Europe/Oslo +Europe/Podgorica +Europe/San_Marino +Europe/Sarajevo +Europe/Skopje +Europe/Stockholm +Europe/Vaduz +Europe/Vatican +Europe/Zagreb +Indian/Antananarivo +Indian/Christmas +Indian/Cocos +Indian/Comoro +Indian/Kerguelen +Indian/Mahe +Indian/Mayotte +Indian/Reunion +Pacific/Chuuk +Pacific/Funafuti +Pacific/Majuro +Pacific/Midway +Pacific/Pohnpei +Pacific/Saipan +Pacific/Wake +Pacific/Wallis +Africa/Timbuktu +America/Argentina/ComodRivadavia +America/Atka +America/Coral_Harbour +America/Ensenada +America/Fort_Wayne +America/Montreal +America/Nipigon +America/Pangnirtung +America/Porto_Acre +America/Rainy_River +America/Rosario +America/Santa_Isabel +America/Shiprock +America/Thunder_Bay +America/Yellowknife +Antarctica/South_Pole +Asia/Choibalsan +Asia/Chongqing +Asia/Harbin +Asia/Kashgar +Asia/Tel_Aviv +Atlantic/Jan_Mayen +Australia/Canberra +Australia/Currie +Europe/Belfast +Europe/Tiraspol +Europe/Uzhgorod +Europe/Zaporozhye +Pacific/Enderbury +Pacific/Johnston +Pacific/Yap +WET +Africa/Asmera +America/Godthab +Asia/Ashkhabad +Asia/Calcutta +Asia/Chungking +Asia/Dacca +Asia/Istanbul +Asia/Katmandu +Asia/Macao +Asia/Rangoon +Asia/Saigon +Asia/Thimbu +Asia/Ujung_Pandang +Asia/Ulan_Bator +Atlantic/Faeroe +Europe/Kiev +Europe/Nicosia +HST +PST8PDT +Pacific/Ponape +Pacific/Truk